git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
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
use anyhow::{anyhow, bail, Context, Result};
use std::cell::RefCell;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::time::{Duration, Instant};

// ---------------------------------------------------------------------------------------------
// Thread-local context: working directory and extra environment for every git runner.
// Tests use it (through `testutil::TempRepo`) instead of `set_current_dir`, because cargo runs
// tests on parallel threads that share one process cwd.
// ---------------------------------------------------------------------------------------------

#[derive(Clone, Default)]
struct CtxData {
    dir: Option<PathBuf>,
    env: Vec<(String, String)>,
    /// Set by `ui::git_job` on its worker: when it becomes true, `exec` kills git like
    /// `Opts.cancel` does (the user stopped waiting).
    cancel: Option<Arc<AtomicBool>>,
}

thread_local! {
    static CTX: RefCell<CtxData> = RefCell::new(CtxData::default());
}

/// A copy of this thread's git context, to carry into a worker thread (`ui::git_job` does).
pub(crate) struct Ctx(CtxData);

pub(crate) fn ctx_snapshot() -> Ctx {
    Ctx(CTX.with(|ctx| ctx.borrow().clone()))
}

/// Installs a snapshot as this thread's context (for a fresh worker thread).
pub(crate) fn ctx_restore(ctx: Ctx) {
    CTX.with(|current| *current.borrow_mut() = ctx.0);
}

impl Ctx {
    /// This snapshot with `flag` as its cancel flag: every `git_raw`/`git_ok`/`git_stream` call
    /// on a thread that restores it kills git once `flag` is true.
    pub(crate) fn with_cancel(mut self, flag: Arc<AtomicBool>) -> Ctx {
        self.0.cancel = Some(flag);
        self
    }
}

/// True when this thread's context carries a cancel flag that is set.
fn ctx_cancelled() -> bool {
    CTX.with(|ctx| {
        ctx.borrow()
            .cancel
            .as_ref()
            .is_some_and(|flag| flag.load(Ordering::Relaxed))
    })
}

/// Runs `f` with every git runner on this thread using `dir` as its working directory and
/// `env` added to its environment (on top of any outer `with_ctx`). Restores the previous
/// context afterwards, also when `f` panics.
#[allow(dead_code)] // used by the test helpers
pub fn with_ctx<T>(dir: &Path, env: Vec<(String, String)>, f: impl FnOnce() -> T) -> T {
    struct Restore(Option<CtxData>);
    impl Drop for Restore {
        fn drop(&mut self) {
            if let Some(previous) = self.0.take() {
                CTX.with(|ctx| *ctx.borrow_mut() = previous);
            }
        }
    }
    let previous = CTX.with(|ctx| {
        let mut ctx = ctx.borrow_mut();
        let previous = ctx.clone();
        ctx.dir = Some(dir.to_path_buf());
        ctx.env.extend(env);
        previous
    });
    let _restore = Restore(Some(previous));
    f()
}

/// `git <args>` with `defaults` in the environment, then this thread's context on top.
fn command_with(args: &[&str], defaults: &[(&str, &str)]) -> Command {
    let mut command = Command::new("git");
    command.args(args).envs(defaults.iter().copied());
    CTX.with(|ctx| {
        let ctx = ctx.borrow();
        if let Some(dir) = &ctx.dir {
            command.current_dir(dir);
        }
        command.envs(ctx.env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
    });
    command
}

/// Runs a short git command and waits for it (no timeout). Uses the same default environment
/// as the other runners (C locale, no prompts), so callers may match git's English messages.
pub fn run(args: &[&str]) -> Result<String> {
    let started = Instant::now();
    let output = command_with(args, &DEFAULT_ENV)
        .output()
        .with_context(|| format!("could not start git {}", args.join(" ")));
    log_call(
        args,
        output.as_ref().ok().and_then(|o| o.status.code()),
        started.elapsed().as_millis(),
    );
    let output = output?;
    if !output.status.success() {
        let detail = String::from_utf8_lossy(&output.stderr).trim().to_string();
        bail!(
            "{}",
            if detail.is_empty() {
                "git command failed".to_string()
            } else {
                detail
            }
        );
    }
    // trim_end only: `status --short` lines start with a meaningful space (" M file").
    Ok(into_trimmed(output.stdout))
}

/// Converts stdout to a String without a second copy, then trims trailing whitespace in place.
fn into_trimmed(bytes: Vec<u8>) -> String {
    let mut text = String::from_utf8(bytes)
        .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned());
    text.truncate(text.trim_end().len());
    text
}

/// Names of all local branches, current one included.
pub fn local_branches() -> Result<Vec<String>> {
    Ok(parse_lines(&run(&["branch", "--format=%(refname:short)"])?))
}

fn parse_lines(text: &str) -> Vec<String> {
    text.lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(String::from)
        .collect()
}

/// Works on a branch with no commits yet (symbolic-ref), and returns "HEAD" when detached.
pub fn current_branch() -> Result<String> {
    run(&["symbolic-ref", "--short", "-q", "HEAD"])
        .or_else(|_| run(&["rev-parse", "--abbrev-ref", "HEAD"]))
}

pub fn status_lines() -> Result<Vec<String>> {
    let status = run(&["status", "--short"])?;
    Ok(if status.is_empty() {
        vec!["(clean working tree)".into()]
    } else {
        status.lines().map(str::to_owned).collect()
    })
}

#[derive(Debug, Clone)]
pub struct Identity {
    pub name: String,
    pub email: String,
}

/// True when the repo's own config sets `key`. `git config --get` exits 1 when unset.
pub fn has_local_config(key: &str) -> bool {
    run(&["config", "--local", "--get", key]).is_ok_and(|value| !value.is_empty())
}

pub fn commit(message: &str, date: &str, amend: bool, identity: Option<&Identity>) -> Result<()> {
    let args = if amend {
        vec!["commit", "--amend", "-m", message]
    } else {
        vec!["commit", "-m", message]
    };
    let mut env = vec![("GIT_AUTHOR_DATE", date), ("GIT_COMMITTER_DATE", date)];
    // Explicit identity beats repo-local user.name/user.email.
    if let Some(id) = identity {
        // Amend keeps the original author, as git's own --amend does; only the committer changes.
        if !amend {
            env.extend([
                ("GIT_AUTHOR_NAME", id.name.as_str()),
                ("GIT_AUTHOR_EMAIL", id.email.as_str()),
            ]);
        }
        env.extend([
            ("GIT_COMMITTER_NAME", id.name.as_str()),
            ("GIT_COMMITTER_EMAIL", id.email.as_str()),
        ]);
    }
    // A write command: the long write ceiling (a kill could leave index.lock behind).
    let opts = Opts {
        env: &env,
        ..Opts::default()
    };
    let out = git_raw(&args, &opts)?;
    if !out.ok() {
        // Hook and "nothing to commit" messages go to stdout, so fall back to it.
        bail!("{}", legacy_detail(&out, true, "git commit failed"));
    }
    Ok(())
}

