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
|
//! ref: composer/src/Composer/Util/Git.php
use crate::io::io_interface;
use anyhow::Result;
use indexmap::IndexMap;
use std::sync::Mutex;
use shirabe_external_packages::composer::pcre::preg::{CaptureKey, Preg};
use shirabe_php_shim::{
InvalidArgumentException, PHP_EOL, PhpMixed, RuntimeException, array_map,
array_merge_recursive, clearstatcache, count, explode, implode, in_array, is_array,
is_callable, is_dir, preg_quote, rawurldecode, rawurlencode, str_contains, str_ends_with,
str_replace, str_replace_array, strlen, strpos, substr, trim, version_compare,
};
use crate::config::Config;
use crate::io::io_interface::IOInterface;
use crate::util::auth_helper::{AuthHelper, StoreAuth};
use crate::util::bitbucket::Bitbucket;
use crate::util::filesystem::Filesystem;
use crate::util::github::GitHub;
use crate::util::gitlab::GitLab;
use crate::util::http_downloader::HttpDownloader;
use crate::util::platform::Platform;
use crate::util::process_executor::ProcessExecutor;
use crate::util::url::Url;
#[derive(Debug)]
pub struct Git {
pub(crate) io: Box<dyn IOInterface>,
pub(crate) config: std::rc::Rc<std::cell::RefCell<Config>>,
pub(crate) process: std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
pub(crate) filesystem: std::rc::Rc<std::cell::RefCell<Filesystem>>,
pub(crate) http_downloader: Option<std::rc::Rc<std::cell::RefCell<HttpDownloader>>>,
}
/// @var string|false|null
static VERSION: Mutex<Option<Option<String>>> = Mutex::new(None);
impl Git {
pub fn new(
io: Box<dyn IOInterface>,
config: std::rc::Rc<std::cell::RefCell<Config>>,
process: std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
fs: std::rc::Rc<std::cell::RefCell<Filesystem>>,
) -> Self {
Self {
io,
config,
process,
filesystem: fs,
http_downloader: None,
}
}
/// @param IOInterface|null $io If present, a warning is output there instead of throwing, so pass this in only for cases where this is a soft failure
pub fn check_for_repo_ownership_error(
output: &str,
path: &str,
io: Option<&dyn IOInterface>,
) -> Result<()> {
if str_contains(output, "fatal: detected dubious ownership") {
let msg = format!(
"The repository at \"{}\" does not have the correct ownership and git refuses to use it:{}{}{}",
path, PHP_EOL, PHP_EOL, output
);
match io {
None => {
return Err(RuntimeException {
message: msg,
code: 0,
}
.into());
}
Some(io) => {
io.write_error3(
&format!("<warning>{}</warning>", msg),
true,
io_interface::NORMAL,
);
}
}
}
Ok(())
}
pub fn set_http_downloader(
&mut self,
http_downloader: std::rc::Rc<std::cell::RefCell<HttpDownloader>>,
) {
self.http_downloader = Some(http_downloader);
}
/// Runs a set of commands using the $url or a variation of it (with auth, ssh, ..)
///
/// Commands should use %url% placeholders for the URL instead of inlining it to allow this function to do its job
/// %sanitizedUrl% is also automatically replaced by the url without user/pass
///
/// As soon as a single command fails it will halt, so assume the commands are run as && in bash
///
/// @param non-empty-array<non-empty-list<string>> $commands
/// @param mixed $commandOutput the output will be written into this var if passed by ref
/// if a callable is passed it will be used as output handler
pub fn run_commands(
&mut self,
commands: Vec<Vec<String>>,
url: &str,
cwd: Option<&str>,
initial_clone: bool,
command_output: Option<&mut PhpMixed>,
) -> Result<()> {
let mut callables: Vec<Box<dyn Fn(&str) -> Vec<String>>> = vec![];
for cmd in commands {
let cmd_clone = cmd.clone();
callables.push(Box::new(move |url: &str| -> Vec<String> {
let mut map: IndexMap<String, String> = IndexMap::new();
map.insert("%url%".to_string(), url.to_string());
map.insert(
"%sanitizedUrl%".to_string(),
Preg::replace(r"{://([^@]+?):(.+?)@}", "://", &url).unwrap_or_default(),
);
array_map(
|value: &String| map.get(value).cloned().unwrap_or_else(|| value.clone()),
&cmd_clone,
)
}));
}
// @phpstan-ignore method.deprecated
self.run_command(callables, url, cwd, initial_clone, command_output)
}
/// @param callable|array<callable> $commandCallable
/// @param mixed $commandOutput the output will be written into this var if passed by ref
/// if a callable is passed it will be used as output handler
/// @deprecated Use runCommands with placeholders instead of callbacks for simplicity
pub fn run_command(
&mut self,
command_callable: Vec<Box<dyn Fn(&str) -> Vec<String>>>,
url: &str,
cwd: Option<&str>,
initial_clone: bool,
mut command_output: Option<&mut PhpMixed>,
) -> Result<()> {
let command_callables = command_callable;
let mut last_command: PhpMixed = PhpMixed::String(String::new());
// Ensure we are allowed to use this URL by config
self.config.borrow_mut().prohibit_url_by_config(
url,
Some(self.io.as_ref()),
&IndexMap::new(),
)?;
let orig_cwd: Option<String> = if initial_clone {
cwd.map(|s| s.to_string())
} else {
None
};
// TODO(phase-b): closure captures &mut self.process, &mut last_command, etc.
// Inlined as a helper that returns (status, last_command, output)
let cwd_string = cwd.map(|s| s.to_string());
// PHP closure: $runCommands = function ($url) use (...) { ... };
let mut run_commands_inline = |url_arg: &str,
this_process: &mut ProcessExecutor,
last_cmd: &mut PhpMixed,
command_output: Option<&mut PhpMixed>|
-> i64 {
let collect_outputs = !command_output
.as_ref()
.map(|v| is_callable(v))
.unwrap_or(false);
let mut outputs: Vec<String> = vec![];
let mut status: i64 = 0;
let mut counter: i64 = 0;
for callable in &command_callables {
let cmd = callable(url_arg);
*last_cmd = PhpMixed::List(
cmd.iter()
.map(|s| Box::new(PhpMixed::String(s.clone())))
.collect(),
);
let mut local_output = String::new();
let exec_cwd = if initial_clone && counter == 0 {
None
} else {
cwd_string.clone()
};
status = this_process.execute_args(&cmd, &mut local_output, exec_cwd);
if collect_outputs {
outputs.push(local_output);
}
if status != 0 {
break;
}
counter += 1;
}
if collect_outputs {
if let Some(out) = command_output {
*out = PhpMixed::String(implode("", &outputs));
}
}
status
};
if Preg::is_match(r"{^ssh://[^@]+@[^:]+:[^0-9]+}", url).unwrap_or(false) {
return Err(InvalidArgumentException {
message: format!(
"The source URL {} is invalid, ssh URLs should have a port number after \":\".\nUse ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.",
url
),
code: 0,
}
.into());
}
if !initial_clone {
// capture username/password from URL if there is one and we have no auth configured yet
let mut output = String::new();
self.process.borrow_mut().execute_args(
&vec!["git".to_string(), "remote".to_string(), "-v".to_string()],
&mut output,
cwd.map(|s| s.to_string()),
);
let mut m: IndexMap<CaptureKey, String> = IndexMap::new();
if Preg::is_match_strict_groups3(
r"{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im",
&output,
Some(&mut m),
)
.unwrap_or(false)
{
let m3 = m.get(&CaptureKey::ByIndex(3)).cloned().unwrap_or_default();
if !self.io.has_authentication(&m3) {
self.io.set_authentication(
m3.clone(),
rawurldecode(&m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default()),
Some(rawurldecode(
&m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default(),
)),
);
}
}
}
let protocols = self.config.borrow_mut().get("github-protocols");
// public github, autoswitch protocols
// @phpstan-ignore composerPcre.maybeUnsafeStrictGroups
let mut m: IndexMap<CaptureKey, String> = IndexMap::new();
if Preg::is_match_strict_groups3(
&format!(
"{{^(?:https?|git)://{}/(.*)}}",
Self::get_github_domains_regex(&*self.config.borrow())
),
url,
Some(&mut m),
)
.unwrap_or(false)
{
let mut messages: Vec<String> = vec![];
let protocols_list: Vec<String> = match &protocols {
PhpMixed::List(l) => l
.iter()
.filter_map(|v| v.as_string().map(|s| s.to_string()))
.collect(),
_ => vec![],
};
for protocol in &protocols_list {
let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default();
let m2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default();
let proto_url = if protocol == "ssh" {
format!("git@{}:{}", m1, m2)
} else {
format!("{}://{}/{}", protocol, m1, m2)
};
if run_commands_inline(
&proto_url,
&mut *self.process.borrow_mut(),
&mut last_command,
command_output.as_deref_mut(),
) == 0
{
return Ok(());
}
messages.push(format!(
"- {}\n{}",
proto_url,
Preg::replace(
r"#^#m",
" ",
&self.process.borrow().get_error_output().to_string()
)
.unwrap_or_default()
));
if initial_clone {
if let Some(ref orig) = orig_cwd {
self.filesystem.borrow_mut().remove_directory(orig);
}
}
}
// failed to checkout, first check git accessibility
let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default();
if !self.io.has_authentication(&m1) && !self.io.is_interactive() {
self.throw_exception(
&format!(
"Failed to clone {} via {} protocols, aborting.\n\n{}",
url,
implode(", ", &protocols_list),
implode("\n", &messages)
),
url,
)?;
}
}
// if we have a private github url and the ssh protocol is disabled then we skip it and directly fallback to https
let protocols_list: Vec<String> = match self.config.borrow_mut().get("github-protocols") {
PhpMixed::List(l) => l
.iter()
.filter_map(|v| v.as_string().map(|s| s.to_string()))
.collect(),
_ => vec![],
};
let bypass_ssh_for_github = Preg::is_match(
&format!(
"{{^git@{}:(.+?)\\.git$}}i",
Self::get_github_domains_regex(&*self.config.borrow())
),
url,
)
.unwrap_or(false)
&& !in_array(
PhpMixed::String("ssh".to_string()),
&PhpMixed::List(
protocols_list
.iter()
.map(|s| Box::new(PhpMixed::String(s.clone())))
.collect(),
),
true,
);
let mut auth: Option<IndexMap<String, Option<String>>> = None;
let mut credentials: Vec<String> = vec![];
if bypass_ssh_for_github
|| 0 != run_commands_inline(
url,
&mut *self.process.borrow_mut(),
&mut last_command,
command_output.as_deref_mut(),
)
{
let mut error_msg = self.process.borrow().get_error_output().to_string();
// private github repository without ssh key access, try https with auth
// @phpstan-ignore composerPcre.maybeUnsafeStrictGroups
let mut m: IndexMap<CaptureKey, String> = IndexMap::new();
let github_matched = Preg::is_match_strict_groups3(
&format!(
"{{^git@{}:(.+?)\\.git$}}i",
Self::get_github_domains_regex(&*self.config.borrow())
),
url,
Some(&mut m),
)
.unwrap_or(false)
|| Preg::is_match_strict_groups3(
&format!(
"{{^https?://{}/(.*?)(?:\\.git)?$}}i",
Self::get_github_domains_regex(&*self.config.borrow())
),
url,
Some(&mut m),
)
.unwrap_or(false);
if github_matched {
let m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default();
let m2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default();
if !self.io.has_authentication(&m1) {
let mut git_hub_util = GitHub::new(
self.io.clone_box(),
std::rc::Rc::clone(&self.config),
Some(std::rc::Rc::clone(&self.process)),
self.http_downloader.clone(),
)?;
let message = "Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos";
if !git_hub_util.authorize_oauth(&m1) && self.io.is_interactive() {
git_hub_util.authorize_oauth_interactively(&m1, Some(message));
}
}
if self.io.has_authentication(&m1) {
auth = Some(self.io.get_authentication(&m1));
let auth_inner = auth.as_ref().unwrap();
let username = auth_inner
.get("username")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let password = auth_inner
.get("password")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let auth_url = format!(
"https://{}:{}@{}/{}.git",
rawurlencode(&username),
rawurlencode(&password),
m1,
m2
);
if run_commands_inline(
&auth_url,
&mut *self.process.borrow_mut(),
&mut last_command,
command_output.as_deref_mut(),
) == 0
{
return Ok(());
}
credentials = vec![rawurlencode(&username), rawurlencode(&password)];
error_msg = self.process.borrow().get_error_output().to_string();
}
} else if {
let bb_matched = Preg::is_match_strict_groups3(
r"{^(https?)://(bitbucket\.org)/(.*?)(?:\.git)?$}i",
url,
Some(&mut m),
)
.unwrap_or(false)
|| Preg::is_match_strict_groups3(
r"{^(git)@(bitbucket\.org):(.+?\.git)$}i",
url,
Some(&mut m),
)
.unwrap_or(false);
bb_matched
} {
// bitbucket either through oauth or app password, with fallback to ssh.
let mut bitbucket_util = Bitbucket::new(
self.io.clone_box(),
std::rc::Rc::clone(&self.config),
Some(std::rc::Rc::clone(&self.process)),
self.http_downloader.clone(),
None,
)?;
let domain = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default();
let mut repo_with_git_part =
m.get(&CaptureKey::ByIndex(3)).cloned().unwrap_or_default();
if !str_ends_with(&repo_with_git_part, ".git") {
repo_with_git_part.push_str(".git");
}
if !self.io.has_authentication(&domain) {
let message = "Enter your Bitbucket credentials to access private repos";
if !bitbucket_util.authorize_oauth(&domain) && self.io.is_interactive() {
bitbucket_util.authorize_oauth_interactively(&domain, Some(message));
let access_token = bitbucket_util.get_token();
self.io.set_authentication(
domain.clone(),
"x-token-auth".to_string(),
Some(access_token),
);
}
}
// First we try to authenticate with whatever we have stored.
if self.io.has_authentication(&domain) {
auth = Some(self.io.get_authentication(&domain));
let mut username = auth
.as_ref()
.unwrap()
.get("username")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let password = auth
.as_ref()
.unwrap()
.get("password")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
// Bitbucket API tokens use the email address as the username for HTTP API calls and
// either the Bitbucket username or 'x-bitbucket-api-token-auth' as the username for git operations.
if strpos(&password, "ATAT") == Some(0) {
username = "x-bitbucket-api-token-auth".to_string();
}
let auth_url = format!(
"https://{}:{}@{}/{}",
rawurlencode(&username),
rawurlencode(&password),
domain,
repo_with_git_part
);
if run_commands_inline(
&auth_url,
&mut *self.process.borrow_mut(),
&mut last_command,
command_output.as_deref_mut(),
) == 0
{
return Ok(());
}
// We already have an access_token from a previous request.
if username != "x-token-auth" {
let access_token =
bitbucket_util.request_token(&domain, &username, &password)?;
if !access_token.is_empty() {
self.io.set_authentication(
domain.clone(),
"x-token-auth".to_string(),
Some(access_token),
);
}
}
}
if self.io.has_authentication(&domain) {
auth = Some(self.io.get_authentication(&domain));
let username = auth
.as_ref()
.unwrap()
.get("username")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let password = auth
.as_ref()
.unwrap()
.get("password")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let auth_url = format!(
"https://{}:{}@{}/{}",
rawurlencode(&username),
rawurlencode(&password),
domain,
repo_with_git_part
);
if run_commands_inline(
&auth_url,
&mut *self.process.borrow_mut(),
&mut last_command,
command_output.as_deref_mut(),
) == 0
{
return Ok(());
}
credentials = vec![rawurlencode(&username), rawurlencode(&password)];
}
// Falling back to ssh
let ssh_url = format!("git@bitbucket.org:{}", repo_with_git_part);
self.io.write_error3(
" No bitbucket authentication configured. Falling back to ssh.",
true,
io_interface::NORMAL,
);
if run_commands_inline(
&ssh_url,
&mut *self.process.borrow_mut(),
&mut last_command,
command_output.as_deref_mut(),
) == 0
{
return Ok(());
}
error_msg = self.process.borrow().get_error_output().to_string();
} else if {
let gl_matched = Preg::is_match_strict_groups3(
&format!(
"{{^(git)@{}:(.+?\\.git)$}}i",
Self::get_gitlab_domains_regex(&*self.config.borrow())
),
url,
Some(&mut m),
)
.unwrap_or(false)
|| Preg::is_match_strict_groups3(
&format!(
"{{^(https?)://{}/(.*)}}i",
Self::get_gitlab_domains_regex(&*self.config.borrow())
),
url,
Some(&mut m),
)
.unwrap_or(false);
gl_matched
} {
let mut m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default();
let m2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default();
let m3 = m.get(&CaptureKey::ByIndex(3)).cloned().unwrap_or_default();
if m1 == "git" {
m1 = "https".to_string();
}
if !self.io.has_authentication(&m2) {
let mut git_lab_util = GitLab::new(
self.io.clone_box(),
std::rc::Rc::clone(&self.config),
Some(std::rc::Rc::clone(&self.process)),
self.http_downloader.clone(),
)?;
let message =
"Cloning failed, enter your GitLab credentials to access private repos";
if !git_lab_util.authorize_oauth(&m2) && self.io.is_interactive() {
git_lab_util.authorize_oauth_interactively(&m1, &m2, Some(message));
}
}
if self.io.has_authentication(&m2) {
auth = Some(self.io.get_authentication(&m2));
let username = auth
.as_ref()
.unwrap()
.get("username")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let password = auth
.as_ref()
.unwrap()
.get("password")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let auth_url = if password == "private-token"
|| password == "oauth2"
|| password == "gitlab-ci-token"
{
format!(
"{}://{}:{}@{}/{}",
m1,
rawurlencode(&password),
rawurlencode(&username),
m2,
m3
) // swap username and password
} else {
format!(
"{}://{}:{}@{}/{}",
m1,
rawurlencode(&username),
rawurlencode(&password),
m2,
m3
)
};
if run_commands_inline(
&auth_url,
&mut *self.process.borrow_mut(),
&mut last_command,
command_output.as_deref_mut(),
) == 0
{
return Ok(());
}
credentials = vec![rawurlencode(&username), rawurlencode(&password)];
error_msg = self.process.borrow().get_error_output().to_string();
}
} else if let Some(m) = self.get_authentication_failure(url) {
// private non-github/gitlab/bitbucket repo that failed to authenticate
let mut m1 = m.get(&CaptureKey::ByIndex(1)).cloned().unwrap_or_default();
let mut m2 = m.get(&CaptureKey::ByIndex(2)).cloned().unwrap_or_default();
let m3 = m.get(&CaptureKey::ByIndex(3)).cloned().unwrap_or_default();
let mut auth_parts: Option<String> = None;
if str_contains(&m2, "@") {
let parts = explode("@", &m2);
auth_parts = parts.get(0).cloned();
m2 = parts.get(1).cloned().unwrap_or_default();
}
let mut store_auth: PhpMixed = PhpMixed::Bool(false);
if self.io.has_authentication(&m2) {
auth = Some(self.io.get_authentication(&m2));
} else if self.io.is_interactive() {
let mut default_username: Option<String> = None;
if let Some(ref parts) = auth_parts {
if !parts.is_empty() {
if str_contains(parts, ":") {
let split = explode(":", parts);
default_username = split.get(0).cloned();
} else {
default_username = Some(parts.clone());
}
}
}
self.io.write_error3(
&format!(" Authentication required (<info>{}</info>):", m2),
true,
io_interface::NORMAL,
);
self.io.write_error3(
&format!("<warning>{}</warning>", trim(&error_msg, None)),
true,
io_interface::VERBOSE,
);
let mut auth_map: IndexMap<String, Option<String>> = IndexMap::new();
auth_map.insert(
"username".to_string(),
self.io
.ask(
" Username: ".to_string(),
default_username
.clone()
.map(PhpMixed::String)
.unwrap_or(PhpMixed::Null),
)
.as_string()
.map(|s| s.to_string()),
);
auth_map.insert(
"password".to_string(),
self.io.ask_and_hide_answer(" Password: ".to_string()),
);
auth = Some(auth_map);
store_auth = self.config.borrow_mut().get("store-auths");
}
if let Some(auth_inner) = auth.as_ref() {
let username = auth_inner
.get("username")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let password = auth_inner
.get("password")
.cloned()
.unwrap_or(None)
.unwrap_or_default();
let auth_url = format!(
"{}{}:{}@{}{}",
m1,
rawurlencode(&username),
rawurlencode(&password),
m2,
m3
);
if run_commands_inline(
&auth_url,
&mut *self.process.borrow_mut(),
&mut last_command,
command_output.as_deref_mut(),
) == 0
{
self.io
.set_authentication(m2.clone(), username, Some(password));
let mut auth_helper =
AuthHelper::new(self.io.clone_box(), std::rc::Rc::clone(&self.config));
let store_auth_enum = match &store_auth {
PhpMixed::String(s) if s == "prompt" => StoreAuth::Prompt,
PhpMixed::Bool(b) => StoreAuth::Bool(*b),
_ => StoreAuth::Bool(false),
};
auth_helper.store_auth(&m2, store_auth_enum)?;
return Ok(());
}
credentials = vec![rawurlencode(&username), rawurlencode(&password)];
error_msg = self.process.borrow().get_error_output().to_string();
}
}
if initial_clone {
if let Some(ref orig) = orig_cwd {
self.filesystem.borrow_mut().remove_directory(orig);
}
}
let mut last_command_str = match &last_command {
PhpMixed::List(l) => {
let parts: Vec<String> = l
.iter()
.filter_map(|v| v.as_string().map(|s| s.to_string()))
.collect();
implode(" ", &parts)
}
_ => last_command.as_string().unwrap_or("").to_string(),
};
let mut error_msg = self.process.borrow().get_error_output().to_string();
if (credentials.len() as i64) > 0 {
last_command_str = self.mask_credentials(&last_command_str, &credentials);
error_msg = self.mask_credentials(&error_msg, &credentials);
}
self.throw_exception(
&format!("Failed to execute {}\n\n{}", last_command_str, error_msg),
url,
)?;
}
Ok(())
}
pub fn sync_mirror(&mut self, url: &str, dir: &str) -> Result<bool> {
let composer_disable_network = Platform::get_env("COMPOSER_DISABLE_NETWORK");
if composer_disable_network
.as_ref()
.map(|v| !v.is_empty() && v != "0")
.unwrap_or(false)
&& composer_disable_network.as_deref() != Some("prime")
{
self.io.write_error3(
&format!(
"<warning>Aborting git mirror sync of {} as network is disabled</warning>",
url
),
true,
io_interface::NORMAL,
);
return Ok(false);
}
// update the repo if it is a valid git repository
let mut output = String::new();
if is_dir(dir)
&& self.process.borrow_mut().execute_args(
&vec![
"git".to_string(),
"rev-parse".to_string(),
"--git-dir".to_string(),
],
&mut output,
Some(dir.to_string()),
) == 0
&& trim(&output, None) == "."
{
// PHP try/finally
let try_result: Result<()> = (|| -> Result<()> {
let commands = vec![
vec![
"git".to_string(),
"remote".to_string(),
"set-url".to_string(),
"origin".to_string(),
"--".to_string(),
"%url%".to_string(),
],
vec![
"git".to_string(),
"remote".to_string(),
"update".to_string(),
"--prune".to_string(),
"origin".to_string(),
],
vec!["git".to_string(), "gc".to_string(), "--auto".to_string()],
];
self.run_commands(commands, url, Some(dir), false, None)?;
Ok(())
})();
// finally
let _ = self.run_commands(
vec![vec![
"git".to_string(),
"remote".to_string(),
"set-url".to_string(),
"origin".to_string(),
"--".to_string(),
"%sanitizedUrl%".to_string(),
]],
url,
Some(dir),
false,
None,
);
if let Err(e) = try_result {
self.io.write_error3(
&format!("<error>Sync mirror failed: {}</error>", e),
true,
io_interface::DEBUG,
);
return Ok(false);
}
return Ok(true);
}
Self::check_for_repo_ownership_error(self.process.borrow().get_error_output(), dir, None)?;
// clean up directory and do a fresh clone into it
self.filesystem.borrow_mut().remove_directory(dir);
self.run_commands(
vec![vec![
"git".to_string(),
"clone".to_string(),
"--mirror".to_string(),
"--".to_string(),
"%url%".to_string(),
dir.to_string(),
]],
url,
Some(dir),
true,
None,
)?;
self.run_commands(
vec![vec![
"git".to_string(),
"remote".to_string(),
"set-url".to_string(),
"origin".to_string(),
"--".to_string(),
"%sanitizedUrl%".to_string(),
]],
url,
Some(dir),
false,
None,
)?;
Ok(true)
}
pub fn fetch_ref_or_sync_mirror(
&mut self,
url: &str,
dir: &str,
r#ref: &str,
pretty_version: Option<&str>,
) -> Result<bool> {
if self.check_ref_is_in_mirror(dir, r#ref)? {
if Preg::is_match(r"{^[a-f0-9]{40}$}", r#ref).unwrap_or(false)
&& pretty_version.is_some()
{
let branch =
Preg::replace(r"{(?:^dev-|(?:\.x)?-dev$)}i", "", &pretty_version.unwrap())?;
let mut branches: Option<String> = None;
let mut tags: Option<String> = None;
let mut output = String::new();
if self.process.borrow_mut().execute_args(
&vec!["git".to_string(), "branch".to_string()],
&mut output,
Some(dir.to_string()),
) == 0
{
branches = Some(output);
}
let mut output = String::new();
if self.process.borrow_mut().execute_args(
&vec!["git".to_string(), "tag".to_string()],
&mut output,
Some(dir.to_string()),
) == 0
{
tags = Some(output);
}
// if the pretty version cannot be found as a branch (nor branch with 'v' in front of the branch as it may have been stripped when generating pretty name),
// nor as a tag, then we sync the mirror as otherwise it will likely fail during install.
// this can occur if a git tag gets created *after* the reference is already put into the cache, as the ref check above will then not sync the new tags
// see https://github.com/composer/composer/discussions/11002
if branches.is_some()
&& !Preg::is_match(
&format!(r"{{^[\s*]*v?{}$}}m", preg_quote(&branch, None)),
branches.as_deref().unwrap_or(""),
)
.unwrap_or(false)
&& tags.is_some()
&& !Preg::is_match(
&format!(r"{{^[\s*]*{}$}}m", preg_quote(&branch, None)),
tags.as_deref().unwrap_or(""),
)
.unwrap_or(false)
{
self.sync_mirror(url, dir)?;
}
}
return Ok(true);
}
if self.sync_mirror(url, dir)? {
return self.check_ref_is_in_mirror(dir, r#ref);
}
Ok(false)
}
pub fn get_no_show_signature_flag(
process: &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
) -> String {
let git_version = Self::get_version(process);
if let Some(v) = git_version {
if version_compare(&v, "2.10.0-rc0", ">=") {
return " --no-show-signature".to_string();
}
}
String::new()
}
/// @return list<string>
pub fn get_no_show_signature_flags(
process: &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
) -> Vec<String> {
let flags = Self::get_no_show_signature_flag(process);
if flags.is_empty() {
return vec![];
}
explode(" ", &substr(&flags, 1, None))
}
/// Checks if git version supports --no-commit-header flag (git 2.33+)
///
/// @internal
pub fn supports_no_commit_header_flag(
process: &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
) -> bool {
let git_version = Self::get_version(process);
git_version
.map(|v| version_compare(&v, "2.33.0-rc0", ">="))
.unwrap_or(false)
}
/// Builds a git rev-list command with --no-commit-header flag when supported (git 2.33+)
///
/// @internal
/// @param list<string> $arguments Additional arguments for git rev-list
/// @return non-empty-list<string>
pub fn build_rev_list_command(
process: &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
arguments: Vec<String>,
) -> Vec<String> {
let mut command = vec!["git".to_string(), "rev-list".to_string()];
if Self::supports_no_commit_header_flag(process) {
command.push("--no-commit-header".to_string());
}
command.extend(arguments);
command
}
/// Parses git rev-list output, removing 'commit <hash>' header lines for git < 2.33.
///
/// When --no-commit-header is not available (git < 2.33), git rev-list --format outputs
/// "commit <hash>" before formatted output. This removes those lines.
///
/// @internal
pub fn parse_rev_list_output(
output: &str,
process: &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
) -> String {
// If git supports --no-commit-header, output is already clean
if Self::supports_no_commit_header_flag(process) {
return output.to_string();
}
// Filter out "commit <hash>" lines for older git versions
Preg::replace(r"{^commit [a-f0-9]{40}\n?}m", "", output).unwrap_or_default()
}
fn check_ref_is_in_mirror(&mut self, dir: &str, r#ref: &str) -> Result<bool> {
let mut output = String::new();
if is_dir(dir)
&& self.process.borrow_mut().execute_args(
&vec![
"git".to_string(),
"rev-parse".to_string(),
"--git-dir".to_string(),
],
&mut output,
Some(dir.to_string()),
) == 0
&& trim(&output, None) == "."
{
let mut ignored_output = String::new();
let exit_code = self.process.borrow_mut().execute_args(
&vec![
"git".to_string(),
"rev-parse".to_string(),
"--quiet".to_string(),
"--verify".to_string(),
format!("{}^{{commit}}", r#ref),
],
&mut ignored_output,
Some(dir.to_string()),
);
if exit_code == 0 {
return Ok(true);
}
}
Self::check_for_repo_ownership_error(self.process.borrow().get_error_output(), dir, None)?;
Ok(false)
}
/// @return array<int, string>|null
fn get_authentication_failure(&self, url: &str) -> Option<IndexMap<CaptureKey, String>> {
let mut m: IndexMap<CaptureKey, String> = IndexMap::new();
if !Preg::is_match_strict_groups3(r"{^(https?://)([^/]+)(.*)$}i", url, Some(&mut m))
.unwrap_or(false)
{
return None;
}
let auth_failures = [
"fatal: Authentication failed",
"remote error: Invalid username or password.",
"error: 401 Unauthorized",
"fatal: unable to access",
"fatal: could not read Username",
];
let error_output = self.process.borrow().get_error_output().to_string();
for auth_failure in &auth_failures {
if strpos(&error_output, auth_failure).is_some() {
return Some(m);
}
}
None
}
pub fn get_mirror_default_branch(
&mut self,
url: &str,
dir: &str,
is_local_path_repository: bool,
) -> Option<String> {
if Platform::get_env("COMPOSER_DISABLE_NETWORK")
.map(|v| !v.is_empty() && v != "0")
.unwrap_or(false)
{
return None;
}
let result: Result<Option<String>> = (|| -> Result<Option<String>> {
let mut output_mixed = PhpMixed::String(String::new());
if is_local_path_repository {
let mut output = String::new();
self.process.borrow_mut().execute_args(
&vec![
"git".to_string(),
"remote".to_string(),
"show".to_string(),
"origin".to_string(),
],
&mut output,
Some(dir.to_string()),
);
output_mixed = PhpMixed::String(output);
} else {
let commands = vec![
vec![
"git".to_string(),
"remote".to_string(),
"set-url".to_string(),
"origin".to_string(),
"--".to_string(),
"%url%".to_string(),
],
vec![
"git".to_string(),
"remote".to_string(),
"show".to_string(),
"origin".to_string(),
],
vec![
"git".to_string(),
"remote".to_string(),
"set-url".to_string(),
"origin".to_string(),
"--".to_string(),
"%sanitizedUrl%".to_string(),
],
];
self.run_commands(commands, url, Some(dir), false, Some(&mut output_mixed))?;
}
let lines = self
.process
.borrow()
.split_lines(output_mixed.as_string().unwrap_or(""));
for line in lines {
let mut matches: IndexMap<CaptureKey, String> = IndexMap::new();
if Preg::is_match_strict_groups3(
r"{^\s*HEAD branch:\s(.+)\s*$}m",
&line,
Some(&mut matches),
)
.unwrap_or(false)
{
return Ok(Some(
matches
.get(&CaptureKey::ByIndex(1))
.cloned()
.unwrap_or_default(),
));
}
}
Ok(None)
})();
match result {
Ok(v) => v,
Err(e) => {
self.io.write_error3(
&format!(
"<error>Failed to fetch root identifier from remote: {}</error>",
e
),
true,
io_interface::DEBUG,
);
None
}
}
}
pub fn clean_env(process: &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>) {
// PHP: $process ?? new ProcessExecutor()
let git_version = Self::get_version(process);
if let Some(v) = git_version {
if version_compare(&v, "2.3.0", ">=") {
// added in git 2.3.0, prevents prompting the user for username/password
if Platform::get_env("GIT_TERMINAL_PROMPT").as_deref() != Some("0") {
Platform::put_env("GIT_TERMINAL_PROMPT", "0");
}
} else {
// added in git 1.7.1, prevents prompting the user for username/password
if Platform::get_env("GIT_ASKPASS").as_deref() != Some("echo") {
Platform::put_env("GIT_ASKPASS", "echo");
}
}
}
// clean up rogue git env vars in case this is running in a git hook
if Platform::get_env("GIT_DIR").is_some() {
Platform::clear_env("GIT_DIR");
}
if Platform::get_env("GIT_WORK_TREE").is_some() {
Platform::clear_env("GIT_WORK_TREE");
}
// Run processes with predictable LANGUAGE
if Platform::get_env("LANGUAGE").as_deref() != Some("C") {
Platform::put_env("LANGUAGE", "C");
}
// clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940
Platform::clear_env("DYLD_LIBRARY_PATH");
}
/// @return non-empty-string
pub fn get_github_domains_regex(config: &Config) -> String {
let domains: Vec<String> = match config.get("github-domains") {
PhpMixed::List(l) => l
.iter()
.filter_map(|v| v.as_string().map(|s| s.to_string()))
.collect(),
_ => vec![],
};
let escaped: Vec<String> = array_map(|s: &String| preg_quote(s, None), &domains);
format!("({})", implode("|", &escaped))
}
/// @return non-empty-string
pub fn get_gitlab_domains_regex(config: &Config) -> String {
let domains: Vec<String> = match config.get("gitlab-domains") {
PhpMixed::List(l) => l
.iter()
.filter_map(|v| v.as_string().map(|s| s.to_string()))
.collect(),
_ => vec![],
};
let escaped: Vec<String> = array_map(|s: &String| preg_quote(s, None), &domains);
format!("({})", implode("|", &escaped))
}
/// @param non-empty-string $message
///
/// @return never
fn throw_exception(&mut self, message: &str, url: &str) -> Result<()> {
// git might delete a directory when it fails and php will not know
clearstatcache();
let mut ignored_output = String::new();
if self.process.borrow_mut().execute_args(
&vec!["git".to_string(), "--version".to_string()],
&mut ignored_output,
Option::<&str>::None,
) != 0
{
return Err(RuntimeException {
message: Url::sanitize(format!(
"Failed to clone {}, git was not found, check that it is installed and in your PATH env.\n\n{}",
url,
self.process.borrow().get_error_output()
)),
code: 0,
}
.into());
}
Err(RuntimeException {
message: Url::sanitize(message.to_string()),
code: 0,
}
.into())
}
/// Retrieves the current git version.
///
/// @return string|null The git version number, if present.
pub fn get_version(
process: &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
) -> Option<String> {
let mut version = VERSION.lock().unwrap();
if version.is_none() {
*version = Some(None);
let mut output = String::new();
// TODO(phase-b): ProcessExecutor::execute takes &mut self; this static fn takes &ProcessExecutor
// For now, mimic the call signature (compilation fix is Phase B)
let exit_code: i64 = 0; // process.execute(&["git", "--version"].map(String::from).to_vec(), &mut output, None);
if exit_code == 0 {
let mut matches: IndexMap<CaptureKey, String> = IndexMap::new();
if Preg::is_match_strict_groups3(
r"/^git version (\d+(?:\.\d+)+)/m",
&output,
Some(&mut matches),
)
.unwrap_or(false)
{
*version = Some(matches.get(&CaptureKey::ByIndex(1)).cloned());
}
}
}
version.clone().unwrap_or(None)
}
/// @param string[] $credentials
fn mask_credentials(&self, error: &str, credentials: &[String]) -> String {
let mut masked_credentials: Vec<String> = vec![];
for credential in credentials {
if in_array(
PhpMixed::String(credential.clone()),
&PhpMixed::List(vec![
Box::new(PhpMixed::String("private-token".to_string())),
Box::new(PhpMixed::String("x-token-auth".to_string())),
Box::new(PhpMixed::String("oauth2".to_string())),
Box::new(PhpMixed::String("gitlab-ci-token".to_string())),
Box::new(PhpMixed::String("x-oauth-basic".to_string())),
]),
false,
) {
masked_credentials.push(credential.clone());
} else if strlen(credential) > 6 {
masked_credentials.push(format!(
"{}...{}",
substr(credential, 0, Some(3)),
substr(credential, -3, None)
));
} else if strlen(credential) > 3 {
masked_credentials.push(format!("{}...", substr(credential, 0, Some(3))));
} else {
masked_credentials.push("XXX".to_string());
}
}
str_replace_array(credentials, &masked_credentials, error)
}
}
|