aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/downloader/git_downloader.rs
blob: ed6f9132436f03981e6389ed2a02f17dceca5f0e (plain)
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
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
//! ref: composer/src/Composer/Downloader/GitDownloader.php

use crate::io::io_interface;
use anyhow::Result;
use indexmap::IndexMap;
use shirabe_external_packages::composer::pcre::{CaptureKey, Preg};
use shirabe_php_shim::{
    PhpMixed, RuntimeException, array_map, basename, dirname, implode, in_array, is_dir,
    preg_quote, realpath, rtrim, sprintf, strlen, strpos, substr, trim, version_compare,
};

use crate::cache::Cache;
use crate::config::Config;
use crate::downloader::DvcsDownloaderInterface;
use crate::downloader::VcsDownloaderBase;
use crate::io::IOInterface;
use crate::io::IOInterfaceImmutable;
use crate::package::PackageInterface;
use crate::package::PackageInterfaceHandle;
use crate::util::Filesystem;
use crate::util::Git as GitUtil;
use crate::util::Platform;
use crate::util::ProcessExecutor;
use crate::util::Url;

#[derive(Debug)]
pub struct GitDownloader {
    inner: VcsDownloaderBase,
    /// @var array<string, bool>
    has_stashed_changes: IndexMap<String, bool>,
    /// @var array<string, bool>
    has_discarded_changes: IndexMap<String, bool>,
    git_util: GitUtil,
    /// @var array<int, array<string, bool>>
    cached_packages: IndexMap<i64, IndexMap<String, bool>>,
}

impl GitDownloader {
    pub fn new(
        io: std::rc::Rc<std::cell::RefCell<dyn IOInterface>>,
        config: std::rc::Rc<std::cell::RefCell<Config>>,
        process: Option<std::rc::Rc<std::cell::RefCell<ProcessExecutor>>>,
        fs: Option<std::rc::Rc<std::cell::RefCell<Filesystem>>>,
    ) -> Self {
        let inner = VcsDownloaderBase::new(io, config, process, fs);
        let git_util = GitUtil::new(
            inner.io.clone(),
            inner.config.clone(),
            inner.process.clone(),
            inner.filesystem.clone(),
        );
        Self {
            inner,
            has_stashed_changes: IndexMap::new(),
            has_discarded_changes: IndexMap::new(),
            git_util,
            cached_packages: IndexMap::new(),
        }
    }