/// `git add .` (stage everything), with the safe environment and the write timeout.
pub fn add_all() -> Result<()> {
    let out = git_raw(&["add", "."], &Opts::default())?;
    if !out.ok() {
        bail!("{}", legacy_detail(&out, false, "git command failed"));
    }
    Ok(())
}

/// The error text the legacy runners always produced: stderr, optionally stdout, else `fallback`.
fn legacy_detail(out: &Out, with_stdout: bool, fallback: &str) -> String {
    let stderr = out.stderr.trim();
    if !stderr.is_empty() {
        return stderr.to_string();
    }
    let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if with_stdout && !stdout.is_empty() {
        return stdout;
    }
    fallback.to_string()
}

/// Why a user-typed branch name may not be used, without running git (None = fine so far).
pub fn branch_name_problem(branch: &str) -> Option<&'static str> {
    if branch.is_empty() {
        Some("it is empty")
    } else if branch.starts_with('-') {
        Some("it starts with '-'")
    } else if branch.chars().any(|c| c.is_control() || c.is_whitespace()) {
        Some("it contains spaces or control characters")
    } else {
        None
    }
}

/// Rejects a branch name git would read as an option or that is not a valid branch name
/// (`git check-ref-format --branch`).
pub fn check_branch_name(branch: &str) -> Result<()> {
    if let Some(problem) = branch_name_problem(branch) {
        bail!("invalid branch name '{}': {problem}", branch.escape_debug());
    }
    if git_ok(&["check-ref-format", "--branch", branch], &Opts::default()).is_err() {
        bail!("invalid branch name '{branch}'");
    }
    Ok(())
}

/// Rejects a remote name git would read as an option (empty, leading '-', control chars).
/// URLs stay allowed, so this does not run check-ref-format.
pub fn check_remote_name(remote: &str) -> Result<()> {
    if let Some(problem) = branch_name_problem(remote) {
        bail!("invalid remote name '{}': {problem}", remote.escape_debug());
    }
    Ok(())
}

/// Legacy push of the commit flow: `git [-c credential...] push [--force-with-lease=refs/heads/<b>
/// --force-if-includes] origin refs/heads/<b>:refs/heads/<b>`. `force` is for an amended commit;
/// callers must ask `policy::check(ForcePush)` first. 300 s timeout, never prompts.
pub fn push(branch: &str, force: bool, login: Option<&str>) -> Result<()> {
    check_branch_name(branch)?;
    let lease = force.then(|| format!("--force-with-lease=refs/heads/{branch}"));
    let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
    let args = push_args(
        "origin",
        &refspec,
        lease.as_deref(),
        false,
        login,
        force_if_includes(),
    );
    let args: Vec<&str> = args.iter().map(String::as_str).collect();
    let opts = Opts {
        timeout: Some(PUSH_TIMEOUT),
        ..Opts::default()
    };
    let out = git_raw(&args, &opts)?;
    if !out.ok() {
        bail!("{}", legacy_detail(&out, false, "git command failed"));
    }
    Ok(())
}

const PUSH_TIMEOUT: Duration = Duration::from_secs(300);

/// Whether a git of this version knows `--force-if-includes` (added in 2.30). An unknown
/// version keeps the flag, so a failed `git --version` changes nothing.
fn supports_force_if_includes(version: Option<(u32, u32, u32)>) -> bool {
    version.is_none_or(|version| version >= (2, 30, 0))
}

/// `supports_force_if_includes` for the installed git, asked once per process.
fn force_if_includes() -> bool {
    static SUPPORTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *SUPPORTED.get_or_init(|| supports_force_if_includes(version().ok()))
}

/// `[-c credential.https://github.com.username=<login>] push [-u] [<lease> [--force-if-includes]]
/// <remote> <refspec>`. `-c` must come before the subcommand; it overrides a repo-local
/// credential.username. `if_includes` is false for git older than 2.30, which lacks the flag.
fn push_args(
    remote: &str,
    refspec: &str,
    lease: Option<&str>,
    set_upstream: bool,
    login: Option<&str>,
    if_includes: bool,
) -> Vec<String> {
    let mut args = Vec::new();
    if let Some(login) = login.filter(|login| !login.is_empty()) {
        args.push("-c".to_string());
        args.push(format!("credential.https://github.com.username={login}"));
    }
    args.push("push".into());
    if set_upstream {
        args.push("-u".into());
    }
    if let Some(lease) = lease {
        args.push(lease.into());
        if if_includes {
            args.push("--force-if-includes".into());
        }
    }
    args.push(remote.into());
    args.push(refspec.into());
    args
}

#[derive(Debug, Clone)]
pub struct Commit {
    pub hash: String,
    pub date: String,
    pub subject: String,
    pub refs: String,
}

pub fn recent_commits(limit: usize) -> Result<Vec<Commit>> {
    let limit = limit.to_string();
    let log = match run(&[
        "log",
        "-n",
        &limit,
        "--no-color",
        "--date=short",
        "--format=%h%x1f%ad%x1f%s%x1f%D",
    ]) {
        Ok(log) => log,
        // Fresh repo: git exits non-zero, which is not an error for the caller.
        Err(e) if e.to_string().contains("does not have any commits") => return Ok(vec![]),
        Err(e) => return Err(e),
    };
    Ok(log
        .lines()
        .filter(|line| !line.trim().is_empty())
        .filter_map(|line| {
            let fields: Vec<&str> = line.split('\u{1f}').collect();
            match fields[..] {
                [hash, date, subject, refs] => Some(Commit {
                    hash: hash.to_string(),
                    date: date.to_string(),
                    subject: subject.to_string(),
                    refs: refs.to_string(),
                }),
                _ => None,
            }
        })
        .collect())
}

