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
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
|
//! ref: composer/tests/Composer/Test/InstallerTest.php
#[path = "common/config_stub.rs"]
mod config_stub;
#[path = "common/test_case.rs"]
mod test_case;
use config_stub::ConfigStubBuilder;
use test_case::{get_package, get_version_constraint};
use indexmap::IndexMap;
use std::cell::RefCell;
use std::rc::Rc;
use shirabe::advisory::{AuditConfig, Auditor};
use shirabe::autoload::{AutoloadGeneratorInterface, ClassLoader};
use shirabe::config::Config;
use shirabe::console::application::ApplicationHandle;
use shirabe::dependency_resolver::{Transaction, UpdateAllowTransitiveDeps};
use shirabe::downloader::{DownloadManagerInterface, DownloaderInterface};
use shirabe::event_dispatcher::{Callable, EventDispatcherInterface, EventInterface};
use shirabe::factory::{DisablePlugins, Factory, LocalConfigInput};
use shirabe::filter::platform_requirement_filter::{
PlatformRequirementFilterFactory, PlatformRequirementFilterInterface,
};
use shirabe::installer::{InstallationManager, Installer};
use shirabe::io::IOInterface;
use shirabe::io::buffer_io::BufferIO;
use shirabe::json::JsonFile;
use shirabe::package::dumper::ArrayDumper;
use shirabe::package::{
Link, Locker, LockerInterface, PackageInterfaceHandle, RootPackageHandle,
RootPackageInterfaceHandle,
};
use shirabe::repository::{
ArrayRepository, InstalledArrayRepository, InstalledRepositoryInterface,
RepositoryInterfaceHandle, RepositoryManager, RepositoryManagerInterface,
};
use shirabe::util::http_downloader::HttpDownloader;
use shirabe::util::r#loop::Loop;
use shirabe::util::platform::Platform;
use shirabe::util::process_executor::ProcessExecutor;
use shirabe_class_map_generator::class_map::ClassMap;
use shirabe_external_packages::composer::pcre::preg::Preg;
use shirabe_external_packages::symfony::console::command::command::Command as SymfonyCommand;
use shirabe_external_packages::symfony::console::command::command::CommandData;
use shirabe_external_packages::symfony::console::input::input_argument::InputArgument;
use shirabe_external_packages::symfony::console::input::input_interface::InputInterface;
use shirabe_external_packages::symfony::console::input::input_option::InputOption;
use shirabe_external_packages::symfony::console::input::string_input::StringInput;
use shirabe_external_packages::symfony::console::output::output_interface::{
OutputInterface, VERBOSITY_NORMAL,
};
use shirabe_external_packages::symfony::console::output::stream_output::StreamOutput;
use shirabe_php_shim::{PREG_SPLIT_DELIM_CAPTURE, PhpMixed};
use shirabe_semver::VersionParser;
use shirabe_semver::constraint::AnyConstraint;
// The chdir back to prevCwd (cwd management) and removeDirectory of tempComposerHome (a
// path produced by the unported install pipeline) are not ported; only the env clears are.
fn tear_down() {
Platform::clear_env("COMPOSER_POOL_OPTIMIZER");
Platform::clear_env("COMPOSER_FUND");
}
struct TearDown;
impl Drop for TearDown {
fn drop(&mut self) {
tear_down();
}
}
// PHP mocks `Composer\Downloader\DownloadManager` with getMockBuilder; PHPUnit mocks are permissive
// (every method returns null), so the Rust equivalent is a no-op stub over the trait seam.
#[derive(Debug)]
struct StubDownloadManager;
#[async_trait::async_trait(?Send)]
impl DownloadManagerInterface for StubDownloadManager {
fn set_prefer_source(&mut self, _prefer_source: bool) {}
fn set_prefer_dist(&mut self, _prefer_dist: bool) {}
fn get_downloader_for_package(
&self,
_package: PackageInterfaceHandle,
) -> anyhow::Result<Option<Rc<RefCell<dyn DownloaderInterface>>>> {
Ok(None)
}
async fn download(
&self,
_package: PackageInterfaceHandle,
_target_dir: &str,
_prev_package: Option<PackageInterfaceHandle>,
) -> anyhow::Result<Option<PhpMixed>> {
Ok(None)
}
async fn prepare(
&self,
_type: &str,
_package: PackageInterfaceHandle,
_target_dir: &str,
_prev_package: Option<PackageInterfaceHandle>,
) -> anyhow::Result<Option<PhpMixed>> {
Ok(None)
}
async fn install(
&self,
_package: PackageInterfaceHandle,
_target_dir: &str,
) -> anyhow::Result<Option<PhpMixed>> {
Ok(None)
}
async fn update(
&self,
_initial: PackageInterfaceHandle,
_target: PackageInterfaceHandle,
_target_dir: &str,
) -> anyhow::Result<Option<PhpMixed>> {
Ok(None)
}
async fn remove(
&self,
_package: PackageInterfaceHandle,
_target_dir: &str,
) -> anyhow::Result<Option<PhpMixed>> {
Ok(None)
}
async fn cleanup(
&self,
_type: &str,
_package: PackageInterfaceHandle,
_target_dir: &str,
_prev_package: Option<PackageInterfaceHandle>,
) -> anyhow::Result<Option<PhpMixed>> {
Ok(None)
}
}
// PHP mocks `Composer\EventDispatcher\EventDispatcher` with disableOriginalConstructor()->getMock();
// a permissive no-op stub mirrors the PHPUnit mock.
#[derive(Debug)]
struct StubEventDispatcher;
impl EventDispatcherInterface for StubEventDispatcher {
fn dispatch(
&mut self,
_event_name: Option<&str>,
_event: Option<&mut dyn EventInterface>,
) -> anyhow::Result<i64> {
Ok(0)
}
fn dispatch_script(
&mut self,
_event_name: &str,
_dev_mode: bool,
_additional_args: Vec<String>,
_flags: IndexMap<String, PhpMixed>,
) -> anyhow::Result<i64> {
Ok(0)
}
fn dispatch_installer_event(
&mut self,
_event_name: &str,
_dev_mode: bool,
_execute_operations: bool,
_transaction: Transaction,
) -> anyhow::Result<i64> {
Ok(0)
}
fn add_listener(&mut self, _event_name: &str, _listener: Callable, _priority: i64) {}
fn has_event_listeners(&mut self, _event: &dyn EventInterface) -> bool {
false
}
}
// PHP mocks `Composer\Autoload\AutoloadGenerator` with disableOriginalConstructor()->getMock();
// a permissive no-op stub mirrors the PHPUnit mock.
#[derive(Debug)]
struct StubAutoloadGenerator;
impl AutoloadGeneratorInterface for StubAutoloadGenerator {
fn set_dev_mode(&mut self, _dev_mode: bool) {}
fn set_class_map_authoritative(&mut self, _class_map_authoritative: bool) {}
fn set_apcu(&mut self, _apcu: bool, _apcu_prefix: Option<String>) {}
fn set_run_scripts(&mut self, _run_scripts: bool) {}
fn set_dry_run(&mut self, _dry_run: bool) {}
fn set_platform_requirement_filter(
&mut self,
_platform_requirement_filter: Rc<dyn PlatformRequirementFilterInterface>,
) {
}
#[allow(clippy::too_many_arguments)]
fn dump(
&mut self,
_config: &Config,
_local_repo: &mut dyn InstalledRepositoryInterface,
_root_package: RootPackageInterfaceHandle,
_installation_manager: &mut dyn shirabe::installer::InstallationManagerInterface,
_target_dir: &str,
_scan_psr_packages: bool,
_suffix: Option<String>,
_locker: Option<&mut dyn LockerInterface>,
_strict_ambiguous: bool,
) -> anyhow::Result<ClassMap> {
Ok(ClassMap::new())
}
fn build_package_map(
&self,
_installation_manager: &mut dyn shirabe::installer::InstallationManagerInterface,
_root_package: RootPackageInterfaceHandle,
_packages: Vec<PackageInterfaceHandle>,
) -> anyhow::Result<Vec<(PackageInterfaceHandle, Option<String>)>> {
Ok(vec![])
}
fn parse_autoloads(
&self,
_package_map: Vec<(PackageInterfaceHandle, Option<String>)>,
_root_package: RootPackageInterfaceHandle,
_filtered_dev_packages: PhpMixed,
) -> IndexMap<String, PhpMixed> {
IndexMap::new()
}
fn create_loader(
&self,
_autoloads: &IndexMap<String, PhpMixed>,
_vendor_dir: Option<String>,
) -> ClassLoader {
unimplemented!("create_loader is not reached by the installer test path")
}
}
/// ref: TestCase::getPackage with class `Composer\Package\RootPackage`.
fn root_package(name: &str, version: &str) -> RootPackageHandle {
let normalized = VersionParser.normalize(version, None).unwrap();
RootPackageHandle::new(name.to_string(), normalized, version.to_string())
}
/// ref: `new Link($source, $target, $constraint, $type, $constraint->getPrettyString())`.
fn link(source: &str, target: &str, constraint: AnyConstraint, r#type: &str) -> Link {
let pretty = constraint.get_pretty_string();
Link::new(
source.to_string(),
target.to_string(),
constraint,
Some(r#type.to_string()),
pretty,
)
}
/// One row of `provideInstaller`.
struct InstallerCase {
root_package: RootPackageHandle,
repositories: Vec<RepositoryInterfaceHandle>,
expected_install: Vec<PackageInterfaceHandle>,
expected_update: Vec<(PackageInterfaceHandle, PackageInterfaceHandle)>,
expected_uninstall: Vec<PackageInterfaceHandle>,
}
/// ref: InstallerTest::provideInstaller
fn provide_installer() -> Vec<InstallerCase> {
let mut cases = vec![];
// when A requires B and B requires A, and A is a non-published root package
// the install of B should succeed
let a = root_package("A", "1.0.0");
a.set_requires(IndexMap::from([(
"b".to_string(),
link(
"A",
"B",
get_version_constraint("=", "1.0.0"),
Link::TYPE_REQUIRE,
),
)]));
let b = get_package("B", "1.0.0");
b.as_complete_package()
.unwrap()
.__set_requires(IndexMap::from([(
"a".to_string(),
link(
"B",
"A",
get_version_constraint("=", "1.0.0"),
Link::TYPE_REQUIRE,
),
)]));
cases.push(InstallerCase {
root_package: a,
repositories: vec![RepositoryInterfaceHandle::new(
ArrayRepository::new(vec![b.clone()]).unwrap(),
)],
expected_install: vec![b],
expected_update: vec![],
expected_uninstall: vec![],
});
// #480: when A requires B and B requires A, and A is a published root package
// only B should be installed, as A is the root
let a = root_package("A", "1.0.0");
a.set_requires(IndexMap::from([(
"b".to_string(),
link(
"A",
"B",
get_version_constraint("=", "1.0.0"),
Link::TYPE_REQUIRE,
),
)]));
let b = get_package("B", "1.0.0");
b.as_complete_package()
.unwrap()
.__set_requires(IndexMap::from([(
"a".to_string(),
link(
"B",
"A",
get_version_constraint("=", "1.0.0"),
Link::TYPE_REQUIRE,
),
)]));
cases.push(InstallerCase {
root_package: a.clone(),
repositories: vec![RepositoryInterfaceHandle::new(
ArrayRepository::new(vec![a.into(), b.clone()]).unwrap(),
)],
expected_install: vec![b],
expected_update: vec![],
expected_uninstall: vec![],
});
// TODO why are there not more cases with uninstall/update?
cases
}
/// ref: InstallerTest::makePackagesComparable
fn make_packages_comparable(
packages: &[PackageInterfaceHandle],
) -> Vec<IndexMap<String, PhpMixed>> {
let dumper = ArrayDumper::new();
packages.iter().map(|p| dumper.dump(p.clone())).collect()
}
#[test]
#[ignore]
fn test_installer() {
let _tear_down = TearDown;
for case in provide_installer() {
let io_buffer = Rc::new(RefCell::new(
BufferIO::new(String::new(), VERBOSITY_NORMAL, None).unwrap(),
));
let io: Rc<RefCell<dyn IOInterface>> = io_buffer.clone();
let config = ConfigStubBuilder::new()
.with("vendor-dir", PhpMixed::String("foo".to_string()))
.with("lock", PhpMixed::Bool(true))
.with("notify-on-install", PhpMixed::Bool(true))
.build_shared();
let download_manager: Rc<RefCell<dyn DownloadManagerInterface>> =
Rc::new(RefCell::new(StubDownloadManager));
let http_downloader = Rc::new(RefCell::new(HttpDownloader::__new_mock(
io.clone(),
config.clone(),
)));
let mut repository_manager = RepositoryManager::new(
io.clone(),
config.clone(),
http_downloader.clone(),
None,
None,
);
repository_manager.set_local_repository(RepositoryInterfaceHandle::new(
InstalledArrayRepository::new().unwrap(),
));
for repository in &case.repositories {
repository_manager.add_repository(repository.clone());
}
let repository_manager: Rc<RefCell<dyn RepositoryManagerInterface>> =
Rc::new(RefCell::new(repository_manager));
let r#loop = Rc::new(RefCell::new(Loop::new(http_downloader.clone(), None)));
let installation_manager: Rc<RefCell<InstallationManager>> = Rc::new(RefCell::new(
InstallationManager::__new_mock(r#loop, io.clone(), None),
));
// emulate a writable lock file: a real JsonFile over a fresh temp path (initially absent, so
// the installer falls back to an update; PHP uses an in-memory JsonFile mock instead).
let lock_dir = tempfile::TempDir::new().unwrap();
let lock_path = lock_dir.path().join("composer.lock");
let lock_json =
JsonFile::new(lock_path.to_string_lossy().into_owned(), None, None).unwrap();
let process = Rc::new(RefCell::new(ProcessExecutor::new(Some(io.clone()))));
let locker: Rc<RefCell<dyn LockerInterface>> = Rc::new(RefCell::new(Locker::new(
io.clone(),
lock_json,
installation_manager.clone(),
"{}",
process,
)));
let autoload_generator: Rc<RefCell<dyn AutoloadGeneratorInterface>> =
Rc::new(RefCell::new(StubAutoloadGenerator));
let root_package: RootPackageInterfaceHandle =
RootPackageInterfaceHandle::dup(&case.root_package.clone().into());
let mut installer = Installer::new(
io.clone(),
config.clone(),
root_package,
download_manager,
repository_manager,
locker,
installation_manager.clone(),
Rc::new(RefCell::new(StubEventDispatcher)),
autoload_generator,
);
installer.set_audit_config(
AuditConfig::from_config(&mut config.borrow_mut(), false, Auditor::FORMAT_SUMMARY)
.unwrap(),
);
let result = installer.run().unwrap();
let output = io_buffer.borrow().get_output().replace('\r', "");
assert_eq!(0, result, "{}", output);
let installed = installation_manager.borrow().__get_installed_packages();
assert_eq!(
make_packages_comparable(&case.expected_install),
make_packages_comparable(&installed),
"{}",
output
);
let updated = installation_manager.borrow().__get_updated_packages();
assert_eq!(case.expected_update, updated);
let uninstalled = installation_manager.borrow().__get_uninstalled_packages();
assert_eq!(case.expected_uninstall, uninstalled);
}
}
/// ref: PHPUnit assertStringMatchesFormat's StringMatchesFormatDescription::createPatternFromFormat.
fn create_pattern_from_format(format: &str) -> String {
let escaped = regex::escape(format);
let bytes = escaped.as_bytes();
let mut out = String::from("(?s)^");
let mut i = 0;
while i < bytes.len() {
// regex::escape turns "%" into "%" (it is not special) so the format codes survive intact.
if bytes[i] == b'%' && i + 1 < bytes.len() {
let replacement: Option<&str> = match bytes[i + 1] {
b'%' => Some("%"),
b'e' => Some("\\/"),
b's' => Some("[^\\r\\n]+"),
b'S' => Some("[^\\r\\n]*"),
b'a' => Some(".+"),
b'A' => Some(".*"),
b'w' => Some("\\s*"),
b'i' => Some("[+-]?\\d+"),
b'd' => Some("\\d+"),
b'x' => Some("[0-9a-fA-F]+"),
b'f' => Some("[+-]?\\.?\\d+\\.?\\d*(?:[Ee][+-]?\\d+)?"),
b'c' => Some("."),
_ => None,
};
if let Some(replacement) = replacement {
out.push_str(replacement);
i += 2;
continue;
}
}
out.push(escaped[i..].chars().next().unwrap());
i += escaped[i..].chars().next().unwrap().len_utf8();
}
out.push('$');
out
}
/// ref: PHPUnit self::assertStringMatchesFormat.
fn assert_string_matches_format(format: &str, subject: &str, context: &str) {
let pattern = create_pattern_from_format(format);
let re = regex::Regex::new(&pattern)
.unwrap_or_else(|e| panic!("invalid format pattern {}: {}", pattern, e));
assert!(
re.is_match(subject),
"output does not match format.\n--- format ---\n{}\n--- output ---\n{}\n--- context ---\n{}",
format,
subject,
context
);
}
#[derive(Debug, Clone)]
enum ExpectLock {
/// No EXPECT-LOCK section (`[]` in PHP); the lock is not asserted.
Unset,
/// EXPECT-LOCK is the literal string "false"; the lock must never be written.
Never,
/// EXPECT-LOCK holds an expected lock JSON.
Json(serde_json::Value),
}
#[derive(Debug, Clone)]
enum ExpectResult {
ExitCode(i64),
/// EXPECT-EXCEPTION: the class-string of an expected exception.
Exception(String),
}
#[derive(Debug, Clone)]
struct IntegrationCase {
file: String,
message: String,
condition: Option<String>,
composer: serde_json::Value,
lock: Option<serde_json::Value>,
installed: Option<serde_json::Value>,
run: String,
expect_lock: ExpectLock,
expect_installed: Option<serde_json::Value>,
expect_output: Option<String>,
expect_output_optimized: Option<String>,
expect: String,
expect_result: ExpectResult,
}
fn fixtures_dir(path: &str) -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../composer/tests/Composer/Test/Fixtures")
.join(path)
.canonicalize()
.unwrap()
}
/// ref: InstallerTest::readTestFile
fn read_test_file(
file: &std::path::Path,
fixtures_dir: &std::path::Path,
) -> IndexMap<String, String> {
let contents = std::fs::read_to_string(file).unwrap();
let tokens = Preg::split4(
r"#(?:^|\n*)--([A-Z-]+)--\n#",
&contents,
-1,
PREG_SPLIT_DELIM_CAPTURE,
);
let section_info: [(&str, bool); 13] = [
("TEST", true),
("CONDITION", false),
("COMPOSER", true),
("LOCK", false),
("INSTALLED", false),
("RUN", true),
("EXPECT-LOCK", false),
("EXPECT-INSTALLED", false),
("EXPECT-OUTPUT", false),
("EXPECT-OUTPUT-OPTIMIZED", false),
("EXPECT-EXIT-CODE", false),
("EXPECT-EXCEPTION", false),
("EXPECT", true),
];
let known: indexmap::IndexSet<&str> = section_info.iter().map(|(k, _)| *k).collect();
let mut section: Option<String> = None;
let mut data: IndexMap<String, String> = IndexMap::new();
for token in tokens {
if section.is_none() && token.is_empty() {
continue; // skip leading blank
}
if section.is_none() {
assert!(
known.contains(token.as_str()),
"The test file \"{}\" must not contain a section named \"{}\".",
file.display(),
token
);
section = Some(token);
continue;
}
let sec = section.take().unwrap();
data.insert(sec, token);
}
for (sec, required) in section_info {
if required {
assert!(
data.contains_key(sec),
"The test file \"{}\" must have a section named \"{}\".",
file.display(),
sec
);
}
}
let _ = fixtures_dir;
data
}
fn collect_test_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
collect_test_files(&path, out);
} else if path.extension().and_then(|e| e.to_str()) == Some("test") {
out.push(path);
}
}
}
/// ref: InstallerTest::loadIntegrationTests
fn load_integration_tests(path: &str) -> Vec<IntegrationCase> {
let dir = fixtures_dir(path);
let mut files = Vec::new();
collect_test_files(&dir, &mut files);
files.sort();
let mut tests = Vec::new();
for file in files {
let test_data = read_test_file(&file, &dir);
// skip 64bit related tests on 32bit (usize is 64-bit here, so this never triggers).
if test_data
.get("EXPECT-OUTPUT")
.map(|s| s.contains("php-64bit"))
.unwrap_or(false)
&& (usize::BITS == 32)
{
continue;
}
let message = test_data["TEST"].clone();
let condition = test_data
.get("CONDITION")
.filter(|s| !s.is_empty())
.cloned();
let mut composer: serde_json::Value = serde_json::from_str(&test_data["COMPOSER"]).unwrap();
if let Some(repositories) = composer.get_mut("repositories") {
let fixtures_str = dir.to_string_lossy().replace('\\', "/");
let rewrite = |repo: &mut serde_json::Value| {
if repo.get("type").and_then(|t| t.as_str()) != Some("composer") {
return;
}
if let Some(url) = repo.get("url").and_then(|u| u.as_str())
&& Preg::is_match(r"{^file://[^/]}", url)
{
let new_url = format!("file://{}/{}", fixtures_str, &url[7..]);
repo["url"] = serde_json::Value::String(new_url);
}
};
match repositories {
serde_json::Value::Array(list) => list.iter_mut().for_each(rewrite),
serde_json::Value::Object(map) => map.values_mut().for_each(rewrite),
_ => {}
}
}
let lock = test_data.get("LOCK").filter(|s| !s.is_empty()).map(|s| {
let mut lock: serde_json::Value = serde_json::from_str(s).unwrap();
if lock.get("hash").is_none() {
let encoded = JsonFile::encode_with_options(
&composer,
shirabe::json::JsonEncodeOptions::none(),
);
let hash = format!("{:x}", md5::compute(encoded.as_bytes()));
lock["hash"] = serde_json::Value::String(hash);
}
lock
});
let installed = test_data
.get("INSTALLED")
.filter(|s| !s.is_empty())
.map(|s| serde_json::from_str(s).unwrap());
let run = test_data["RUN"].clone();
let expect_lock = match test_data.get("EXPECT-LOCK").filter(|s| !s.is_empty()) {
None => ExpectLock::Unset,
Some(s) if s == "false" => ExpectLock::Never,
Some(s) => ExpectLock::Json(serde_json::from_str(s).unwrap()),
};
let expect_installed = test_data
.get("EXPECT-INSTALLED")
.filter(|s| !s.is_empty())
.map(|s| serde_json::from_str(s).unwrap());
let expect_output = test_data.get("EXPECT-OUTPUT").cloned();
let expect_output_optimized = test_data.get("EXPECT-OUTPUT-OPTIMIZED").cloned();
let expect = test_data["EXPECT"].clone();
let expect_result =
if let Some(exc) = test_data.get("EXPECT-EXCEPTION").filter(|s| !s.is_empty()) {
assert!(
test_data
.get("EXPECT-EXIT-CODE")
.filter(|s| !s.is_empty())
.is_none(),
"EXPECT-EXCEPTION and EXPECT-EXIT-CODE are mutually exclusive"
);
ExpectResult::Exception(exc.clone())
} else if let Some(code) = test_data.get("EXPECT-EXIT-CODE").filter(|s| !s.is_empty()) {
ExpectResult::ExitCode(code.trim().parse().unwrap())
} else {
ExpectResult::ExitCode(0)
};
tests.push(IntegrationCase {
file: file
.strip_prefix(&dir)
.unwrap()
.to_string_lossy()
.into_owned(),
message,
condition,
composer,
lock,
installed,
run,
expect_lock,
expect_installed,
expect_output,
expect_output_optimized,
expect,
expect_result,
});
}
tests
}
/// ref: the inline `eval($condition)` in doTestIntegration, ported for the known fixture conditions.
fn evaluate_condition(condition: &str) -> bool {
match condition.trim() {
// putenv() returns true on success, so these conditions always run the test (with the env set).
"putenv('COMPOSER_FUND=1')" => {
Platform::put_env("COMPOSER_FUND", "1");
true
}
"putenv('COMPOSER_FUND=0')" => {
Platform::put_env("COMPOSER_FUND", "0");
true
}
// HHVM is never defined under the Rust port.
"!defined('HHVM_VERSION')" => true,
// TODO(phase-d): unported CONDITION expression (PHP eval has no Rust equivalent).
other => panic!("// TODO(phase-d): unported CONDITION: {}", other),
}
}
fn opt_bool(input: &dyn InputInterface, name: &str) -> bool {
input
.get_option(name)
.ok()
.and_then(|m| m.as_bool())
.unwrap_or(false)
}
/// ref: `$ignorePlatformReqs = true === getOption('ignore-platform-reqs') ?: (getOption('ignore-platform-req') ?: false)`.
fn ignore_platform_reqs_value(input: &dyn InputInterface) -> PhpMixed {
if opt_bool(input, "ignore-platform-reqs") {
return PhpMixed::Bool(true);
}
let list = input
.get_option("ignore-platform-req")
.unwrap_or(PhpMixed::Bool(false));
match &list {
PhpMixed::List(items) if !items.is_empty() => list,
PhpMixed::Array(map) if !map.is_empty() => list,
_ => PhpMixed::Bool(false),
}
}
fn write_json(path: &std::path::Path, value: &serde_json::Value) {
std::fs::write(path, serde_json::to_string_pretty(value).unwrap()).unwrap();
}
/// ref: InstallerTest::doTestIntegration
fn do_test_integration(case: &IntegrationCase, expect_output: Option<&str>) {
if let Some(condition) = &case.condition
&& !evaluate_condition(condition)
{
return; // markTestSkipped
}
let io_buffer = Rc::new(RefCell::new(
BufferIO::new(String::new(), VERBOSITY_NORMAL, None).unwrap(),
));
let io: Rc<RefCell<dyn IOInterface>> = io_buffer.clone();
let is_exception = matches!(case.expect_result, ExpectResult::Exception(_));
// Create Composer mock object according to configuration (FactoryMock::create).
let composer_str = serde_json::to_string(&case.composer).unwrap();
let composer_data = JsonFile::parse_json(Some(&composer_str), None)
.unwrap()
.as_array()
.cloned()
.unwrap_or_default();
let composer = Factory::__create_mock(
io.clone(),
Some(LocalConfigInput::Data(composer_data)),
DisablePlugins::None,
false,
)
.unwrap();
// installed.json mock: a real JsonFile over a temp file holding $installed, wrapped in the
// no-op InstalledFilesystemRepositoryMock.
let installed_dir = tempfile::TempDir::new().unwrap();
let installed_path = installed_dir.path().join("installed.json");
write_json(
&installed_path,
case.installed.as_ref().unwrap_or(&serde_json::json!([])),
);
let installed_json =
JsonFile::new(installed_path.to_string_lossy().into_owned(), None, None).unwrap();
let local_repo = shirabe::repository::InstalledFilesystemRepository::__new_mock(
installed_json,
false,
None,
None,
)
.unwrap();
let repository_manager = composer.borrow().get_repository_manager();
repository_manager
.borrow_mut()
.set_local_repository(RepositoryInterfaceHandle::new(local_repo));
// emulate a writable lock file: a real composer.lock over a temp path.
let lock_dir = tempfile::TempDir::new().unwrap();
let lock_path = lock_dir.path().join("composer.lock");
if let Some(lock) = &case.lock {
write_json(&lock_path, lock);
}
let lock_before = std::fs::read_to_string(&lock_path).ok();
let lock_json = JsonFile::new(lock_path.to_string_lossy().into_owned(), None, None).unwrap();
// The Locker needs a concrete InstallationManager; build a fresh recording mock just for it. The
// asserted trace comes from the composer's own installation manager (read via as_any below).
let process = Rc::new(RefCell::new(ProcessExecutor::new(Some(io.clone()))));
let locker_loop = composer.borrow().get_loop();
let locker_im = Rc::new(RefCell::new(InstallationManager::__new_mock(
locker_loop,
io.clone(),
None,
)));
let contents = serde_json::to_string(&case.composer).unwrap();
let locker = Locker::new(io.clone(), lock_json, locker_im, &contents, process);
composer
.borrow_mut()
.set_locker(Rc::new(RefCell::new(locker)));
composer
.borrow_mut()
.set_autoload_generator(Rc::new(RefCell::new(StubAutoloadGenerator)));
composer
.borrow_mut()
.set_event_dispatcher(Rc::new(RefCell::new(StubEventDispatcher)));
let installer = Rc::new(RefCell::new(Installer::create(
io.clone(),
&composer.upcast(),
)));
// Application with inline install/update commands (setCode closures).
let application = ApplicationHandle::new("Composer".to_string(), "".to_string()).unwrap();
application.set_catch_exceptions(false);
let run_result: Rc<RefCell<Option<anyhow::Result<i64>>>> = Rc::new(RefCell::new(None));
let install = Rc::new(RefCell::new(CommandData::new(Some("install".to_string()))));
{
let install_ref = install.borrow();
install_ref
.add_option(
"ignore-platform-reqs",
PhpMixed::Null,
Some(InputOption::VALUE_NONE),
"",
PhpMixed::Null,
)
.unwrap();
install_ref
.add_option(
"ignore-platform-req",
PhpMixed::Null,
Some(InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY),
"",
PhpMixed::Null,
)
.unwrap();
install_ref
.add_option(
"no-dev",
PhpMixed::Null,
Some(InputOption::VALUE_NONE),
"",
PhpMixed::Null,
)
.unwrap();
install_ref
.add_option(
"dry-run",
PhpMixed::Null,
Some(InputOption::VALUE_NONE),
"",
PhpMixed::Null,
)
.unwrap();
let installer_cl = installer.clone();
let composer_cl = composer.clone();
let run_result_cl = run_result.clone();
install_ref.set_code(Box::new(move |input, _output| {
let ignore = ignore_platform_reqs_value(input);
let mut inst = installer_cl.borrow_mut();
inst.set_dev_mode(!opt_bool(input, "no-dev"))
.set_dry_run(opt_bool(input, "dry-run"))
.set_platform_requirement_filter(
PlatformRequirementFilterFactory::from_bool_or_list(ignore).unwrap(),
)
.set_audit_config(
AuditConfig::from_config(
&mut composer_cl.borrow().get_config().borrow_mut(),
false,
Auditor::FORMAT_SUMMARY,
)
.unwrap(),
);
let r = inst.run();
let code = match &r {
Ok(c) => *c,
Err(_) => 1,
};
*run_result_cl.borrow_mut() = Some(r);
PhpMixed::Int(code)
}));
}
application
.add(install.clone() as Rc<RefCell<dyn SymfonyCommand>>)
.unwrap();
let update = Rc::new(RefCell::new(CommandData::new(Some("update".to_string()))));
{
let update_ref = update.borrow();
for (name, mode) in [
("ignore-platform-reqs", InputOption::VALUE_NONE),
("no-dev", InputOption::VALUE_NONE),
("no-install", InputOption::VALUE_NONE),
("dry-run", InputOption::VALUE_NONE),
("lock", InputOption::VALUE_NONE),
("with-all-dependencies", InputOption::VALUE_NONE),
("with-dependencies", InputOption::VALUE_NONE),
("minimal-changes", InputOption::VALUE_NONE),
("prefer-stable", InputOption::VALUE_NONE),
("prefer-lowest", InputOption::VALUE_NONE),
] {
update_ref
.add_option(name, PhpMixed::Null, Some(mode), "", PhpMixed::Null)
.unwrap();
}
update_ref
.add_option(
"ignore-platform-req",
PhpMixed::Null,
Some(InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY),
"",
PhpMixed::Null,
)
.unwrap();
update_ref
.add_argument(
"packages",
Some(InputArgument::IS_ARRAY | InputArgument::OPTIONAL),
"",
PhpMixed::Null,
)
.unwrap();
let installer_cl = installer.clone();
let composer_cl = composer.clone();
let run_result_cl = run_result.clone();
update_ref.set_code(Box::new(move |input, _output| {
let packages: Vec<String> =
match input.get_argument("packages").unwrap_or(PhpMixed::Null) {
PhpMixed::List(items) => items
.into_iter()
.filter_map(|v| v.as_string().map(|s| s.to_string()))
.collect(),
_ => vec![],
};
let filtered: Vec<String> = packages
.iter()
.filter(|p| !["lock", "nothing", "mirrors"].contains(&p.as_str()))
.cloned()
.collect();
let update_mirrors = opt_bool(input, "lock") || filtered.len() != packages.len();
let update_allow_transitive = if opt_bool(input, "with-all-dependencies") {
UpdateAllowTransitiveDeps::UpdateListedWithTransitiveDeps
} else if opt_bool(input, "with-dependencies") {
UpdateAllowTransitiveDeps::UpdateListedWithTransitiveDepsNoRootRequire
} else {
UpdateAllowTransitiveDeps::UpdateOnlyListed
};
let ignore = ignore_platform_reqs_value(input);
let mut inst = installer_cl.borrow_mut();
inst.set_dev_mode(!opt_bool(input, "no-dev"))
.set_update(true)
.set_install(!opt_bool(input, "no-install"))
.set_dry_run(opt_bool(input, "dry-run"))
.set_update_mirrors(update_mirrors)
.set_update_allow_list(filtered)
.set_update_allow_transitive_dependencies(update_allow_transitive)
.unwrap()
.set_prefer_stable(opt_bool(input, "prefer-stable"))
.set_prefer_lowest(opt_bool(input, "prefer-lowest"))
.set_platform_requirement_filter(
PlatformRequirementFilterFactory::from_bool_or_list(ignore).unwrap(),
)
.set_audit_config(
AuditConfig::from_config(
&mut composer_cl.borrow().get_config().borrow_mut(),
false,
Auditor::FORMAT_SUMMARY,
)
.unwrap(),
)
.set_minimal_update(opt_bool(input, "minimal-changes"));
let r = inst.run();
let code = match &r {
Ok(c) => *c,
Err(_) => 1,
};
*run_result_cl.borrow_mut() = Some(r);
PhpMixed::Int(code)
}));
}
application
.add(update.clone() as Rc<RefCell<dyn SymfonyCommand>>)
.unwrap();
assert!(
Preg::is_match(r"{^(install|update)\b}", &case.run),
"The run command only supports install and update"
);
let app_output_stream = shirabe_php_shim::php_fopen_resource("php://memory", "w+");
let app_output = StreamOutput::new(app_output_stream.clone(), None, None, None)
.unwrap()
.expect("php://memory is a valid stream");
let mut string_input = StringInput::new(&format!("{} -vvv", case.run)).unwrap();
string_input.set_interactive(false);
let input: Rc<RefCell<dyn InputInterface>> = Rc::new(RefCell::new(string_input));
let output: Rc<RefCell<dyn OutputInterface>> = Rc::new(RefCell::new(app_output));
let app_run = application.run(Some(input), Some(output));
let output_string = io_buffer.borrow().get_output().replace('\r', "");
// Shouldn't check output and results if an exception was expected by this point.
if is_exception {
let ExpectResult::Exception(_) = &case.expect_result else {
unreachable!()
};
let normalized = case.expect.replace('\n', shirabe_php_shim::PHP_EOL);
let normalized = normalized.trim_end();
let err = match run_result.borrow().as_ref() {
Some(Err(e)) => format!("{}", e),
_ => app_run
.as_ref()
.err()
.map(|e| format!("{}", e))
.unwrap_or_default(),
};
assert!(
err.contains(normalized),
"expected exception message containing:\n{}\n--- got ---\n{}",
normalized,
err
);
return;
}
let result = match run_result.borrow().as_ref() {
Some(Ok(c)) => *c,
Some(Err(e)) => panic!("installer run failed: {}\n{}", e, output_string),
None => app_run.unwrap_or(-1) as i64,
};
let ExpectResult::ExitCode(expect_result) = &case.expect_result else {
unreachable!()
};
shirabe_php_shim::rewind(&app_output_stream);
let app_output_contents =
shirabe_php_shim::stream_get_contents(&app_output_stream).unwrap_or_default();
assert_eq!(
*expect_result, result,
"{}{}",
output_string, app_output_contents
);
if let ExpectLock::Json(expect_lock) = &case.expect_lock {
let actual = std::fs::read_to_string(&lock_path).unwrap();
let mut actual_lock: serde_json::Value = serde_json::from_str(&actual).unwrap();
if let Some(obj) = actual_lock.as_object_mut() {
for k in ["hash", "content-hash", "_readme", "plugin-api-version"] {
obj.remove(k);
}
}
let mut expect_lock = expect_lock.clone();
// PHP turns the empty-array sentinel into stdClass; serde compares {} vs [] strictly, so
// normalize the known object-valued keys to {} when they are empty.
if let Some(obj) = expect_lock.as_object_mut() {
for k in ["stability-flags", "platform", "platform-dev"] {
if obj.get(k) == Some(&serde_json::json!([])) {
obj.insert(k.to_string(), serde_json::json!({}));
}
}
}
assert_eq!(expect_lock, actual_lock);
} else if let ExpectLock::Never = &case.expect_lock {
let lock_after = std::fs::read_to_string(&lock_path).ok();
assert_eq!(lock_before, lock_after, "lock file must not be written");
}
if let Some(expect_installed) = &case.expect_installed {
let dumper = ArrayDumper::new();
let local_repo = repository_manager.borrow().get_local_repository();
let mut actual_installed: Vec<IndexMap<String, PhpMixed>> = local_repo
.get_canonical_packages()
.unwrap()
.into_iter()
.map(|package| {
let mut dumped = dumper.dump(package);
dumped.shift_remove("version_normalized");
dumped
})
.collect();
actual_installed.sort_by(
|a: &IndexMap<String, PhpMixed>, b: &IndexMap<String, PhpMixed>| {
let an = a
.get("name")
.and_then(|m| m.as_string())
.map(|s| s.to_string())
.unwrap_or_default();
let bn = b
.get("name")
.and_then(|m| m.as_string())
.map(|s| s.to_string())
.unwrap_or_default();
an.cmp(&bn)
},
);
// Faithful comparison would dump expect_installed through the same shape; we compare the
// serialized forms so the assertion still fails loudly on divergence.
let actual_json = serde_json::to_value(
actual_installed
.iter()
.map(php_mixed_map_to_json)
.collect::<Vec<_>>(),
)
.unwrap();
assert_eq!(expect_installed, &actual_json);
}
// trace from the composer's recording InstallationManager.
let im_handle = composer.borrow().get_installation_manager();
let im_ref = im_handle.borrow();
let trace = im_ref
.as_any()
.downcast_ref::<InstallationManager>()
.expect("composer installation manager is the recording mock")
.__get_trace();
assert_eq!(case.expect.trim_end(), trace.join("\n"));
if let Some(expect_output) = expect_output
&& !expect_output.is_empty()
{
let output = Preg::replace(r"{^ - .*?\.ini$}m", "__inilist__", &output_string);
let output = Preg::replace(r"{(__inilist__\r?\n)+}", "__inilist__\n", &output);
assert_string_matches_format(expect_output.trim_end(), output.trim_end(), &output_string);
}
}
fn php_mixed_map_to_json(map: &IndexMap<String, PhpMixed>) -> serde_json::Value {
serde_json::to_value(map).unwrap_or(serde_json::Value::Null)
}
#[test]
#[ignore = "ported; exercises the full install pipeline which is not yet executable end-to-end (execute_batch / repository / autoload stubs), so cases are expected to fail at runtime"]
fn test_slow_integration() {
let _tear_down = TearDown;
for case in load_integration_tests("installer-slow/") {
Platform::clear_env("COMPOSER_FUND");
Platform::put_env("COMPOSER_POOL_OPTIMIZER", "0");
let expect_output = case.expect_output.clone();
do_test_integration(&case, expect_output.as_deref());
}
}
#[test]
#[ignore = "ported; exercises the full install pipeline which is not yet executable end-to-end (execute_batch / repository / autoload stubs), so cases are expected to fail at runtime"]
fn test_integration_with_pool_optimizer() {
let _tear_down = TearDown;
for case in load_integration_tests("installer/") {
Platform::clear_env("COMPOSER_FUND");
Platform::put_env("COMPOSER_POOL_OPTIMIZER", "1");
let expect_output = case
.expect_output_optimized
.clone()
.filter(|s| !s.is_empty())
.or_else(|| case.expect_output.clone());
do_test_integration(&case, expect_output.as_deref());
}
}
#[test]
#[ignore = "ported; exercises the full install pipeline which is not yet executable end-to-end (execute_batch / repository / autoload stubs), so cases are expected to fail at runtime"]
fn test_integration_with_raw_pool() {
let _tear_down = TearDown;
for case in load_integration_tests("installer/") {
Platform::clear_env("COMPOSER_FUND");
Platform::put_env("COMPOSER_POOL_OPTIMIZER", "0");
let expect_output = case.expect_output.clone();
do_test_integration(&case, expect_output.as_deref());
}
}
|