    pub(crate) async fn do_download(
        &mut self,
        package: PackageInterfaceHandle,
        _path: &str,
        url: &str,
        _prev_package: Option<PackageInterfaceHandle>,
    ) -> Result<Option<PhpMixed>> {
        // Do not create an extra local cache when repository is already local
        if Filesystem::is_local_path(url) {
            return Ok(None);
        }

        GitUtil::clean_env(&self.inner.process);

        let cache_path = format!(
            "{}/{}/",
            self.inner
                .config
                .borrow_mut()
                .get("cache-vcs-dir")
                .as_string()
                .unwrap_or(""),
            Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string()))?,
        );
        let git_version = GitUtil::get_version(&self.inner.process);

        // --dissociate option is only available since git 2.3.0-rc0
        if git_version.is_some()
            && version_compare(git_version.as_deref().unwrap_or(""), "2.3.0-rc0", ">=")
            && Cache::is_usable(&cache_path)
        {
            self.inner.io.write_error3(
                &format!(
                    "  - Syncing <info>{}</info> (<comment>{}</comment>) into cache",
                    package.get_name(),
                    package.get_full_pretty_version(
                        true,
                        <dyn PackageInterface>::DISPLAY_SOURCE_REF_IF_DEV,
                    ),
                ),
                true,
                io_interface::NORMAL,
            );
            self.inner.io.write_error3(
                &sprintf(
                    "    Cloning to cache at %s",
                    &[PhpMixed::String(cache_path.clone())],
                ),
                true,
                io_interface::DEBUG,
            );
            let r#ref = package.get_source_reference();
            let pretty_version = package.get_pretty_version();
            if self.git_util.fetch_ref_or_sync_mirror(
                url,
                &cache_path,
                r#ref.as_deref().unwrap_or(""),
                Some(&pretty_version),
            )? && is_dir(&cache_path)
            {
                self.cached_packages
                    .entry(package.get_id())
                    .or_insert_with(IndexMap::new)
                    .insert(r#ref.as_deref().unwrap_or("").to_string(), true);
            }
        } else if git_version.is_none() {
            return Err(RuntimeException {
                message: "git was not found in your PATH, skipping source download".to_string(),
                code: 0,
            }
            .into());
        }

        Ok(None)
    }

    pub(crate) async fn do_install(
        &mut self,
        package: PackageInterfaceHandle,
        path: &str,
        url: &str,
    ) -> Result<Option<PhpMixed>> {
        GitUtil::clean_env(&self.inner.process);
        let path = self.normalize_path(path);
        let cache_path = format!(
            "{}/{}/",
            self.inner
                .config
                .borrow_mut()
                .get("cache-vcs-dir")
                .as_string()
                .unwrap_or(""),
            Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string()))?,
        );
        let r#ref = package.get_source_reference().unwrap_or_default();

        let msg;
        let commands: Vec<Vec<String>>;
        let has_cached = self
            .cached_packages
            .get(&package.get_id())
            .and_then(|m| m.get(&r#ref))
            .copied()
            .unwrap_or(false);
        if has_cached {
            msg = format!("Cloning {} from cache", self.get_short_hash(&r#ref));

            let mut clone_flags: Vec<String> = vec![
                "--dissociate".to_string(),
                "--reference".to_string(),
                cache_path.clone(),
            ];
            let transport_options = package.get_transport_options();
            if let Some(git_opts) = transport_options.get("git").and_then(|v| v.as_array()) {
                if let Some(single) = git_opts.get("single_use_clone").and_then(|v| v.as_bool()) {
                    if single {
                        clone_flags = vec![];
                    }
                }
            }

            commands = vec![
                {
                    let mut base = vec![
                        "git".to_string(),
                        "clone".to_string(),
                        "--no-checkout".to_string(),
                        cache_path.clone(),
                        path.clone(),
                    ];
                    base.extend(clone_flags);
                    base
                },
                vec![
                    "git".to_string(),
                    "remote".to_string(),
                    "set-url".to_string(),
                    "origin".to_string(),
                    "--".to_string(),
                    "%sanitizedUrl%".to_string(),
                ],
                vec![
                    "git".to_string(),
                    "remote".to_string(),
                    "add".to_string(),
                    "composer".to_string(),
                    "--".to_string(),
                    "%sanitizedUrl%".to_string(),
                ],
            ];
        } else {
            msg = format!("Cloning {}", self.get_short_hash(&r#ref));
            commands = vec![
                vec![
                    "git".to_string(),
                    "clone".to_string(),
                    "--no-checkout".to_string(),
                    "--".to_string(),
                    "%url%".to_string(),
                    path.clone(),
                ],
                vec![
                    "git".to_string(),
                    "remote".to_string(),
                    "add".to_string(),
                    "composer".to_string(),
                    "--".to_string(),
                    "%url%".to_string(),
                ],
                vec![
                    "git".to_string(),
                    "fetch".to_string(),
                    "composer".to_string(),
                ],
                vec![
                    "git".to_string(),
                    "remote".to_string(),
                    "set-url".to_string(),
                    "origin".to_string(),
                    "--".to_string(),
                    "%sanitizedUrl%".to_string(),
                ],
                vec![
                    "git".to_string(),
                    "remote".to_string(),
                    "set-url".to_string(),
                    "composer".to_string(),
                    "--".to_string(),
                    "%sanitizedUrl%".to_string(),
                ],
            ];
            if Platform::get_env("COMPOSER_DISABLE_NETWORK").is_some() {
                return Err(RuntimeException {
                    message: format!(
                        "The required git reference for {} is not in cache and network is disabled, aborting",
                        package.get_name(),
                    ),
                    code: 0,
                }
                .into());
            }
        }

        self.inner.io.write_error3(&msg, true, io_interface::NORMAL);

        self.git_util
            .run_commands(commands, url, Some(&path), true, None)?;

        let source_url = package.get_source_url();
        if Some(url) != source_url.as_deref() && source_url.is_some() {
            self.update_origin_url(&path, source_url.as_deref().unwrap());
        } else {
            self.set_push_url(&path, url);
        }

        let pretty_version = package.get_pretty_version();
        if let Some(new_ref) =
            self.update_to_commit(package.clone(), &path, &r#ref, &pretty_version)?
        {
            if package.get_dist_reference() == package.get_source_reference() {
                // TODO(phase-b): set_dist_reference requires &mut PackageInterface
                // package.set_dist_reference(Some(new_ref.clone()));
            }
            // package.set_source_reference(Some(new_ref));
            let _ = new_ref;
        }

        Ok(None)
    }

    pub(crate) async fn do_update(
        &mut self,
        _initial: PackageInterfaceHandle,
        target: PackageInterfaceHandle,
        path: &str,
        url: &str,
    ) -> Result<Option<PhpMixed>> {
        GitUtil::clean_env(&self.inner.process);
        let path = self.normalize_path(path);
        if !self.has_metadata_repository(&path) {
            return Err(RuntimeException {
                message: format!(
                    "The .git directory is missing from {}, see https://getcomposer.org/commit-deps for more information",
                    path
                ),
                code: 0,
            }
            .into());
        }

        let cache_path = format!(
            "{}/{}/",
            self.inner
                .config
                .borrow_mut()
                .get("cache-vcs-dir")
                .as_string()
                .unwrap_or(""),
            Preg::replace(r"{[^a-z0-9.]}i", "-", &Url::sanitize(url.to_string()))?,
        );
        let r#ref = target.get_source_reference().unwrap_or_default();

        let msg;
        let remote_url;
        let has_cached = self
            .cached_packages
            .get(&target.get_id())
            .and_then(|m| m.get(&r#ref))
            .copied()
            .unwrap_or(false);
        if has_cached {
            msg = format!("Checking out {} from cache", self.get_short_hash(&r#ref));
            remote_url = cache_path.clone();
        } else {
            msg = format!("Checking out {}", self.get_short_hash(&r#ref));
            remote_url = "%url%".to_string();
            if Platform::get_env("COMPOSER_DISABLE_NETWORK").is_some() {
                return Err(RuntimeException {
                    message: format!(
                        "The required git reference for {} is not in cache and network is disabled, aborting",
                        target.get_name(),
                    ),
                    code: 0,
                }
                .into());
            }
        }

        self.inner.io.write_error3(&msg, true, io_interface::NORMAL);

        let mut output = String::new();
        if self.inner.process.borrow_mut().execute_args(
            &vec![
                "git".to_string(),
                "rev-parse".to_string(),
                "--quiet".to_string(),
                "--verify".to_string(),
                format!("{}^{{commit}}", r#ref),
            ],
            &mut output,
            Some(path.clone()),
        ) != 0
        {
            let commands = vec![
                vec![
                    "git".to_string(),
                    "remote".to_string(),
                    "set-url".to_string(),
                    "composer".to_string(),
                    "--".to_string(),
                    remote_url.clone(),
                ],
                vec![
                    "git".to_string(),
                    "fetch".to_string(),
                    "composer".to_string(),
                ],
                vec![
                    "git".to_string(),
                    "fetch".to_string(),
                    "--tags".to_string(),
                    "composer".to_string(),
                ],
            ];

            self.git_util
                .run_commands(commands, url, Some(&path), false, None)?;
        }

        let command = vec![
            "git".to_string(),
            "remote".to_string(),
            "set-url".to_string(),
            "composer".to_string(),
            "--".to_string(),
            "%sanitizedUrl%".to_string(),
        ];
        self.git_util
            .run_commands(vec![command], url, Some(&path), false, None)?;

        let pretty_version = target.get_pretty_version();
        if let Some(new_ref) =
            self.update_to_commit(target.clone(), &path, &r#ref, &pretty_version)?
        {
            if target.get_dist_reference() == target.get_source_reference() {
                // TODO(phase-b): set_dist_reference requires &mut PackageInterface
                // target.set_dist_reference(Some(new_ref.clone()));
            }
            // target.set_source_reference(Some(new_ref));
            let _ = new_ref;
        }

        let mut update_origin_url = false;
        let mut output = String::new();
        if self.inner.process.borrow_mut().execute_args(
            &vec!["git".to_string(), "remote".to_string(), "-v".to_string()],
            &mut output,
            Some(path.clone()),
        ) == 0
        {
            let mut origin_match: IndexMap<CaptureKey, String> = IndexMap::new();
            let mut composer_match: IndexMap<CaptureKey, String> = IndexMap::new();
            if Preg::is_match3(
                r"{^origin\s+(?P<url>\S+)}m",
                &output,
                Some(&mut origin_match),
            )
            .unwrap_or(false)
                && Preg::is_match3(
                    r"{^composer\s+(?P<url>\S+)}m",
                    &output,
                    Some(&mut composer_match),
                )
                .unwrap_or(false)
            {
                let origin_url = origin_match
                    .get(&CaptureKey::ByName("url".to_string()))
                    .cloned()
                    .unwrap_or_default();
                let composer_url = composer_match
                    .get(&CaptureKey::ByName("url".to_string()))
                    .cloned()
                    .unwrap_or_default();
                if origin_url == composer_url
                    && Some(composer_url.as_str()) != target.get_source_url().as_deref()
                {
                    update_origin_url = true;
                }
            }
        }
        if update_origin_url && target.get_source_url().is_some() {
            self.update_origin_url(&path, &target.get_source_url().unwrap());
        }

        Ok(None)
    }

    pub fn get_local_changes(
        &self,
        _package: PackageInterfaceHandle,
        path: &str,
    ) -> Option<String> {
        GitUtil::clean_env(&self.inner.process);
        if !self.has_metadata_repository(path) {
            return None;
        }

        let command = vec![
            "git".to_string(),
            "status".to_string(),
            "--porcelain".to_string(),
            "--untracked-files=no".to_string(),
        ];
        let mut output = String::new();
        if self.inner.process.borrow_mut().execute_args(
            &command,
            &mut output,
            Some(path.to_string()),
        ) != 0
        {
            // TODO(phase-b): cannot throw from &self / non-Result fn; bubble error via Result later
            panic!(
                "{}",
                format!(
                    "Failed to execute {}\n\n{}",
                    implode(" ", &command),
                    self.inner.process.borrow().get_error_output(),
                )
            );
        }

        let output = trim(&output, None);

        if strlen(&output) > 0 {
            Some(output)
        } else {
            None
        }
    }

    pub fn get_unpushed_changes(
        &self,
        _package: PackageInterfaceHandle,
        path: &str,
    ) -> Option<String> {
        GitUtil::clean_env(&self.inner.process);
        let path = self.normalize_path(path);
        if !self.has_metadata_repository(&path) {
            return None;
        }

        let command = vec![
            "git".to_string(),
            "show-ref".to_string(),
            "--head".to_string(),
            "-d".to_string(),
        ];
        let mut output = String::new();
        if self
            .inner
            .process
            .borrow_mut()
            .execute_args(&command, &mut output, Some(path.clone()))
            != 0
        {
            // TODO(phase-b): bubble error via Result later
            panic!(
                "{}",
                format!(
                    "Failed to execute {}\n\n{}",
                    implode(" ", &command),
                    self.inner.process.borrow().get_error_output(),
                )
            );
        }

        let mut refs = trim(&output, None);
        let mut head_match: IndexMap<CaptureKey, String> = IndexMap::new();
        if !Preg::is_match_strict_groups3(r"{^([a-f0-9]+) HEAD$}mi", &refs, Some(&mut head_match))
            .unwrap_or(false)
        {
            // could not match the HEAD for some reason
            return None;
        }
        let head_ref = head_match
            .get(&CaptureKey::ByIndex(1))
            .cloned()
            .unwrap_or_default();

        let mut branches_match: IndexMap<CaptureKey, Vec<String>> = IndexMap::new();
        if !Preg::is_match_all_strict_groups3(
            &format!("{{^{} refs/heads/(.+)$}}mi", preg_quote(&head_ref, None)),
            &refs,
            Some(&mut branches_match),
        )
        .unwrap_or(false)
        {
            // not on a branch, we are either on a not-modified tag or some sort of detached head, so skip this
            return None;
        }
        let candidate_branches: Vec<String> = branches_match
            .get(&CaptureKey::ByIndex(1))
            .cloned()
            .unwrap_or_default();

        // use the first match as branch name for now
        let mut branch = candidate_branches[0].clone();
        let mut unpushed_changes: Option<String> = None;
        let mut branch_not_found_error = false;

        // do two passes, as if we find anything we want to fetch and then re-try
        for i in 0..=1 {
            let mut remote_branches: Vec<String> = vec![];

            // try to find matching branch names in remote repos
            for candidate in &candidate_branches {
                let mut m: IndexMap<CaptureKey, Vec<String>> = IndexMap::new();
                if Preg::is_match_all_strict_groups3(
                    &format!(
                        "{{^[a-f0-9]+ refs/remotes/((?:[^/]+)/{})$}}mi",
                        preg_quote(candidate, None)
                    ),
                    &refs,
                    Some(&mut m),
                )
                .unwrap_or(false)
                {
                    let matches: Vec<String> =
                        m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default();
                    for match_ in matches {
                        branch = candidate.clone();
                        remote_branches.push(match_);
                    }
                    break;
                }
            }

            // if it doesn't exist, then we assume it is an unpushed branch
            // this is bad as we have no reference point to do a diff so we just bail listing
            // the branch as being unpushed
            if remote_branches.is_empty() {
                unpushed_changes = Some(format!(
                    "Branch {} could not be found on any remote and appears to be unpushed",
                    branch
                ));
                branch_not_found_error = true;
            } else {
                // if first iteration found no remote branch but it has now found some, reset $unpushedChanges
                // so we get the real diff output no matter its length
                if branch_not_found_error {
                    unpushed_changes = None;
                }
                for remote_branch in &remote_branches {
                    let command = vec![
                        "git".to_string(),
                        "diff".to_string(),
                        "--name-status".to_string(),
                        format!("{}...{}", remote_branch, branch),
                        "--".to_string(),
                    ];
                    let mut output = String::new();
                    if self.inner.process.borrow_mut().execute_args(
                        &command,
                        &mut output,
                        Some(path.clone()),
                    ) != 0
                    {
                        // TODO(phase-b): bubble error via Result later
                        panic!(
                            "{}",
                            format!(
                                "Failed to execute {}\n\n{}",
                                implode(" ", &command),
                                self.inner.process.borrow().get_error_output(),
                            )
                        );
                    }

                    let output = trim(&output, None);
                    // keep the shortest diff from all remote branches we compare against
                    if unpushed_changes.is_none()
                        || strlen(&output) < strlen(unpushed_changes.as_deref().unwrap_or(""))
                    {
                        unpushed_changes = Some(output);
                    }
                }
            }

            // first pass and we found unpushed changes, fetch from all remotes to make sure we have up to date
            // remotes and then try again as outdated remotes can sometimes cause false-positives
            if unpushed_changes.is_some() && i == 0 {
                let mut output = String::new();
                self.inner.process.borrow_mut().execute_args(
                    &vec!["git".to_string(), "fetch".to_string(), "--all".to_string()],
                    &mut output,
                    Some(path.clone()),
                );

                // update list of refs after fetching
                let command = vec![
                    "git".to_string(),
                    "show-ref".to_string(),
                    "--head".to_string(),
                    "-d".to_string(),
                ];
                let mut output = String::new();
                if self.inner.process.borrow_mut().execute_args(
                    &command,
                    &mut output,
                    Some(path.clone()),
                ) != 0
                {
                    // TODO(phase-b): bubble error via Result later
                    panic!(
                        "{}",
                        format!(
                            "Failed to execute {}\n\n{}",
                            implode(" ", &command),
                            self.inner.process.borrow().get_error_output(),
                        )
                    );
                }
                refs = trim(&output, None);
            }

            // abort after first pass if we didn't find anything
            if unpushed_changes.is_none() {
                break;
            }
        }

        unpushed_changes
    }

    pub(crate) async fn clean_changes(
        &mut self,
        package: PackageInterfaceHandle,
        path: &str,
        update: bool,
    ) -> Result<Option<PhpMixed>> {
        GitUtil::clean_env(&self.inner.process);
        let path = self.normalize_path(path);

        let unpushed = self.get_unpushed_changes(package.clone(), &path);
        if let Some(unpushed) = unpushed.as_deref() {
            if self.inner.io.is_interactive()
                || self
                    .inner
                    .config
                    .borrow_mut()
                    .get("discard-changes")
                    .as_bool()
                    != Some(true)
            {
                return Err(RuntimeException {
                    message: format!(
                        "Source directory {} has unpushed changes on the current branch: \n{}",
                        path, unpushed
                    ),
                    code: 0,
                }
                .into());
            }
        }

        let changes = match self.get_local_changes(package.clone(), &path) {
            Some(c) => c,
            None => return Ok(None),
        };

        if !self.inner.io.is_interactive() {
            let discard_changes = self.inner.config.borrow_mut().get("discard-changes");
            if discard_changes.as_bool() == Some(true) {
                return self.discard_changes(&path).await;
            }
            if discard_changes.as_string() == Some("stash") {
                if !update {
                    return self
                        .inner
                        .clean_changes(package.clone(), &path, update)
                        .await;
                }

                return self.stash_changes(&path).await;
            }

            return self.inner.clean_changes(package, &path, update).await;
        }

        let changes: Vec<String> = array_map(
            |elem: &String| format!("    {}", elem),
            &Preg::split(r"{\s*\r?\n\s*}", &changes)?,
        );
        self.inner.io.write_error3(
            &format!(
                "    <error>{} has modified files:</error>",
                package.get_pretty_name()
            ),
            true,
            io_interface::NORMAL,
        );
        let slice_end = 10_usize.min(changes.len());
        // TODO(phase-b): PHP passes the list directly to writeError; joined here so write_error3 takes &str
        self.inner
            .io
            .write_error3(&changes[..slice_end].join("\n"), true, io_interface::NORMAL);
        if (changes.len() as i64) > 10 {
            self.inner.io.write_error3(
                &format!(
                    "    <info>{} more files modified, choose \"v\" to view the full list</info>",
                    changes.len() as i64 - 10
                ),
                true,
                io_interface::NORMAL,
            );
        }

        'outer: loop {
            let answer = self
                .inner
                .io
                .ask(
                    format!(
                        "    <info>Discard changes [y,n,v,{}?]?</info> ",
                        if update { "s," } else { "" }
                    ),
                    PhpMixed::String("?".to_string()),
                )
                .as_string()
                .map(|s| s.to_string());
            let mut do_help = false;
            match answer.as_deref() {
                Some("y") => {
                    self.discard_changes(&path).await?;
                    break 'outer;
                }
                Some("s") => {
                    if !update {
                        // goto help;
                        do_help = true;
                    } else {
                        self.stash_changes(&path).await?;
                        break 'outer;
                    }
                }
                Some("n") => {
                    return Err(RuntimeException {
                        message: "Update aborted".to_string(),
                        code: 0,
                    }
                    .into());
                }
                Some("v") => {
                    // TODO(phase-b): PHP passes list directly; joined here for &str arg
                    self.inner
                        .io
                        .write_error3(&changes.join("\n"), true, io_interface::NORMAL);
                }
                Some("d") => {
                    self.view_diff(&path);
                }
                _ => {
                    // case '?': default:
                    do_help = true;
                }
            }

            if do_help {
                // help:
                // TODO(phase-b): PHP passes list directly; joined here for &str arg
                self.inner.io.write_error3(
                    &[
                        format!(
                            "    y - discard changes and apply the {}",
                            if update { "update" } else { "uninstall" }
                        ),
                        format!(
                            "    n - abort the {} and let you manually clean things up",
                            if update { "update" } else { "uninstall" }
                        ),
                        "    v - view modified files".to_string(),
                        "    d - view local modifications (diff)".to_string(),
                    ]
                    .join("\n"),
                    true,
                    io_interface::NORMAL,
                );
                if update {
                    self.inner.io.write_error3(
                        "    s - stash changes and try to reapply them after the update",
                        true,
                        io_interface::NORMAL,
                    );
                }
                self.inner
                    .io
                    .write_error3("    ? - print help", true, io_interface::NORMAL);
            }
        }

        Ok(None)
    }

    pub(crate) fn reapply_changes(&mut self, path: &str) -> Result<()> {
        let path = self.normalize_path(path);
        if self
            .has_stashed_changes
            .get(&path)
            .copied()
            .unwrap_or(false)
        {
            self.has_stashed_changes.shift_remove(&path);
            self.inner.io.write_error3(
                "    <info>Re-applying stashed changes</info>",
                true,
                io_interface::NORMAL,
            );
            let mut output = String::new();
            if self.inner.process.borrow_mut().execute_args(
                &vec!["git".to_string(), "stash".to_string(), "pop".to_string()],
                &mut output,
                Some(path.clone()),
            ) != 0
            {
                return Err(RuntimeException {
                    message: format!(
                        "Failed to apply stashed changes:\n\n{}",
                        self.inner.process.borrow().get_error_output()
                    ),
                    code: 0,
                }
                .into());
            }
        }

        self.has_discarded_changes.shift_remove(&path);
        Ok(())
    }

    /// Updates the given path to the given commit ref
    ///
    /// @throws \RuntimeException
    /// @return null|string       if a string is returned, it is the commit reference that was checked out if the original could not be found
    pub(crate) fn update_to_commit(
        &mut self,
        package: PackageInterfaceHandle,
        path: &str,
        reference: &str,
        pretty_version: &str,
    ) -> Result<Option<String>> {
        let force: Vec<String> = if self
            .has_discarded_changes
            .get(path)
            .copied()
            .unwrap_or(false)
            || self.has_stashed_changes.get(path).copied().unwrap_or(false)
        {
            vec!["-f".to_string()]
        } else {
            vec![]
        };

        // This uses the "--" sequence to separate branch from file parameters.
        //
        // Otherwise git tries the branch name as well as file name.
        // If the non-existent branch is actually the name of a file, the file
        // is checked out.

        let mut branch = Preg::replace(r"{(?:^dev-|(?:\.x)?-dev$)}i", "", &pretty_version)?;

        // Closure equivalent: $execute = function(array $command) use (&$output, $path) { ... };
        // Inlined below at each call site.

        let mut branches: Option<String> = None;
        {
            let mut output = String::new();
            if self.inner.process.borrow_mut().execute_args(
                &vec!["git".to_string(), "branch".to_string(), "-r".to_string()],
                &mut output,
                Some(path.to_string()),
            ) == 0
            {
                branches = Some(output);
            }
        }

        // check whether non-commitish are branches or tags, and fetch branches with the remote name
        let git_ref = reference.to_string();
        if !Preg::is_match(r"{^[a-f0-9]{40}$}", reference).unwrap_or(false)
            && branches.is_some()
            && Preg::is_match(
                &format!("{{^\\s+composer/{}$}}m", preg_quote(reference, None)),
                branches.as_deref().unwrap_or(""),
            )
            .unwrap_or(false)
        {
            let mut command1: Vec<String> = vec!["git".to_string(), "checkout".to_string()];
            command1.extend(force.clone());
            command1.extend(vec![
                "-B".to_string(),
                branch.clone(),
                format!("composer/{}", reference),
                "--".to_string(),
            ]);
            let command2 = vec![
                "git".to_string(),
                "reset".to_string(),
                "--hard".to_string(),
                format!("composer/{}", reference),
                "--".to_string(),
            ];

            let mut output = String::new();
            let ok1 = self.inner.process.borrow_mut().execute_args(
                &command1,
                &mut output,
                Some(path.to_string()),
            ) == 0;
            let ok2 = if ok1 {
                let mut output = String::new();
                self.inner.process.borrow_mut().execute_args(
                    &command2,
                    &mut output,
                    Some(path.to_string()),
                ) == 0
            } else {
                false
            };
            if ok1 && ok2 {
                return Ok(None);
            }
        }

        // try to checkout branch by name and then reset it so it's on the proper branch name
        if Preg::is_match(r"{^[a-f0-9]{40}$}", reference).unwrap_or(false) {
            // add 'v' in front of the branch if it was stripped when generating the pretty name
            if branches.is_some()
                && !Preg::is_match(
                    &format!("{{^\\s+composer/{}$}}m", preg_quote(&branch, None)),
                    branches.as_deref().unwrap_or(""),
                )
                .unwrap_or(false)
                && Preg::is_match(
                    &format!("{{^\\s+composer/v{}$}}m", preg_quote(&branch, None)),
                    branches.as_deref().unwrap_or(""),
                )
                .unwrap_or(false)
            {
                branch = format!("v{}", branch);
            }

            let command = vec![
                "git".to_string(),
                "checkout".to_string(),
                branch.clone(),
                "--".to_string(),
            ];
            let mut fallback_command: Vec<String> = vec!["git".to_string(), "checkout".to_string()];
            fallback_command.extend(force.clone());
            fallback_command.extend(vec![
                "-B".to_string(),
                branch.clone(),
                format!("composer/{}", branch),
                "--".to_string(),
            ]);
            let reset_command = vec![
                "git".to_string(),
                "reset".to_string(),
                "--hard".to_string(),
                reference.to_string(),
                "--".to_string(),
            ];

            let mut output = String::new();
            let ok_command = self.inner.process.borrow_mut().execute_args(
                &command,
                &mut output,
                Some(path.to_string()),
            ) == 0;
            let ok_fallback = if !ok_command {
                let mut output = String::new();
                self.inner.process.borrow_mut().execute_args(
                    &fallback_command,
                    &mut output,
                    Some(path.to_string()),
                ) == 0
            } else {
                false
            };
            let ok_reset = if ok_command || ok_fallback {
                let mut output = String::new();
                self.inner.process.borrow_mut().execute_args(
                    &reset_command,
                    &mut output,
                    Some(path.to_string()),
                ) == 0
            } else {
                false
            };
            if (ok_command || ok_fallback) && ok_reset {
                return Ok(None);
            }
        }

        let mut command1: Vec<String> = vec!["git".to_string(), "checkout".to_string()];
        command1.extend(force.clone());
        command1.extend(vec![git_ref.clone(), "--".to_string()]);
        let command2 = vec![
            "git".to_string(),
            "reset".to_string(),
            "--hard".to_string(),
            git_ref.clone(),
            "--".to_string(),
        ];
        {
            let mut output = String::new();
            let ok1 = self.inner.process.borrow_mut().execute_args(
                &command1,
                &mut output,
                Some(path.to_string()),
            ) == 0;
            let ok2 = if ok1 {
                let mut output = String::new();
                self.inner.process.borrow_mut().execute_args(
                    &command2,
                    &mut output,
                    Some(path.to_string()),
                ) == 0
            } else {
                false
            };
            if ok1 && ok2 {
                return Ok(None);
            }
        }

        let mut exception_extra = String::new();

        // reference was not found (prints "fatal: reference is not a tree: $ref")
        if strpos(self.inner.process.borrow().get_error_output(), reference).is_some() {
            self.inner.io.write_error3(
                &format!(
                    "    <warning>{} is gone (history was rewritten?)</warning>",
                    reference
                ),
                true,
                io_interface::NORMAL,
            );
            exception_extra = format!(
                "\nIt looks like the commit hash is not available in the repository, maybe {}? Run \"composer update {}\" to resolve this.",
                if package.is_dev() {
                    "the commit was removed from the branch"
                } else {
                    "the tag was recreated"
                },
                package.get_pretty_name(),
            );
        }

        let command = format!("{} && {}", implode(" ", &command1), implode(" ", &command2));

        Err(RuntimeException {
            message: Url::sanitize(format!(
                "Failed to execute {}\n\n{}{}",
                command,
                self.inner.process.borrow().get_error_output(),
                exception_extra,
            )),
            code: 0,
        }
        .into())
    }

    pub(crate) fn update_origin_url(&mut self, path: &str, url: &str) {
        let mut output = String::new();
        self.inner.process.borrow_mut().execute_args(
            &vec![
                "git".to_string(),
                "remote".to_string(),
                "set-url".to_string(),
                "origin".to_string(),
                "--".to_string(),
                url.to_string(),
            ],
            &mut output,
            Some(path.to_string()),
        );
        self.set_push_url(path, url);
    }

    pub(crate) fn set_push_url(&mut self, path: &str, url: &str) {
        // set push url for github projects
        let mut match_: IndexMap<CaptureKey, String> = IndexMap::new();
        if Preg::is_match3(
            &format!(
                "{{^(?:https?|git)://{}/([^/]+)/([^/]+?)(?:\\.git)?$}}",
                GitUtil::get_github_domains_regex(&*self.inner.config.borrow())
            ),
            url,
            Some(&mut match_),
        )
        .unwrap_or(false)
        {
            let protocols = self.inner.config.borrow_mut().get("github-protocols");
            let m1 = match_
                .get(&CaptureKey::ByIndex(1))
                .cloned()
                .unwrap_or_default();
            let m2 = match_
                .get(&CaptureKey::ByIndex(2))
                .cloned()
                .unwrap_or_default();
            let m3 = match_
                .get(&CaptureKey::ByIndex(3))
                .cloned()
                .unwrap_or_default();
            let mut push_url = format!("git@{}:{}/{}.git", m1, m2, m3);
            if !in_array(PhpMixed::String("ssh".to_string()), &protocols, true) {
                push_url = format!("https://{}/{}/{}.git", m1, m2, m3);
            }
            let cmd = vec![
                "git".to_string(),
                "remote".to_string(),
                "set-url".to_string(),
                "--push".to_string(),
                "origin".to_string(),
                "--".to_string(),
                push_url,
            ];
            let mut ignored_output = String::new();
            self.inner.process.borrow_mut().execute_args(
                &cmd,
                &mut ignored_output,
                Some(path.to_string()),
            );
        }
    }

    pub(crate) fn get_commit_logs(
        &mut self,
        from_reference: &str,
        to_reference: &str,
        path: &str,
    ) -> Result<String> {
        let path = self.normalize_path(path);
        let mut args = vec![
            "--format=%h - %an: %s".to_string(),
            format!("{}..{}", from_reference, to_reference),
        ];
        args.extend(GitUtil::get_no_show_signature_flags(&self.inner.process));
        let command = GitUtil::build_rev_list_command(&self.inner.process, args);

        let mut output = String::new();
        if self
            .inner
            .process
            .borrow_mut()
            .execute_args(&command, &mut output, Some(path.clone()))
            != 0
        {
            return Err(RuntimeException {
                message: format!(
                    "Failed to execute {}\n\n{}",
                    implode(" ", &command),
                    self.inner.process.borrow().get_error_output(),
                ),
                code: 0,
            }
            .into());
        }

        Ok(GitUtil::parse_rev_list_output(&output, &self.inner.process))
    }

    /// @phpstan-return PromiseInterface<void|null>
    /// @throws \RuntimeException
    pub(crate) async fn discard_changes(&mut self, path: &str) -> Result<Option<PhpMixed>> {
        let path = self.normalize_path(path);
        let mut output = String::new();
        if self.inner.process.borrow_mut().execute_args(
            &vec!["git".to_string(), "clean".to_string(), "-df".to_string()],
            &mut output,
            Some(path.clone()),
        ) != 0
        {
            return Err(RuntimeException {
                message: format!("Could not reset changes\n\n:{}", output),
                code: 0,
            }
            .into());
        }
        let mut output = String::new();
        if self.inner.process.borrow_mut().execute_args(
            &vec!["git".to_string(), "reset".to_string(), "--hard".to_string()],
            &mut output,
            Some(path.clone()),
        ) != 0
        {
            return Err(RuntimeException {
                message: format!("Could not reset changes\n\n:{}", output),
                code: 0,
            }
            .into());
        }

        self.has_discarded_changes.insert(path, true);

        Ok(None)
    }

    /// @phpstan-return PromiseInterface<void|null>
    /// @throws \RuntimeException
    pub(crate) async fn stash_changes(&mut self, path: &str) -> Result<Option<PhpMixed>> {
        let path = self.normalize_path(path);
        let mut output = String::new();
        if self.inner.process.borrow_mut().execute_args(
            &vec![
                "git".to_string(),
                "stash".to_string(),
                "--include-untracked".to_string(),
            ],
            &mut output,
            Some(path.clone()),
        ) != 0
        {
            return Err(RuntimeException {
                message: format!("Could not stash changes\n\n:{}", output),
                code: 0,
            }
            .into());
        }

        self.has_stashed_changes.insert(path, true);

        Ok(None)
    }

    /// @throws \RuntimeException
    pub(crate) fn view_diff(&mut self, path: &str) {
        let path = self.normalize_path(path);
        let mut output = String::new();
        if self.inner.process.borrow_mut().execute_args(
            &vec!["git".to_string(), "diff".to_string(), "HEAD".to_string()],
            &mut output,
            Some(path.clone()),
        ) != 0
        {
            // TODO(phase-b): cannot throw from non-Result fn; bubble error via Result later
            panic!("{}", format!("Could not view diff\n\n:{}", output));
        }

        self.inner
            .io
            .write_error3(&output, true, io_interface::NORMAL);
    }

    pub(crate) fn normalize_path(&self, path: &str) -> String {
        let mut path = path.to_string();
        if Platform::is_windows() && strlen(&path) > 0 {
            let mut base_path = path.clone();
            let mut removed: Vec<String> = vec![];

            while !is_dir(&base_path) && base_path != "\\" {
                let mut new_removed = vec![basename(&base_path)];
                new_removed.extend(removed);
                removed = new_removed;
                base_path = dirname(&base_path);
            }

            if base_path == "\\" {
                return path;
            }

            path = rtrim(
                &format!(
                    "{}/{}",
                    realpath(&base_path).unwrap_or_default(),
                    implode("/", &removed),
                ),
                Some("/"),
            );
        }

        path
    }

    pub(crate) fn has_metadata_repository(&self, path: &str) -> bool {
        let path = self.normalize_path(path);

        is_dir(&format!("{}/.git", path))
    }

    pub(crate) fn get_short_hash(&self, reference: &str) -> String {
        if !self.inner.io.is_verbose()
            && Preg::is_match(r"{^[0-9a-f]{40}$}", reference).unwrap_or(false)
        {
            return substr(reference, 0, Some(10));
        }

        reference.to_string()
    }
}

impl DvcsDownloaderInterface for GitDownloader {
    fn get_unpushed_changes(
        &self,
        package: PackageInterfaceHandle,
        path: String,
    ) -> Option<String> {
        GitDownloader::get_unpushed_changes(self, package, &path)
    }
}

// TODO(phase-b): GitDownloader extends VcsDownloader which implements DownloaderInterface.
// Delegating each trait method to todo!() until the inner VcsDownloaderBase exposes the
// matching impl surface.
#[async_trait::async_trait(?Send)]
impl crate::downloader::DownloaderInterface for GitDownloader {
    fn get_installation_source(&self) -> String {
        todo!()
    }

    async fn download(
        &self,
        _package: PackageInterfaceHandle,
        _path: &str,
        _prev_package: Option<PackageInterfaceHandle>,
        _output: bool,
    ) -> anyhow::Result<Option<PhpMixed>> {
        todo!()
    }

    async fn prepare(
        &self,
        _type: &str,
        _package: PackageInterfaceHandle,
        _path: &str,
        _prev_package: Option<PackageInterfaceHandle>,
    ) -> anyhow::Result<Option<PhpMixed>> {
        todo!()
    }

    async fn install(
        &self,
        _package: PackageInterfaceHandle,
        _path: &str,
        _output: bool,
    ) -> anyhow::Result<Option<PhpMixed>> {
        todo!()
    }

    async fn update(
        &self,
        _initial: PackageInterfaceHandle,
        _target: PackageInterfaceHandle,
        _path: &str,
    ) -> anyhow::Result<Option<PhpMixed>> {
        todo!()
    }

    async fn remove(
        &self,
        _package: PackageInterfaceHandle,
        _path: &str,
        _output: bool,
    ) -> anyhow::Result<Option<PhpMixed>> {
        todo!()
    }

    async fn cleanup(
        &self,
        _type: &str,
        _package: PackageInterfaceHandle,
        _path: &str,
        _prev_package: Option<PackageInterfaceHandle>,
    ) -> anyhow::Result<Option<PhpMixed>> {
        todo!()
    }
}