pub fn remote_branches() -> Result<Vec<String>> {
    // strip=2 drops "refs/remotes/", leaving "origin/main".
    let out = run(&["branch", "-r", "--no-color", "--format=%(refname:strip=2)"])?;
    Ok(out
        .lines()
        .map(str::trim)
        .filter(|b| !b.is_empty() && !b.ends_with("/HEAD"))
        .map(str::to_owned)
        .collect())
}

pub fn upstream(branch: &str) -> Result<Option<String>> {
    let refname = format!("refs/heads/{branch}");
    let out = run(&["for-each-ref", "--format=%(upstream:short)", &refname])?;
    Ok(if out.is_empty() { None } else { Some(out) })
}

// ---------------------------------------------------------------------------------------------
// Runners for the git modes: no prompts, no editors, no pager, C locale, timeouts, cancel.
// ---------------------------------------------------------------------------------------------

/// Applied to every `git_raw`/`git_ok`/`git_stream` call before the thread context and
/// `Opts.env`, so both can override any of them (an empty value in `Opts.env` removes the
/// variable). GIT_OPTIONAL_LOCKS=0 only skips optional index refreshes, so writes are unaffected.
const DEFAULT_ENV: [(&str, &str); 6] = [
    ("GIT_TERMINAL_PROMPT", "0"),
    ("GIT_EDITOR", "true"),
    ("GIT_SEQUENCE_EDITOR", "true"),
    ("GIT_PAGER", "cat"),
    ("LC_ALL", "C"),
    ("GIT_OPTIONAL_LOCKS", "0"),
];

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);
/// Default ceiling for commands that write (see `WRITE_COMMANDS`): long enough for any real
/// work, but a write stuck on a prompt nobody can see (gpg pinentry, a blocking LFS filter)
/// still ends.
const WRITE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
const POLL: Duration = Duration::from_millis(25);
/// After git exits, how long a grandchild (credential helper, ssh) may keep stdout/stderr open
/// without sending anything before we stop waiting for the rest of the output.
const DRAIN: Duration = if cfg!(test) {
    Duration::from_secs(3)
} else {
    Duration::from_secs(5)
};

/// Subcommands that change the repository. Killing one half-way can leave `index.lock` /
/// `packed-refs.lock` behind (or a half-done rebase), so they get the long `WRITE_TIMEOUT`
/// instead of the 120 s default; a caller that wants another one passes `Opts.timeout`.
const WRITE_COMMANDS: &[&str] = &[
    "add",
    "am",
    "apply",
    "bisect",
    "branch",
    "checkout",
    "cherry-pick",
    "clean",
    "commit",
    "config",
    "gc",
    "init",
    "maintenance",
    "merge",
    "mv",
    "notes",
    "pack-refs",
    "prune",
    "pull",
    "read-tree",
    "rebase",
    "reflog",
    "repack",
    "replace",
    "reset",
    "restore",
    "revert",
    "rm",
    "sparse-checkout",
    "stash",
    "submodule",
    "switch",
    "symbolic-ref",
    "tag",
    "update-index",
    "update-ref",
    "worktree",
];

/// The git subcommand in `args`, skipping global options (`-c k=v`, `-C dir`, `--no-pager`...).
fn subcommand<'a>(args: &[&'a str]) -> Option<&'a str> {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        match *arg {
            "-c" | "-C" | "--git-dir" | "--work-tree" | "--namespace" | "--config-env" => {
                iter.next();
            }
            arg if arg.starts_with('-') => {}
            arg => return Some(arg),
        }
    }
    None
}

/// The timeout used when the caller passes none: 120 s for read-only commands, 30 minutes for
/// commands that write to the repository (see `WRITE_COMMANDS`).
fn default_timeout(args: &[&str]) -> Option<Duration> {
    match subcommand(args) {
        Some(sub) if WRITE_COMMANDS.contains(&sub) => Some(WRITE_TIMEOUT),
        _ => Some(DEFAULT_TIMEOUT),
    }
}

/// Records a finished call in the session log (and, in tests, remembers it per thread).
fn log_call(args: &[&str], code: Option<i32>, ms: u128) {
    crate::cmdlog::record(args, code, ms);
    #[cfg(test)]
    LAST_CALL.with(|last| *last.borrow_mut() = Some((args.join(" "), code)));
}

#[cfg(test)]
thread_local! {
    /// The last call `log_call` saw on this thread: (args joined by spaces, exit code).
    static LAST_CALL: RefCell<Option<(String, Option<i32>)>> = const { RefCell::new(None) };
}

/// Kills git and, on Windows, everything it started (git-remote-https, ssh, a credential
/// helper), which would otherwise keep running and hold our pipes open.
fn kill_tree(child: &mut std::process::Child) {
    #[cfg(windows)]
    {
        // Only while git still runs: after it exits its PID may belong to another process.
        if let Ok(None) = child.try_wait() {
            use std::os::windows::process::CommandExt;
            const CREATE_NO_WINDOW: u32 = 0x0800_0000;
            let _ = Command::new("taskkill")
                .args(["/PID", &child.id().to_string(), "/T", "/F"])
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .creation_flags(CREATE_NO_WINDOW)
                .status();
        }
    }
    let _ = child.kill();
}

/// Options for `git_raw`, `git_ok` and `git_stream`. `Opts::default()`: stdin is null, no
/// extra env, no line limit, the default timeout (120 s for read-only commands, 30 minutes
/// for commands that write, see `WRITE_COMMANDS`), not cancellable.
#[derive(Default, Clone, Copy)]
pub struct Opts<'a> {
    /// Bytes written to git's stdin (then closed). Never recorded in the command log.
    pub stdin: Option<&'a [u8]>,
    /// Extra environment, applied last. An empty value removes the variable.
    pub env: &'a [(&'a str, &'a str)],
    /// Stop (and kill git) once more than this many stdout lines arrive; sets `Out.truncated`.
    pub max_lines: Option<usize>,
    /// Kill git and return an error after this long (default: see `default_timeout`).
    pub timeout: Option<Duration>,
    /// When this flag becomes true git is killed and `Out.cancelled` is set.
    pub cancel: Option<&'a AtomicBool>,
}

