1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
|
use clap::Args;
use std::path::{Path, PathBuf};
#[derive(Args)]
pub struct ValidateArgs {
/// Path to composer.json file
pub file: Option<String>,
/// Skips checks for non-essential issues
#[arg(long)]
pub no_check_all: bool,
/// Validates the lock file
#[arg(long)]
pub check_lock: bool,
/// Skips lock file validation
#[arg(long)]
pub no_check_lock: bool,
/// Skips publish-related checks
#[arg(long)]
pub no_check_publish: bool,
/// Skips version constraint checks
#[arg(long)]
pub no_check_version: bool,
/// Also validate all dependencies
#[arg(short = 'A', long)]
pub with_dependencies: bool,
/// Return a non-zero exit code on warnings as well as errors
#[arg(long)]
pub strict: bool,
}
// ─── Result accumulator ─────────────────────────────────────────────────────
struct ValidationResult {
errors: Vec<String>,
publish_errors: Vec<String>,
warnings: Vec<String>,
}
impl ValidationResult {
fn new() -> Self {
Self {
errors: Vec::new(),
publish_errors: Vec::new(),
warnings: Vec::new(),
}
}
fn has_errors(&self) -> bool {
!self.errors.is_empty()
}
fn has_publish_errors(&self) -> bool {
!self.publish_errors.is_empty()
}
fn has_warnings(&self) -> bool {
!self.warnings.is_empty()
}
}
// ─── Entry point ─────────────────────────────────────────────────────────────
pub async fn execute(
args: &ValidateArgs,
cli: &super::Cli,
console: &mozart_core::console::Console,
) -> anyhow::Result<()> {
let working_dir = match &cli.working_dir {
Some(dir) => PathBuf::from(dir),
None => std::env::current_dir()?,
};
// Determine which file to validate
let file = match &args.file {
Some(f) => PathBuf::from(f),
None => working_dir.join("composer.json"),
};
// Validate-specific exit codes (matching Composer's behavior):
// 3 = file not found or not readable
// 2 = JSON parse error
const VALIDATE_FILE_ERROR: i32 = 3;
const VALIDATE_JSON_ERROR: i32 = 2;
// Check file exists
if !file.exists() {
return Err(mozart_core::exit_code::bail(
VALIDATE_FILE_ERROR,
format!("{} not found.", file.display()),
));
}
// Read file content
let content = match std::fs::read_to_string(&file) {
Ok(c) => c,
Err(_) => {
return Err(mozart_core::exit_code::bail(
VALIDATE_FILE_ERROR,
format!("{} is not readable.", file.display()),
));
}
};
// Parse JSON syntax
let json_value: serde_json::Value = match serde_json::from_str(&content) {
Ok(v) => v,
Err(e) => {
return Err(mozart_core::exit_code::bail(
VALIDATE_JSON_ERROR,
format!("{} does not contain valid JSON: {e}", file.display()),
));
}
};
// Run manifest validations
let mut result = ValidationResult::new();
validate_manifest(&json_value, args, &mut result);
// Check lock file freshness
let mut lock_errors: Vec<String> = Vec::new();
let check_lock = !args.no_check_lock || args.check_lock;
if check_lock {
check_lock_freshness(&content, &file, &mut lock_errors);
}
// Output results
let check_publish = !args.no_check_publish;
output_result(&file, &result, check_publish, check_lock, &lock_errors);
// Stub for --with-dependencies
if args.with_dependencies {
console.info("The --with-dependencies option is not yet implemented");
}
let exit_code = compute_exit_code(
&result,
&lock_errors,
check_publish,
check_lock,
args.strict,
);
if exit_code != 0 {
return Err(mozart_core::exit_code::bail_silent(exit_code));
}
Ok(())
}
// ─── Manifest validation ─────────────────────────────────────────────────────
fn validate_manifest(
manifest: &serde_json::Value,
args: &ValidateArgs,
result: &mut ValidationResult,
) {
let obj = match manifest.as_object() {
Some(o) => o,
None => {
result
.errors
.push("composer.json must be a JSON object".to_string());
return;
}
};
check_name(obj, result);
check_license(obj, result);
if !args.no_check_version {
check_version_field(obj, result);
}
check_package_type(obj, result);
check_require_overlap(obj, result);
check_provide_replace_overlap(obj, result);
check_commit_references(obj, result);
check_empty_psr_prefixes(obj, result);
check_minimum_stability(obj, result);
}
// ─── Individual checks ───────────────────────────────────────────────────────
/// Check the "name" field: must be present (for published packages) and lowercase.
fn check_name(obj: &serde_json::Map<String, serde_json::Value>, result: &mut ValidationResult) {
match obj.get("name").and_then(|v| v.as_str()) {
None => {
result.publish_errors.push(
"The name property is not set. This is required for published packages."
.to_string(),
);
}
Some(name) => {
// Uppercase characters are a publish error
if name.chars().any(|c| c.is_ascii_uppercase()) {
let suggested = name.to_lowercase();
result.publish_errors.push(format!(
"Name \"{name}\" does not match the best practice (e.g. lower-cased/with-dashes). \
We suggest using \"{suggested}\" instead. As such you will not be able to submit it to Packagist."
));
}
// Must contain a slash (vendor/package format)
if !name.is_empty()
&& !mozart_core::validation::validate_package_name(name)
&& !name.contains('/')
{
result.errors.push(format!(
"The name \"{name}\" is invalid, it should be in the format \"vendor/package\"."
));
}
}
}
}
/// Check the "license" field: warn if absent.
fn check_license(obj: &serde_json::Map<String, serde_json::Value>, result: &mut ValidationResult) {
if obj.get("license").is_none() {
result.warnings.push(
"No license specified, it is recommended to do so. \
For closed-source software you may use \"proprietary\" as license."
.to_string(),
);
}
}
/// Warn if the "version" field is present.
fn check_version_field(
obj: &serde_json::Map<String, serde_json::Value>,
result: &mut ValidationResult,
) {
if obj.contains_key("version") {
result.warnings.push(
"The version field is present, it is recommended to leave it out \
if the package is published on Packagist."
.to_string(),
);
}
}
/// Warn if the package type is the deprecated "composer-installer".
fn check_package_type(
obj: &serde_json::Map<String, serde_json::Value>,
result: &mut ValidationResult,
) {
if let Some(pkg_type) = obj.get("type").and_then(|v| v.as_str())
&& pkg_type == "composer-installer"
{
result.warnings.push(
"The package type 'composer-installer' is deprecated. \
Please distribute your custom installers as plugins from now on. \
See https://getcomposer.org/doc/articles/plugins.md for plugin documentation."
.to_string(),
);
}
}
/// Warn if the same package appears in both require and require-dev.
fn check_require_overlap(
obj: &serde_json::Map<String, serde_json::Value>,
result: &mut ValidationResult,
) {
let require = obj.get("require").and_then(|v| v.as_object());
let require_dev = obj.get("require-dev").and_then(|v| v.as_object());
if let (Some(req), Some(req_dev)) = (require, require_dev) {
let mut overlaps: Vec<&str> = Vec::new();
for key in req.keys() {
if req_dev.contains_key(key) {
overlaps.push(key.as_str());
}
}
if !overlaps.is_empty() {
let plural = if overlaps.len() > 1 { "are" } else { "is" };
result.warnings.push(format!(
"{} {plural} required both in require and require-dev, \
this can lead to unexpected behavior",
overlaps.join(", "),
));
}
}
}
/// Warn if a package listed in provide/replace is also in require/require-dev.
fn check_provide_replace_overlap(
obj: &serde_json::Map<String, serde_json::Value>,
result: &mut ValidationResult,
) {
for link_type in &["provide", "replace"] {
if let Some(links) = obj.get(*link_type).and_then(|v| v.as_object()) {
for require_type in &["require", "require-dev"] {
if let Some(requires) = obj.get(*require_type).and_then(|v| v.as_object()) {
for provide_name in links.keys() {
if requires.contains_key(provide_name) {
result.warnings.push(format!(
"The package {provide_name} in {require_type} is also listed in \
{link_type} which satisfies the requirement. Remove it from \
{link_type} if you wish to install it."
));
}
}
}
}
}
}
}
/// Warn about version constraints containing '#' (commit references).
fn check_commit_references(
obj: &serde_json::Map<String, serde_json::Value>,
result: &mut ValidationResult,
) {
for section in &["require", "require-dev"] {
if let Some(deps) = obj.get(*section).and_then(|v| v.as_object()) {
for (package, version) in deps {
if let Some(v) = version.as_str()
&& v.contains('#')
{
result.warnings.push(format!(
"The package \"{package}\" is pointing to a commit-ref, \
this is bad practice and can cause unforeseen issues."
));
}
}
}
}
}
/// Warn about empty PSR-0/PSR-4 namespace prefixes (performance impact).
fn check_empty_psr_prefixes(
obj: &serde_json::Map<String, serde_json::Value>,
result: &mut ValidationResult,
) {
if let Some(autoload) = obj.get("autoload").and_then(|v| v.as_object()) {
if let Some(psr0) = autoload.get("psr-0").and_then(|v| v.as_object())
&& psr0.contains_key("")
{
result.warnings.push(
"Defining autoload.psr-0 with an empty namespace prefix is a bad idea \
for performance"
.to_string(),
);
}
if let Some(psr4) = autoload.get("psr-4").and_then(|v| v.as_object())
&& psr4.contains_key("")
{
result.warnings.push(
"Defining autoload.psr-4 with an empty namespace prefix is a bad idea \
for performance"
.to_string(),
);
}
}
}
/// Check minimum-stability value if present.
fn check_minimum_stability(
obj: &serde_json::Map<String, serde_json::Value>,
result: &mut ValidationResult,
) {
if let Some(stability) = obj.get("minimum-stability").and_then(|v| v.as_str())
&& !mozart_core::validation::validate_stability(stability)
{
result.errors.push(format!(
"The minimum-stability \"{stability}\" is invalid. \
Must be one of: dev, alpha, beta, rc, stable."
));
}
}
// ─── Lock file freshness ─────────────────────────────────────────────────────
fn check_lock_freshness(
composer_json_content: &str,
composer_json_path: &Path,
lock_errors: &mut Vec<String>,
) {
let lock_path = composer_json_path
.parent()
.unwrap_or(Path::new("."))
.join("composer.lock");
if !lock_path.exists() {
// No lock file is not an error for validate — it's optional
return;
}
match mozart_registry::lockfile::LockFile::read_from_file(&lock_path) {
Ok(lock) => {
if !lock.is_fresh(composer_json_content) {
lock_errors.push(
"- The lock file is not up to date with the latest changes in composer.json, \
it is recommended that you run `mozart update` or `mozart update <package name>`."
.to_string(),
);
}
}
Err(e) => {
lock_errors.push(format!("- The lock file could not be read: {e}"));
}
}
}
// ─── Output ──────────────────────────────────────────────────────────────────
fn output_result(
file: &Path,
result: &ValidationResult,
check_publish: bool,
check_lock: bool,
lock_errors: &[String],
) {
let name = file.display().to_string();
// Print header message
if result.has_errors() {
eprintln!(
"{}",
mozart_core::console::error(&format!(
"{name} is invalid, the following errors/warnings were found:"
))
);
} else if result.has_publish_errors() && check_publish {
eprintln!(
"{}",
mozart_core::console::info(&format!(
"{name} is valid for simple usage with Composer but has"
))
);
eprintln!(
"{}",
mozart_core::console::info(
"strict errors that make it unable to be published as a package"
)
);
eprintln!(
"{}",
mozart_core::console::warning(
"See https://getcomposer.org/doc/04-schema.md for details on the schema"
)
);
} else if result.has_warnings() {
eprintln!(
"{}",
mozart_core::console::info(&format!("{name} is valid, but with a few warnings"))
);
eprintln!(
"{}",
mozart_core::console::warning(
"See https://getcomposer.org/doc/04-schema.md for details on the schema"
)
);
} else if !lock_errors.is_empty() {
let kind = if check_lock { "errors" } else { "warnings" };
println!(
"{}",
mozart_core::console::info(&format!(
"{name} is valid but your composer.lock has some {kind}"
))
);
} else {
println!(
"{}",
mozart_core::console::info(&format!("{name} is valid"))
);
}
// Collect error and warning message lines
let mut all_errors: Vec<String> = Vec::new();
let mut all_warnings: Vec<String> = Vec::new();
if !result.errors.is_empty() {
all_errors.push("# General errors".to_string());
for e in &result.errors {
all_errors.push(format!("- {e}"));
}
}
if !result.warnings.is_empty() {
all_warnings.push("# General warnings".to_string());
for w in &result.warnings {
all_warnings.push(format!("- {w}"));
}
}
// Publish errors: shown as errors if check_publish is true
if check_publish && !result.publish_errors.is_empty() {
all_errors.push("# Publish errors".to_string());
for e in &result.publish_errors {
all_errors.push(format!("- {e}"));
}
}
// Lock errors: shown as errors or warnings depending on check_lock
if !lock_errors.is_empty() {
if check_lock {
all_errors.push("# Lock file errors".to_string());
all_errors.extend_from_slice(lock_errors);
} else {
all_warnings.push("# Lock file warnings".to_string());
all_warnings.extend_from_slice(lock_errors);
}
}
// Print errors
for msg in &all_errors {
if msg.starts_with('#') {
eprintln!("{}", mozart_core::console::error(msg));
} else {
eprintln!("{msg}");
}
}
// Print warnings
for msg in &all_warnings {
if msg.starts_with('#') {
eprintln!("{}", mozart_core::console::warning(msg));
} else {
eprintln!("{msg}");
}
}
}
// ─── Exit code ───────────────────────────────────────────────────────────────
/// Compute the exit code following Composer's convention:
/// 0 = valid, 1 = warnings (only with --strict), 2 = errors, 3 = file unreadable (handled earlier)
fn compute_exit_code(
result: &ValidationResult,
lock_errors: &[String],
check_publish: bool,
check_lock: bool,
strict: bool,
) -> i32 {
let has_errors = result.has_errors()
|| (check_publish && result.has_publish_errors())
|| (check_lock && !lock_errors.is_empty());
if has_errors {
return 2;
}
let has_warnings = result.has_warnings() || (!check_lock && !lock_errors.is_empty());
if strict && has_warnings {
return 1;
}
0
}
// ─── Tests ───────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
fn make_args() -> ValidateArgs {
ValidateArgs {
file: None,
no_check_all: false,
check_lock: false,
no_check_lock: false,
no_check_publish: false,
no_check_version: false,
with_dependencies: false,
strict: false,
}
}
fn parse_and_validate(json: &str, args: &ValidateArgs) -> ValidationResult {
let value: serde_json::Value = serde_json::from_str(json).unwrap();
let mut result = ValidationResult::new();
validate_manifest(&value, args, &mut result);
result
}
// ── check_name ─────────────────────────────────────────────────────────
#[test]
fn test_validate_missing_name_is_publish_error() {
let json = r#"{"require": {"php": ">=8.1"}, "license": "MIT"}"#;
let result = parse_and_validate(json, &make_args());
assert!(result.errors.is_empty());
assert!(!result.publish_errors.is_empty());
assert!(result.publish_errors[0].contains("name property is not set"));
}
#[test]
fn test_validate_uppercase_name_publish_error() {
let json = r#"{"name": "Vendor/Package", "license": "MIT"}"#;
let result = parse_and_validate(json, &make_args());
assert!(!result.publish_errors.is_empty());
assert!(result.publish_errors[0].contains("does not match the best practice"));
assert!(result.publish_errors[0].contains("vendor/package"));
}
#[test]
fn test_validate_valid_name_no_publish_error() {
let json = r#"{"name": "vendor/package", "license": "MIT"}"#;
let result = parse_and_validate(json, &make_args());
assert!(result.publish_errors.is_empty());
assert!(result.errors.is_empty());
}
#[test]
fn test_validate_name_without_slash_is_error() {
let json = r#"{"name": "novendor", "license": "MIT"}"#;
let result = parse_and_validate(json, &make_args());
assert!(!result.errors.is_empty());
assert!(result.errors[0].contains("vendor/package"));
}
// ── check_license ──────────────────────────────────────────────────────
#[test]
fn test_validate_missing_license_warns() {
let json = r#"{"name": "vendor/pkg"}"#;
let result = parse_and_validate(json, &make_args());
assert!(!result.warnings.is_empty());
assert!(result.warnings.iter().any(|w| w.contains("No license")));
}
#[test]
fn test_validate_present_license_no_warning() {
let json = r#"{"name": "vendor/pkg", "license": "MIT"}"#;
let result = parse_and_validate(json, &make_args());
assert!(!result.warnings.iter().any(|w| w.contains("No license")));
}
// ── check_version_field ────────────────────────────────────────────────
#[test]
fn test_validate_version_field_warns() {
let json = r#"{"name": "vendor/pkg", "license": "MIT", "version": "1.0.0"}"#;
let result = parse_and_validate(json, &make_args());
assert!(result.warnings.iter().any(|w| w.contains("version field")));
}
#[test]
fn test_validate_no_check_version_suppresses_warning() {
let json = r#"{"name": "vendor/pkg", "license": "MIT", "version": "1.0.0"}"#;
let mut args = make_args();
args.no_check_version = true;
let result = parse_and_validate(json, &args);
assert!(!result.warnings.iter().any(|w| w.contains("version field")));
}
// ── check_package_type ─────────────────────────────────────────────────
#[test]
fn test_validate_deprecated_type_warns() {
let json = r#"{"name": "vendor/pkg", "license": "MIT", "type": "composer-installer"}"#;
let result = parse_and_validate(json, &make_args());
assert!(
result
.warnings
.iter()
.any(|w| w.contains("composer-installer"))
);
}
#[test]
fn test_validate_normal_type_no_warning() {
let json = r#"{"name": "vendor/pkg", "license": "MIT", "type": "library"}"#;
let result = parse_and_validate(json, &make_args());
assert!(
!result
.warnings
.iter()
.any(|w| w.contains("composer-installer"))
);
}
// ── check_require_overlap ──────────────────────────────────────────────
#[test]
fn test_validate_require_overlap_warns() {
let json = r#"{
"name": "vendor/pkg",
"license": "MIT",
"require": {"monolog/monolog": "^3.0"},
"require-dev": {"monolog/monolog": "^3.0"}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(
result
.warnings
.iter()
.any(|w| w.contains("required both in require and require-dev"))
);
}
#[test]
fn test_validate_no_require_overlap_no_warning() {
let json = r#"{
"name": "vendor/pkg",
"license": "MIT",
"require": {"monolog/monolog": "^3.0"},
"require-dev": {"phpunit/phpunit": "^10.0"}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(!result.warnings.iter().any(|w| w.contains("required both")));
}
// ── check_provide_replace_overlap ──────────────────────────────────────
#[test]
fn test_validate_provide_replace_overlap_warns() {
let json = r#"{
"name": "vendor/pkg",
"license": "MIT",
"require": {"psr/log": "^3.0"},
"provide": {"psr/log": "^3.0"}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(
result
.warnings
.iter()
.any(|w| w.contains("also listed in provide"))
);
}
// ── check_commit_references ────────────────────────────────────────────
#[test]
fn test_validate_commit_ref_warns() {
let json = r#"{
"name": "vendor/pkg",
"license": "MIT",
"require": {"foo/bar": "dev-main#abc123"}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(result.warnings.iter().any(|w| w.contains("commit-ref")));
}
#[test]
fn test_validate_normal_constraint_no_commit_warning() {
let json = r#"{
"name": "vendor/pkg",
"license": "MIT",
"require": {"foo/bar": "^1.0"}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(!result.warnings.iter().any(|w| w.contains("commit-ref")));
}
// ── check_empty_psr_prefixes ───────────────────────────────────────────
#[test]
fn test_validate_empty_psr4_prefix_warns() {
let json = r#"{
"name": "vendor/pkg",
"license": "MIT",
"autoload": {"psr-4": {"": "src/"}}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(result.warnings.iter().any(|w| w.contains("psr-4")));
}
#[test]
fn test_validate_empty_psr0_prefix_warns() {
let json = r#"{
"name": "vendor/pkg",
"license": "MIT",
"autoload": {"psr-0": {"": "src/"}}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(result.warnings.iter().any(|w| w.contains("psr-0")));
}
#[test]
fn test_validate_named_psr4_prefix_no_warning() {
let json = r#"{
"name": "vendor/pkg",
"license": "MIT",
"autoload": {"psr-4": {"Vendor\\Pkg\\": "src/"}}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(!result.warnings.iter().any(|w| w.contains("psr-4")));
}
// ── check_minimum_stability ────────────────────────────────────────────
#[test]
fn test_validate_invalid_stability_errors() {
let json = r#"{"name": "vendor/pkg", "license": "MIT", "minimum-stability": "invalid"}"#;
let result = parse_and_validate(json, &make_args());
assert!(!result.errors.is_empty());
assert!(
result
.errors
.iter()
.any(|e| e.contains("minimum-stability"))
);
}
#[test]
fn test_validate_valid_stability_no_error() {
for stab in &["dev", "alpha", "beta", "rc", "stable"] {
let json = format!(
r#"{{"name": "vendor/pkg", "license": "MIT", "minimum-stability": "{stab}"}}"#
);
let result = parse_and_validate(&json, &make_args());
assert!(
!result
.errors
.iter()
.any(|e| e.contains("minimum-stability")),
"stability '{stab}' should be valid"
);
}
}
// ── validate_manifest with non-object ──────────────────────────────────
#[test]
fn test_validate_non_object_json_errors() {
let value = serde_json::json!([1, 2, 3]);
let mut result = ValidationResult::new();
validate_manifest(&value, &make_args(), &mut result);
assert!(result.errors.iter().any(|e| e.contains("JSON object")));
}
// ── compute_exit_code ─────────────────────────────────────────────────
#[test]
fn test_compute_exit_code_no_issues() {
let result = ValidationResult::new();
assert_eq!(compute_exit_code(&result, &[], true, true, false), 0);
}
#[test]
fn test_compute_exit_code_errors() {
let mut result = ValidationResult::new();
result.errors.push("some error".to_string());
assert_eq!(compute_exit_code(&result, &[], true, true, false), 2);
}
#[test]
fn test_compute_exit_code_publish_errors_counted() {
let mut result = ValidationResult::new();
result.publish_errors.push("publish error".to_string());
assert_eq!(compute_exit_code(&result, &[], true, true, false), 2);
}
#[test]
fn test_compute_exit_code_publish_errors_not_checked() {
let mut result = ValidationResult::new();
result.publish_errors.push("publish error".to_string());
// check_publish = false → publish errors don't count
assert_eq!(compute_exit_code(&result, &[], false, true, false), 0);
}
#[test]
fn test_compute_exit_code_lock_errors_counted() {
let result = ValidationResult::new();
let lock_errors = vec!["lock stale".to_string()];
assert_eq!(
compute_exit_code(&result, &lock_errors, true, true, false),
2
);
}
#[test]
fn test_compute_exit_code_lock_errors_not_checked() {
let result = ValidationResult::new();
let lock_errors = vec!["lock stale".to_string()];
// check_lock = false → lock errors become warnings, not counted unless strict
assert_eq!(
compute_exit_code(&result, &lock_errors, true, false, false),
0
);
}
#[test]
fn test_compute_exit_code_strict_warnings() {
let mut result = ValidationResult::new();
result.warnings.push("some warning".to_string());
assert_eq!(compute_exit_code(&result, &[], true, true, true), 1);
}
#[test]
fn test_compute_exit_code_warnings_not_strict() {
let mut result = ValidationResult::new();
result.warnings.push("some warning".to_string());
assert_eq!(compute_exit_code(&result, &[], true, true, false), 0);
}
// ── check_lock_freshness ───────────────────────────────────────────────
#[test]
fn test_check_lock_freshness_no_lock_file() {
use tempfile::tempdir;
let dir = tempdir().unwrap();
let composer_json_path = dir.path().join("composer.json");
let content = r#"{"name": "vendor/pkg", "require": {}}"#;
std::fs::write(&composer_json_path, content).unwrap();
let mut lock_errors: Vec<String> = Vec::new();
check_lock_freshness(content, &composer_json_path, &mut lock_errors);
// No lock file → no errors
assert!(lock_errors.is_empty());
}
#[test]
fn test_check_lock_freshness_fresh_lock() {
use mozart_registry::lockfile::LockFile;
use tempfile::tempdir;
let dir = tempdir().unwrap();
let composer_json_path = dir.path().join("composer.json");
let content = r#"{"name": "vendor/pkg", "require": {"php": ">=8.1"}}"#;
std::fs::write(&composer_json_path, content).unwrap();
let hash = LockFile::compute_content_hash(content).unwrap();
let lock = LockFile {
readme: LockFile::default_readme(),
content_hash: hash,
packages: vec![],
packages_dev: Some(vec![]),
aliases: vec![],
minimum_stability: "stable".to_string(),
stability_flags: serde_json::json!({}),
prefer_stable: false,
prefer_lowest: false,
platform: serde_json::json!({}),
platform_dev: serde_json::json!({}),
plugin_api_version: None,
};
let lock_path = dir.path().join("composer.lock");
lock.write_to_file(&lock_path).unwrap();
let mut lock_errors: Vec<String> = Vec::new();
check_lock_freshness(content, &composer_json_path, &mut lock_errors);
assert!(
lock_errors.is_empty(),
"fresh lock should produce no errors"
);
}
#[test]
fn test_check_lock_freshness_stale_lock() {
use mozart_registry::lockfile::LockFile;
use tempfile::tempdir;
let dir = tempdir().unwrap();
let composer_json_path = dir.path().join("composer.json");
let original_content = r#"{"name": "vendor/pkg", "require": {"php": ">=8.1"}}"#;
let modified_content = r#"{"name": "vendor/pkg", "require": {"php": ">=8.2"}}"#;
// Write original content
std::fs::write(&composer_json_path, original_content).unwrap();
// Create lock file based on original content
let hash = LockFile::compute_content_hash(original_content).unwrap();
let lock = LockFile {
readme: LockFile::default_readme(),
content_hash: hash,
packages: vec![],
packages_dev: Some(vec![]),
aliases: vec![],
minimum_stability: "stable".to_string(),
stability_flags: serde_json::json!({}),
prefer_stable: false,
prefer_lowest: false,
platform: serde_json::json!({}),
platform_dev: serde_json::json!({}),
plugin_api_version: None,
};
let lock_path = dir.path().join("composer.lock");
lock.write_to_file(&lock_path).unwrap();
// Now check against modified content (lock is stale)
let mut lock_errors: Vec<String> = Vec::new();
check_lock_freshness(modified_content, &composer_json_path, &mut lock_errors);
assert!(
!lock_errors.is_empty(),
"stale lock should produce a lock error"
);
assert!(lock_errors[0].contains("not up to date"));
}
// ── Full manifest: valid package ───────────────────────────────────────
#[test]
fn test_validate_no_errors_on_valid_package() {
let json = r#"{
"name": "vendor/package",
"description": "A test package",
"license": "MIT",
"require": {"php": ">=8.1"}
}"#;
let result = parse_and_validate(json, &make_args());
assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
assert!(
result.publish_errors.is_empty(),
"publish errors: {:?}",
result.publish_errors
);
// Only the version-field warning might appear — but we have no version field here
assert!(
!result.warnings.iter().any(|w| w.contains("version field")),
"unexpected version warning"
);
}
}
|