/// What a git call produced. `code` is None when git was killed (cancel, limit, early stop).
#[derive(Debug, Default)]
pub struct Out {
    pub stdout: Vec<u8>,
    pub stderr: String,
    pub code: Option<i32>,
    /// Output was cut short by `max_lines`, by a `git_stream` callback returning false, or
    /// because a leftover child process kept stdout open after git exited (5 s without output,
    /// or past the timeout).
    pub truncated: bool,
    pub cancelled: bool,
}

impl Out {
    /// True when git ran to completion with exit code 0.
    pub fn ok(&self) -> bool {
        self.code == Some(0)
    }

    /// stdout as lossy UTF-8 with trailing whitespace trimmed.
    pub fn text(&self) -> String {
        into_trimmed(self.stdout.clone())
    }
}

enum Stop {
    Cancelled,
    Truncated,
    TimedOut,
}

/// Spawns git and feeds every stdout chunk (one line including its '\n', or the tail) to
/// `on_chunk`. Kills git on every early exit. Errors only on spawn failure or timeout.
fn exec(args: &[&str], o: &Opts, on_chunk: &mut dyn FnMut(&[u8]) -> bool) -> Result<Out> {
    let started = Instant::now();
    let mut command = command_with(args, &DEFAULT_ENV);
    for (key, value) in o.env {
        if value.is_empty() {
            command.env_remove(key);
        } else {
            command.env(key, value);
        }
    }
    command
        .stdin(if o.stdin.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = match command.spawn() {
        Ok(child) => child,
        Err(error) => {
            log_call(args, None, started.elapsed().as_millis());
            return Err(anyhow!(error).context(format!("could not start git {}", args.join(" "))));
        }
    };

    if let (Some(data), Some(mut pipe)) = (o.stdin, child.stdin.take()) {
        let data = data.to_vec();
        std::thread::spawn(move || {
            let _ = pipe.write_all(&data);
        });
    }
    // stderr is appended to a shared buffer as it arrives, so whatever came is kept even when
    // a grandchild never closes the pipe. The channel disconnects when the reader finishes.
    let err_buf = Arc::new(Mutex::new(Vec::new()));
    let (err_done_tx, err_done_rx) = mpsc::channel::<()>();
    if let Some(mut pipe) = child.stderr.take() {
        let err_buf = Arc::clone(&err_buf);
        std::thread::spawn(move || {
            let _done = err_done_tx;
            let mut chunk = [0u8; 8192];
            loop {
                match pipe.read(&mut chunk) {
                    Ok(0) => break,
                    Ok(n) => err_buf
                        .lock()
                        .unwrap_or_else(|poisoned| poisoned.into_inner())
                        .extend_from_slice(&chunk[..n]),
                    Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
                    Err(_) => break,
                }
            }
        });
    } else {
        drop(err_done_tx);
    }
    // Bounded: while a caller is busy in its line callback (e.g. Log browsing), git blocks instead of filling memory.
    let (out_tx, out_rx) = mpsc::sync_channel::<Vec<u8>>(1024);
    if let Some(pipe) = child.stdout.take() {
        std::thread::spawn(move || {
            let mut reader = BufReader::new(pipe);
            loop {
                let mut chunk = Vec::new();
                match reader.read_until(b'\n', &mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(_) => {
                        if out_tx.send(chunk).is_err() {
                            break;
                        }
                    }
                }
            }
        });
    }

    let timeout = o.timeout.or_else(|| default_timeout(args));
    let timed_out = || timeout.is_some_and(|limit| started.elapsed() >= limit);
    let cancelled = || o.cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) || ctx_cancelled();
    // Set when a leftover process kept stdout open past the drain deadline.
    let mut cut_off = false;
    // Set when git's exit is seen while stdout is still open; stderr shares this deadline.
    let mut drain_deadline: Option<Instant> = None;
    let mut lines = 0usize;
    // Returns false when reading must stop (line limit or the callback said so).
    let mut handle = |chunk: Vec<u8>| -> bool {
        if o.max_lines.is_some_and(|max| lines >= max) {
            return false;
        }
        lines += 1;
        on_chunk(&chunk)
    };
    let mut stop: Option<Stop> = None;
    let mut status = None;
    loop {
        if cancelled() {
            stop = Some(Stop::Cancelled);
            break;
        }
        if timed_out() {
            stop = Some(Stop::TimedOut);
            break;
        }
        match out_rx.recv_timeout(POLL) {
            Ok(chunk) => {
                if !handle(chunk) {
                    stop = Some(Stop::Truncated);
                    break;
                }
            }
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
            Err(mpsc::RecvTimeoutError::Timeout) => {
                if let Ok(Some(exit)) = child.try_wait() {
                    status = Some(exit);
                    // git exited; the reader thread may still hold buffered lines, and a
                    // grandchild may hold stdout open. Drain until the reader is done; the
                    // deadline restarts after every chunk, so neither a steady producer nor
                    // time spent in `on_chunk` (Log browsing) cuts the output short.
                    let mut deadline = Instant::now() + DRAIN;
                    drain_deadline = Some(deadline);
                    loop {
                        if cancelled() {
                            stop = Some(Stop::Cancelled);
                            break;
                        }
                        let left = deadline.saturating_duration_since(Instant::now());
                        // The overall timeout still bounds a leftover process that never stops.
                        if left.is_zero() || timed_out() {
                            cut_off = true;
                            break;
                        }
                        match out_rx.recv_timeout(left.min(POLL)) {
                            Ok(chunk) => {
                                if !handle(chunk) {
                                    stop = Some(Stop::Truncated);
                                    break;
                                }
                                deadline = Instant::now() + DRAIN;
                                drain_deadline = Some(deadline);
                            }
                            Err(mpsc::RecvTimeoutError::Disconnected) => break,
                            Err(mpsc::RecvTimeoutError::Timeout) => {}
                        }
                    }
                    break;
                }
            }
        }
    }
    // stdout is done; wait for the exit status, still honouring cancel and timeout.
    while stop.is_none() && status.is_none() {
        match child.try_wait() {
            Ok(Some(exit)) => status = Some(exit),
            Ok(None) => {
                if cancelled() {
                    stop = Some(Stop::Cancelled);
                } else if timed_out() {
                    stop = Some(Stop::TimedOut);
                } else {
                    std::thread::sleep(POLL);
                }
            }
            Err(_) => break,
        }
    }
    let mut out = Out::default();
    if stop.is_some() {
        kill_tree(&mut child);
        let _ = child.wait();
    } else if status.is_none() {
        status = child.wait().ok();
    }
    out.code = if stop.is_some() {
        None
    } else {
        status.and_then(|s| s.code())
    };
    // Wait for the stderr reader against one deadline; a grandchild (credential daemon) can
    // keep the pipe open, so keep whatever arrived and stop waiting at the deadline.
    let grace = if stop.is_some() {
        Duration::from_millis(500)
    } else {
        drain_deadline.map_or(DRAIN, |deadline| {
            deadline.saturating_duration_since(Instant::now())
        })
    };
    let _ = err_done_rx.recv_timeout(grace);
    out.stderr = String::from_utf8_lossy(
        &err_buf
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()),
    )
    .into_owned();
    if cut_off && stop.is_none() {
        out.truncated = true;
    }
    log_call(args, out.code, started.elapsed().as_millis());
    match stop {
        Some(Stop::TimedOut) => bail!(
            "git {} timed out after {}s",
            subcommand(args).unwrap_or(""),
            timeout.unwrap_or_default().as_secs_f32()
        ),
        Some(Stop::Cancelled) => out.cancelled = true,
        Some(Stop::Truncated) => out.truncated = true,
        None => {}
    }
    Ok(out)
}

/// Runs git and returns everything it produced. Errors ONLY when git cannot start or times
/// out; a non-zero exit code is returned in `Out.code`, never as an error.
pub fn git_raw(args: &[&str], o: &Opts) -> Result<Out> {
    let mut stdout = Vec::new();
    let mut out = exec(args, o, &mut |chunk| {
        stdout.extend_from_slice(chunk);
        true
    })?;
    out.stdout = stdout;
    Ok(out)
}

/// Runs git and returns stdout (lossy UTF-8, trailing whitespace trimmed). A non-zero exit
/// bails with git's stderr (stdout when stderr is empty). A cancel bails `input::CANCELLED`.
/// Output cut by `max_lines` is returned as is.
pub fn git_ok(args: &[&str], o: &Opts) -> Result<String> {
    let out = git_raw(args, o)?;
    if out.cancelled {
        bail!(crate::input::CANCELLED);
    }
    if out.truncated || out.ok() {
        return Ok(into_trimmed(out.stdout));
    }
    Err(failure(args, &out))
}

/// The error for a failed git call: stderr, else stdout, else the exit code.
fn failure(args: &[&str], out: &Out) -> anyhow::Error {
    let stderr = out.stderr.trim();
    if !stderr.is_empty() {
        return anyhow!("{stderr}");
    }
    let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if !stdout.is_empty() {
        return anyhow!("{stdout}");
    }
    let code = out
        .code
        .map_or("killed".to_string(), |c| format!("exit {c}"));
    anyhow!(
        "git {} failed ({code})",
        args.first().copied().unwrap_or("")
    )
}

/// Streams stdout line by line (without the trailing "\n" / "\r\n"). Returning false from
/// `on_line` stops reading and kills git (`Out.truncated` is then set). Honours cancel,
/// max_lines and timeout like `git_raw`; `Out.stdout` stays empty.
pub fn git_stream(args: &[&str], o: &Opts, on_line: &mut dyn FnMut(&[u8]) -> bool) -> Result<Out> {
    exec(args, o, &mut |chunk| {
        let line = chunk.strip_suffix(b"\n").unwrap_or(chunk);
        let line = line.strip_suffix(b"\r").unwrap_or(line);
        on_line(line)
    })
}

/// Parses `git --version` output, e.g. "git version 2.43.0.windows.1" -> (2, 43, 0).
pub fn parse_version(text: &str) -> Option<(u32, u32, u32)> {
    let rest = text.trim().strip_prefix("git version ")?;
    let token = rest.split_whitespace().next()?;
    let mut parts = token.split('.').map(|part| {
        let digits: String = part.chars().take_while(char::is_ascii_digit).collect();
        digits.parse::<u32>().ok()
    });
    let major = parts.next()??;
    let minor = parts.next()??;
    let patch = parts.next().flatten().unwrap_or(0);
    Some((major, minor, patch))
}

/// The installed git version.
pub fn version() -> Result<(u32, u32, u32)> {
    let text = git_ok(&["--version"], &Opts::default())?;
    parse_version(&text).ok_or_else(|| anyhow!("could not read the git version from '{text}'"))
}

/// The `--force-with-lease` argument for a `push_to` lease value. The expected oid is dropped
/// on purpose: git then compares against our remote-tracking ref, and `--force-if-includes`
/// (always added) refuses when that ref moved (e.g. a background fetch) to commits we never
/// integrated. `"refs/heads/b:<oid>"` -> `--force-with-lease=refs/heads/b`; `""` -> bare.
fn lease_arg(lease: &str) -> String {
    let refname = lease.split_once(':').map_or(lease, |(refname, _)| refname);
    if refname.is_empty() {
        "--force-with-lease".to_string()
    } else {
        format!("--force-with-lease={refname}")
    }
}

/// `git [-c credential.https://github.com.username=<login>] push [-u]
/// [--force-with-lease[=<ref>] --force-if-includes] <remote> refs/heads/<b>:refs/heads/<b>`.
/// `lease`: None = plain push; `Some("refs/heads/b:<oid>")` (or `Some("b")`) = lease on that
/// ref against the remote-tracking ref (the oid part is ignored, see `lease_arg`); `Some("")`
/// = bare `--force-with-lease`. Never a raw --force. Returns git's report (it prints to stderr).
#[allow(dead_code)] // thin wrapper over push_to_cancellable, used by the tests
pub fn push_to(
    remote: &str,
    branch: &str,
    lease: Option<&str>,
    set_upstream: bool,
    login: Option<&str>,
) -> Result<String> {
    push_to_cancellable(remote, branch, lease, set_upstream, login, None)
}

/// `push_to` that stops (and kills git) when `cancel` becomes true, bailing `input::CANCELLED`.
pub fn push_to_cancellable(
    remote: &str,
    branch: &str,
    lease: Option<&str>,
    set_upstream: bool,
    login: Option<&str>,
    cancel: Option<&AtomicBool>,
) -> Result<String> {
    check_remote_name(remote)?;
    check_branch_name(branch)?;
    let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
    let lease = lease.map(lease_arg);
    let args = push_args(
        remote,
        &refspec,
        lease.as_deref(),
        set_upstream,
        login,
        force_if_includes(),
    );
    let args: Vec<&str> = args.iter().map(String::as_str).collect();
    let opts = Opts {
        timeout: Some(PUSH_TIMEOUT),
        cancel,
        ..Opts::default()
    };
    let out = git_raw(&args, &opts)?;
    if out.cancelled {
        bail!(crate::input::CANCELLED);
    }
    if !out.ok() {
        return Err(failure(&args, &out));
    }
    let mut report = out.stderr.trim().to_string();
    let stdout = out.text();
    if !stdout.is_empty() {
        if !report.is_empty() {
            report.push('\n');
        }
        report.push_str(&stdout);
    }
    Ok(report)
}

#[cfg(test)]
mod runner_tests {
    use super::*;
    use crate::testutil::TempRepo;

    #[test]
    fn parses_versions() {
        let cases = [
            ("git version 2.43.0.windows.1", Some((2, 43, 0))),
            ("git version 2.39.3 (Apple Git-146)", Some((2, 39, 3))),
            ("git version 2.30.1\n", Some((2, 30, 1))),
            ("git version 2.30", Some((2, 30, 0))),
            ("git version 3.0.0-rc1", Some((3, 0, 0))),
            ("git version x.y", None),
            ("hello", None),
            ("", None),
        ];
        for (text, expected) in cases {
            assert_eq!(parse_version(text), expected, "{text}");
        }
        let (major, _, _) = version().unwrap();
        assert!(major >= 2);
    }

    #[test]
    fn raw_keeps_exit_code() {
        let repo = TempRepo::new(1);
        let out = repo.run(|| git_raw(&["rev-parse", "--verify", "nope"], &Opts::default()));
        let out = out.unwrap();
        assert_ne!(out.code, Some(0));
        assert!(out.code.is_some());
        assert!(!out.cancelled && !out.truncated);
        let error = repo.run(|| git_ok(&["rev-parse", "--verify", "nope"], &Opts::default()));
        assert!(!error.unwrap_err().to_string().is_empty());
        let head = repo
            .run(|| git_ok(&["rev-parse", "HEAD"], &Opts::default()))
            .unwrap();
        assert_eq!(head, repo.git(&["rev-parse", "HEAD"]));
    }

    #[test]
    fn stdin_round_trip() {
        let repo = TempRepo::new(0);
        let opts = Opts {
            stdin: Some(b"hello\n"),
            ..Opts::default()
        };
        let oid = repo
            .run(|| git_ok(&["hash-object", "--stdin"], &opts))
            .unwrap();
        assert_eq!(oid, "ce013625030ba8dba906f756967f9e9ca394464a");
    }

    #[test]
    fn max_lines_truncates() {
        let repo = TempRepo::new(5);
        let opts = Opts {
            max_lines: Some(2),
            ..Opts::default()
        };
        let out = repo
            .run(|| git_raw(&["log", "--format=%H"], &opts))
            .unwrap();
        assert!(out.truncated);
        assert_eq!(out.text().lines().count(), 2);
        let out = repo
            .run(|| {
                git_raw(
                    &["log", "--format=%H"],
                    &Opts {
                        max_lines: Some(5),
                        ..opts
                    },
                )
            })
            .unwrap();
        assert!(!out.truncated && out.ok());
        assert_eq!(out.text().lines().count(), 5);
    }

    #[test]
    fn stream_stops_when_asked() {
        let repo = TempRepo::new(4);
        let mut seen = Vec::new();
        let out = repo
            .run(|| {
                git_stream(&["log", "--format=%s"], &Opts::default(), &mut |line| {
                    seen.push(String::from_utf8_lossy(line).into_owned());
                    seen.len() < 2
                })
            })
            .unwrap();
        assert!(out.truncated);
        assert_eq!(seen, ["commit 4", "commit 3"]);
        let mut all = 0;
        let out = repo
            .run(|| {
                git_stream(&["log", "--format=%s"], &Opts::default(), &mut |_| {
                    all += 1;
                    true
                })
            })
            .unwrap();
        assert!(out.ok() && !out.truncated && out.stdout.is_empty());
        assert_eq!(all, 4);
    }

    /// A git alias that runs `sleep` through git's shell keeps git busy for a while. It runs
    /// outside any TempRepo: on Windows the orphaned `sleep` would keep its directory alive.
    const SLOW: [&str; 3] = ["-c", "alias.slow=!sleep 3", "slow"];

    #[test]
    fn timeout_kills_git() {
        let opts = Opts {
            timeout: Some(Duration::from_millis(300)),
            ..Opts::default()
        };
        let started = Instant::now();
        let result = TempRepo::outside().run(|| git_raw(&SLOW, &opts));
        assert!(result.unwrap_err().to_string().contains("timed out"));
        assert!(started.elapsed() < Duration::from_millis(2500));
    }

    #[test]
    fn cancel_kills_git() {
        let repo = TempRepo::new(0);
        let flag = AtomicBool::new(false);
        let started = Instant::now();
        let out = std::thread::scope(|scope| {
            scope.spawn(|| {
                std::thread::sleep(Duration::from_millis(200));
                flag.store(true, Ordering::Relaxed);
            });
            let opts = Opts {
                cancel: Some(&flag),
                ..Opts::default()
            };
            TempRepo::outside().run(|| git_raw(&SLOW, &opts))
        })
        .unwrap();
        assert!(out.cancelled && out.code.is_none());
        assert!(started.elapsed() < Duration::from_millis(2500));
        let opts = Opts {
            cancel: Some(&flag),
            ..Opts::default()
        };
        let error = repo.run(|| git_ok(&["status"], &opts)).unwrap_err();
        assert!(crate::input::is_cancel(&error));
    }

    #[test]
    fn with_ctx_targets_repo_and_restores() {
        let a = TempRepo::new(1);
        let b = TempRepo::new(2);
        let top =
            |r: &TempRepo| r.run(|| git_ok(&["rev-list", "--count", "HEAD"], &Opts::default()));
        assert_eq!(top(&a).unwrap(), "1");
        assert_eq!(top(&b).unwrap(), "2");
        a.run(|| {
            b.run(|| assert_eq!(run(&["rev-list", "--count", "HEAD"]).unwrap(), "2"));
            assert_eq!(run(&["rev-list", "--count", "HEAD"]).unwrap(), "1");
            // The context follows a worker started through ctx_snapshot/ctx_restore.
            let ctx = ctx_snapshot();
            let count = std::thread::spawn(move || {
                ctx_restore(ctx);
                run(&["rev-list", "--count", "HEAD"]).unwrap()
            })
            .join()
            .unwrap();
            assert_eq!(count, "1");
        });
        assert!(CTX.with(|ctx| ctx.borrow().dir.is_none()));
    }

    #[test]
    fn calls_are_logged() {
        let repo = TempRepo::new(1);
        let args = ["log", "-1", "--format=%H", "--grep=cmdlog-probe-xyz"];
        let out = repo.run(|| git_raw(&args, &Opts::default())).unwrap();
        assert_eq!(out.code, Some(0));
        // The per-thread record of this exact call, not the shared 200-entry ring.
        let last = LAST_CALL.with(|last| last.borrow().clone());
        assert_eq!(last, Some((args.join(" "), Some(0))));
        repo.run(|| run(&["rev-parse", "--verify", "nope"]))
            .unwrap_err();
        let last = LAST_CALL.with(|last| last.borrow().clone()).unwrap();
        assert_eq!(last.0, "rev-parse --verify nope");
        assert!(last.1.is_some_and(|code| code != 0));
    }

    /// Regression: after git exited, output the reader thread had not handed over yet was
    /// dropped under load (empty or partial stdout with exit code 0).
    #[test]
    fn output_is_never_lost_under_load() {
        let repo = TempRepo::new(3);
        std::thread::scope(|scope| {
            for _ in 0..8 {
                scope.spawn(|| {
                    repo.run(|| {
                        for _ in 0..25 {
                            let count = git_ok(&["rev-list", "--count", "HEAD"], &Opts::default());
                            assert_eq!(count.unwrap(), "3");
                        }
                    })
                });
            }
        });
    }

    /// A process left behind by git that keeps stdout open: what arrived is kept, the call
    /// returns after the drain deadline and reports `truncated`.
    #[test]
    fn leftover_child_holding_stdout_is_cut_off() {
        // `cd /` so the leftover sleep does not keep the temp directory alive on Windows.
        let args = ["-c", "alias.bg=!echo hi; (cd / && sleep 8 &)", "bg"];
        let started = Instant::now();
        let out = TempRepo::outside()
            .run(|| git_raw(&args, &Opts::default()))
            .unwrap();
        assert_eq!(out.text(), "hi");
        assert_eq!(out.code, Some(0));
        assert!(out.truncated);
        assert!(started.elapsed() < Duration::from_secs(8));
    }

    #[test]
    fn write_commands_get_the_long_write_timeout() {
        let write = Some(WRITE_TIMEOUT);
        let cases: [(&[&str], Option<Duration>); 12] = [
            (&["status"], Some(DEFAULT_TIMEOUT)),
            (&["log", "-1"], Some(DEFAULT_TIMEOUT)),
            (&["fetch", "origin"], Some(DEFAULT_TIMEOUT)),
            (
                &["-c", "core.x=1", "rev-parse", "HEAD"],
                Some(DEFAULT_TIMEOUT),
            ),
            (&["add", "."], write),
            (&["commit", "--amend", "-m", "x"], write),
            (&["-c", "credential.helper=x", "stash", "push", "-u"], write),
            (&["-C", "dir", "rebase", "--continue"], write),
            (&["--no-pager", "cherry-pick", "abc"], write),
            (&["update-ref", "refs/x", "abc"], write),
            (&["reset", "--hard"], write),
            (&[], Some(DEFAULT_TIMEOUT)),
        ];
        for (args, expected) in cases {
            assert_eq!(default_timeout(args), expected, "{args:?}");
        }
        for sub in [
            "apply", "am", "revert", "merge", "switch", "checkout", "restore", "clean", "branch",
            "tag", "config", "worktree", "gc", "prune", "pull",
        ] {
            assert_eq!(default_timeout(&[sub]), write, "{sub}");
        }
        assert_eq!(WRITE_TIMEOUT, Duration::from_secs(1800));
    }

    /// Regression: time spent inside the line callback (Log browsing) counted against the
    /// post-exit drain deadline, so the rest of the output was dropped as `truncated` with
    /// exit code 0.
    #[test]
    fn slow_callback_does_not_cut_off_the_drain() {
        // git exits at once; a leftover subshell prints b and c a second later (`cd /` so it
        // does not keep a temp directory alive on Windows).
        let args = [
            "-c",
            "alias.late=!echo a; (cd / && sleep 1 && echo b && echo c) &",
            "late",
        ];
        let mut seen = Vec::new();
        let out = TempRepo::outside()
            .run(|| {
                git_stream(&args, &Opts::default(), &mut |line| {
                    let line = String::from_utf8_lossy(line).into_owned();
                    if line == "b" {
                        // Longer than the whole drain window.
                        std::thread::sleep(DRAIN + Duration::from_millis(500));
                    }
                    seen.push(line);
                    true
                })
            })
            .unwrap();
        assert_eq!(seen, ["a", "b", "c"]);
        assert_eq!(out.code, Some(0));
        assert!(!out.truncated);
    }

    #[test]
    fn ctx_cancel_flag_kills_git() {
        let flag = Arc::new(AtomicBool::new(false));
        let ctx = ctx_snapshot().with_cancel(Arc::clone(&flag));
        let started = Instant::now();
        let out = std::thread::scope(|scope| {
            scope.spawn(|| {
                std::thread::sleep(Duration::from_millis(200));
                flag.store(true, Ordering::Relaxed);
            });
            scope
                .spawn(move || {
                    ctx_restore(ctx);
                    TempRepo::outside().run(|| git_raw(&SLOW, &Opts::default()))
                })
                .join()
                .unwrap()
        })
        .unwrap();
        assert!(out.cancelled && out.code.is_none());
        assert!(started.elapsed() < Duration::from_millis(2500));
    }

    #[test]
    fn force_if_includes_needs_git_2_30() {
        assert!(supports_force_if_includes(Some((2, 30, 0))));
        assert!(supports_force_if_includes(Some((2, 43, 1))));
        assert!(supports_force_if_includes(Some((3, 0, 0))));
        assert!(!supports_force_if_includes(Some((2, 29, 9))));
        assert!(!supports_force_if_includes(Some((1, 9, 0))));
        // Unknown version: keep the flag (the old behaviour).
        assert!(supports_force_if_includes(None));
        assert_eq!(
            push_args(
                "o",
                "r",
                Some("--force-with-lease=refs/heads/a"),
                false,
                None,
                false
            ),
            ["push", "--force-with-lease=refs/heads/a", "o", "r"]
        );
    }

    #[test]
    fn branch_names_are_validated() {
        for bad in ["", "-f", "--mirror", "--delete", "a b", "x\ny", "tab\t"] {
            assert!(branch_name_problem(bad).is_some(), "{bad:?}");
        }
        for good in ["main", "feat/x", "release-1.0", "ünï"] {
            assert!(branch_name_problem(good).is_none(), "{good}");
        }
        let repo = TempRepo::new(1);
        repo.run(|| {
            assert!(check_branch_name("main").is_ok());
            assert!(check_branch_name("feat/x").is_ok());
            for bad in ["--mirror", "a..b", "x~1", "end.lock", "-f"] {
                assert!(check_branch_name(bad).is_err(), "{bad}");
            }
            assert!(check_remote_name("origin").is_ok());
            assert!(check_remote_name("--upload-pack=x").is_err());
            assert!(check_remote_name("").is_err());
        });
    }

    #[test]
    fn lease_drops_the_expected_oid() {
        assert_eq!(
            lease_arg("refs/heads/feat:0123abcd"),
            "--force-with-lease=refs/heads/feat"
        );
        assert_eq!(
            lease_arg("refs/heads/feat"),
            "--force-with-lease=refs/heads/feat"
        );
        assert_eq!(lease_arg(""), "--force-with-lease");
        assert_eq!(
            push_args(
                "origin",
                "refs/heads/a:refs/heads/a",
                Some("--force-with-lease"),
                true,
                Some("me"),
                true
            ),
            [
                "-c",
                "credential.https://github.com.username=me",
                "push",
                "-u",
                "--force-with-lease",
                "--force-if-includes",
                "origin",
                "refs/heads/a:refs/heads/a",
            ]
        );
        assert_eq!(
            push_args("o", "r", None, false, Some(""), true),
            ["push", "o", "r"]
        );
    }

    #[test]
    fn push_rejects_option_like_names_and_pushes_refspec() {
        let repo = TempRepo::new(1).with_remote();
        repo.run(|| {
            for bad in ["--mirror", "-f", "--delete", ""] {
                assert!(push(bad, false, None).is_err(), "{bad}");
                assert!(push_to("origin", bad, None, false, None).is_err(), "{bad}");
            }
            assert!(push_to("--mirror", "main", None, false, None).is_err());
        });
        // Nothing was deleted or mirrored on the remote.
        let remote = repo.remote_path();
        let remote = remote.to_string_lossy();
        assert_eq!(
            repo.git(&["--git-dir", &remote, "rev-parse", "main"]),
            repo.git(&["rev-parse", "HEAD"])
        );
        repo.write("n.txt", "n\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-q", "-m", "next"]);
        repo.run(|| push("main", false, None)).unwrap();
        assert_eq!(
            repo.git(&["--git-dir", &remote, "rev-parse", "main"]),
            repo.git(&["rev-parse", "HEAD"])
        );
        // An amended commit goes up with the lease.
        repo.git(&["commit", "-q", "--amend", "-m", "next (amended)"]);
        repo.run(|| push("main", true, None)).unwrap();
        assert_eq!(
            repo.git(&["--git-dir", &remote, "rev-parse", "main"]),
            repo.git(&["rev-parse", "HEAD"])
        );
        // Without force a rewritten history is rejected with git's own message.
        repo.git(&["commit", "-q", "--amend", "-m", "again"]);
        let error = repo
            .run(|| push("main", false, None))
            .unwrap_err()
            .to_string();
        assert!(error.contains("rejected"), "{error}");
    }

    #[test]
    fn push_to_cancellable_honours_cancel() {
        let repo = TempRepo::new(1).with_remote();
        let flag = AtomicBool::new(true);
        let error = repo
            .run(|| push_to_cancellable("origin", "main", None, false, None, Some(&flag)))
            .unwrap_err();
        assert!(crate::input::is_cancel(&error));
        let report = repo.run(|| push_to_cancellable("origin", "main", None, false, None, None));
        assert!(report.is_ok(), "{report:?}");
    }

    #[test]
    fn legacy_commit_and_add_keep_their_errors() {
        let repo = TempRepo::new(1);
        let error = repo
            .run(|| commit("x", "2026-01-02 10:00:00", false, None))
            .unwrap_err();
        assert!(error.to_string().contains("nothing to commit"), "{error}");
        repo.write("a.txt", "a\n");
        repo.run(add_all).unwrap();
        assert!(repo
            .git(&["diff", "--cached", "--name-only"])
            .contains("a.txt"));
        let id = Identity {
            name: "Ann".into(),
            email: "ann@example.com".into(),
        };
        repo.run(|| commit("add a", "2026-01-02 10:00:00", false, Some(&id)))
            .unwrap();
        assert_eq!(
            repo.git(&["log", "-1", "--format=%an|%ae|%s"]),
            "Ann|ann@example.com|add a"
        );
        let outside = TempRepo::outside();
        assert!(!outside.run(add_all).unwrap_err().to_string().is_empty());
    }

    #[test]
    fn run_uses_c_locale() {
        // recent_commits matches git's English text for a fresh repo, even in a German shell.
        let repo = TempRepo::new(0);
        let german = vec![
            ("LANG".to_string(), "de_DE.UTF-8".to_string()),
            ("LANGUAGE".to_string(), "de".to_string()),
        ];
        let commits = repo.run(|| with_ctx(repo.path(), german, || recent_commits(5)));
        assert!(commits.unwrap().is_empty());
    }
}

#[cfg(test)]
mod plumbing_tests {
    use super::*;

    #[test]
    fn trims_end_but_keeps_leading_space() {
        assert_eq!(into_trimmed(b" M file\n\n".to_vec()), " M file");
    }

    #[test]
    fn invalid_utf8_is_lossy() {
        assert_eq!(into_trimmed(vec![b'a', 0xff, b'\n']), "a\u{fffd}");
    }

    #[test]
    fn parses_branch_lines() {
        assert_eq!(
            parse_lines("main\n  dev \n\nfeat/x"),
            ["main", "dev", "feat/x"]
        );
    }
}