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
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
//! Time travel mode: change the dates of existing commits on the current branch.
//!
//! No rebase, no filter-branch: every commit object in the range is read with `cat-file`,
//! rewritten byte-for-byte except its `parent`, `author`/`committer` timestamps and any
//! signature, written with `hash-object -w`, and the branch is moved with ONE compare-and-swap
//! `update-ref`. Trees never change, so there are no conflicts, no hooks and no working tree
//! update; if gct dies midway only unreferenced objects are left behind.

use crate::{
    git::{self, Opts},
    history::{self, LogEntry},
    input,
    model::Config,
    policy::{self, Op},
    repo_state::{self, EntryKind, Head},
    safety, screen,
    ui::{self, Choice, Key},
};
use anyhow::{anyhow, bail, Result};
use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, Weekday};

const TITLE: &str = "Time travel";
/// Most commits one run may rewrite.
const MAX_COMMITS: usize = 500;
const PREVIEW_ROWS: usize = 12;

/// One commit of the range, as read from the object database.
#[derive(Debug, Clone)]
struct Commit {
    oid: String,
    raw: Vec<u8>,
    /// (unix seconds, tz offset string such as "+0530").
    author: (i64, String),
    committer: (i64, String),
    signed: bool,
    subject: String,
}

/// The commits from the chosen oldest one up to the branch tip, oldest first.
#[derive(Debug, Clone)]
struct Range {
    branch: String,
    tip: String,
    /// Parent of the oldest commit; None when the range starts at the root commit.
    base: Option<String>,
    commits: Vec<Commit>,
}

#[derive(Debug)]
struct Applied {
    backup: String,
    new_tip: String,
}

// ---------------------------------------------------------------------------------------------
// Pure core
// ---------------------------------------------------------------------------------------------

/// Splits a commit object into its header lines (each with its '\n') and the rest, which
/// starts at the blank separator line. An object without a blank line is all header.
fn split_header(raw: &[u8]) -> (&[u8], &[u8]) {
    let end = raw
        .windows(2)
        .position(|w| w == b"\n\n")
        .map_or(raw.len(), |p| p + 1);
    raw.split_at(end)
}

fn is_signature_header(line: &[u8]) -> bool {
    line.starts_with(b"gpgsig ") || line.starts_with(b"gpgsig-sha256 ")
}

/// Replaces the " <ts> <tz>" after the last '>' of an author/committer line.
fn retime_line(line: &[u8], ts: i64, tz: &str) -> Vec<u8> {
    let Some(gt) = line.iter().rposition(|&b| b == b'>') else {
        return line.to_vec();
    };
    let mut out = line[..=gt].to_vec();
    out.extend_from_slice(format!(" {ts} {tz}").as_bytes());
    if line.ends_with(b"\r\n") {
        out.extend_from_slice(b"\r\n");
    } else if line.ends_with(b"\n") {
        out.push(b'\n');
    }
    out
}

/// Rewrites a raw commit object: the `parent` line becomes `new_parent` (removed for a new
/// root; the range is linear so there is at most one), the author/committer timestamps and tz
/// are replaced, `gpgsig`/`gpgsig-sha256` blocks (with their continuation lines) are dropped,
/// and every other byte (message, encoding, extra headers, CRLF, trailing newline) is kept.
pub fn rewrite_commit_object(
    raw: &[u8],
    new_parent: Option<&str>,
    author: (i64, &str),
    committer: (i64, &str),
) -> Vec<u8> {
    let (header, rest) = split_header(raw);
    let mut out = Vec::with_capacity(raw.len() + 48);
    let mut skipping = false;
    let mut parent_done = false;
    for line in header.split_inclusive(|&b| b == b'\n') {
        if line.starts_with(b" ") {
            if !skipping {
                out.extend_from_slice(line);
            }
            continue;
        }
        skipping = false;
        if line.starts_with(b"parent ") {
            if !parent_done {
                if let Some(parent) = new_parent {
                    out.extend_from_slice(format!("parent {parent}\n").as_bytes());
                }
                parent_done = true;
            }
            continue;
        }
        if !parent_done && !line.starts_with(b"tree ") {
            // The original was a root commit but the new one gets a parent.
            if let Some(parent) = new_parent {
                out.extend_from_slice(format!("parent {parent}\n").as_bytes());
            }
            parent_done = true;
        }
        if is_signature_header(line) {
            skipping = true;
        } else if line.starts_with(b"author ") {
            out.extend(retime_line(line, author.0, author.1));
        } else if line.starts_with(b"committer ") {
            out.extend(retime_line(line, committer.0, committer.1));
        } else {
            out.extend_from_slice(line);
        }
    }
    out.extend_from_slice(rest);
    out
}

/// "Name <mail> 1700000000 +0530" (after the keyword) -> (1700000000, "+0530").
fn parse_signature(line: &[u8]) -> Result<(i64, String)> {
    let gt = line
        .iter()
        .rposition(|&b| b == b'>')
        .ok_or_else(|| anyhow!("malformed author/committer line"))?;
    let tail = String::from_utf8_lossy(&line[gt + 1..]);
    let mut parts = tail.split_whitespace();
    let ts = parts
        .next()
        .and_then(|t| t.parse::<i64>().ok())
        .ok_or_else(|| anyhow!("malformed timestamp in author/committer line"))?;
    let tz = parts.next().unwrap_or("+0000").to_string();
    Ok((ts, tz))
}

/// Header facts of a raw commit.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ParsedCommit {
    parents: Vec<String>,
    /// (unix seconds, tz offset string such as "+0530").
    author: (i64, String),
    committer: (i64, String),
    signed: bool,
    subject: String,
}

fn parse_commit(raw: &[u8]) -> Result<ParsedCommit> {
    let (header, rest) = split_header(raw);
    let (mut parents, mut author, mut committer, mut signed) = (Vec::new(), None, None, false);
    for line in header.split_inclusive(|&b| b == b'\n') {
        let trimmed = line.strip_suffix(b"\n").unwrap_or(line);
        if let Some(p) = trimmed.strip_prefix(b"parent ") {
            parents.push(String::from_utf8_lossy(p).trim().to_string());
        } else if trimmed.starts_with(b"author ") {
            author = Some(parse_signature(trimmed)?);
        } else if trimmed.starts_with(b"committer ") {
            committer = Some(parse_signature(trimmed)?);
        } else if is_signature_header(line) {
            signed = true;
        }
    }
    let message = String::from_utf8_lossy(rest);
    let subject = message
        .trim_start()
        .lines()
        .next()
        .unwrap_or("")
        .trim_end()
        .to_string();
    Ok(ParsedCommit {
        parents,
        author: author.ok_or_else(|| anyhow!("commit has no author line"))?,
        committer: committer.ok_or_else(|| anyhow!("commit has no committer line"))?,
        signed,
        subject,
    })
}

/// "+0530" -> 19800 seconds, "-0800" -> -28800.
fn tz_offset(tz: &str) -> Result<i64> {
    let (sign, digits) = match tz.as_bytes().first() {
        Some(b'+') => (1, &tz[1..]),
        Some(b'-') => (-1, &tz[1..]),
        _ => bail!("unknown time zone '{tz}'"),
    };
    if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
        bail!("unknown time zone '{tz}'");
    }
    let hours: i64 = digits[..2].parse()?;
    let minutes: i64 = digits[2..].parse()?;
    Ok(sign * (hours * 3600 + minutes * 60))
}

/// Wall-clock time of `ts` in the fixed offset `tz`.
fn to_local(ts: i64, tz: &str) -> Result<NaiveDateTime> {
    ts.checked_add(tz_offset(tz)?)
        .and_then(|t| DateTime::from_timestamp(t, 0))
        .map(|d| d.naive_utc())
        .ok_or_else(|| anyhow!("timestamp {ts} out of range"))
}

/// Unix time of the wall-clock `local` in the fixed offset `tz` (no DST: offsets are fixed).
fn from_local(local: NaiveDateTime, tz: &str) -> Result<i64> {
    local
        .and_utc()
        .timestamp()
        .checked_sub(tz_offset(tz)?)
        .ok_or_else(|| anyhow!("date {local} out of range"))
}

/// Latest date gct writes: 9999-12-31 23:59:59 UTC.
const MAX_TS: i64 = 253_402_300_799;

/// A new commit time must be in 1970..=9999 (git stores unsigned seconds since 1970).
fn check_ts(ts: i64) -> Result<i64> {
    if (0..=MAX_TS).contains(&ts) {
        Ok(ts)
    } else {
        bail!(
            "The new date ({}) is outside 1970-9999; git cannot store it.",
            show_time(ts, "+0000")
        )
    }
}

/// `ts + delta`, checked for overflow and the 1970-9999 range.
fn shift_ts(ts: i64, delta: i64) -> Result<i64> {
    check_ts(
        ts.checked_add(delta)
            .ok_or_else(|| anyhow!("The shifted date is out of range."))?,
    )
}

fn show_time(ts: i64, tz: &str) -> String {
    to_local(ts, tz).map_or_else(
        |_| format!("@{ts} {tz}"),
        |t| format!("{} {tz}", t.format("%Y-%m-%d %H:%M:%S")),
    )
}

/// Deterministic 64-bit generator (splitmix64).
fn next_random(state: &mut u64) -> u64 {
    *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
    let mut z = *state;
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// `n` strictly increasing times inside [start, end) and inside the daily working hours
/// [hours.0:00, hours.1:00), optionally skipping Saturdays and Sundays. The usable seconds are
/// cut into `n` equal slots and one second is drawn per slot from a generator seeded with
/// `seed`, so the result is spread out, jittered and the same for the same seed.
pub fn spread_dates(
    n: usize,
    start: NaiveDateTime,
    end: NaiveDateTime,
    hours: (u32, u32),
    skip_weekends: bool,
    seed: u64,
) -> Result<Vec<NaiveDateTime>> {
    if hours.0 >= hours.1 || hours.1 > 24 {
        bail!("Working hours must be like 09-18 (start before end, end at most 24).");
    }
    if start >= end {
        bail!("The window must end after it starts.");
    }
    if (end - start).num_days() > 36_600 {
        bail!("The window is longer than 100 years.");
    }
    let mut spans: Vec<(NaiveDateTime, i64)> = Vec::new();
    let mut day = start.date();
    while day <= end.date() {
        let weekend = matches!(day.weekday(), Weekday::Sat | Weekday::Sun);
        if !(skip_weekends && weekend) {
            let midnight = day
                .and_hms_opt(0, 0, 0)
                .ok_or_else(|| anyhow!("bad date"))?;
            let at = |h: u32| {
                midnight
                    .checked_add_signed(Duration::hours(i64::from(h)))
                    .ok_or_else(|| anyhow!("date out of range"))
            };
            let open = at(hours.0)?.max(start);
            let close = at(hours.1)?.min(end);
            if close > open {
                spans.push((open, (close - open).num_seconds()));
            }
        }
        let Some(next) = day.succ_opt() else { break };
        day = next;
    }
    let total: i64 = spans.iter().map(|s| s.1).sum();
    if n == 0 {
        return Ok(Vec::new());
    }
    if n as i64 > total {
        bail!("Cannot fit {n} commits into the window: only {total} usable seconds.");
    }
    let mut state = seed;
    let mut out = Vec::with_capacity(n);
    for i in 0..n {
        let lo = (i as i128 * total as i128 / n as i128) as i64;
        let hi = ((i as i128 + 1) * total as i128 / n as i128) as i64;
        let mut offset = lo + (next_random(&mut state) % (hi - lo) as u64) as i64;
        let mut placed = None;
        for (open, len) in &spans {
            if offset < *len {
                placed = open.checked_add_signed(Duration::seconds(offset));
                break;
            }
            offset -= len;
        }
        out.push(placed.ok_or_else(|| anyhow!("internal error placing a date"))?);
    }
    Ok(out)
}

/// Largest shift accepted: 100 years (36 600 days).
const MAX_DELTA: i64 = 36_600 * 86_400;

/// "+2d", "-3h", "+1d 2h 30m", "90m", "1w" -> signed seconds. The leading sign applies to
/// the whole amount; zero and more than 100 years are refused.
pub fn parse_delta(text: &str) -> Result<i64> {
    let text = text.trim();
    let (sign, rest) = match text.strip_prefix('-') {
        Some(rest) => (-1, rest),
        None => (1, text.strip_prefix('+').unwrap_or(text)),
    };
    let usage = "Use amounts like +2d, -3h or +1d 2h 30m (w d h m s).";
    let (mut total, mut number, mut any) = (0i64, String::new(), false);
    for ch in rest.chars() {
        if ch.is_ascii_digit() {
            number.push(ch);
        } else if ch.is_whitespace() {
            if !number.is_empty() {
                bail!("Missing unit after {number}. {usage}");
            }
        } else {
            let unit = match ch.to_ascii_lowercase() {
                'w' => 604_800,
                'd' => 86_400,
                'h' => 3_600,
                'm' => 60,
                's' => 1,
                _ => bail!("Unknown unit '{ch}'. {usage}"),
            };
            if number.is_empty() {
                bail!("Missing number. {usage}");
            }
            let too_large = || anyhow!("Amount too large: at most 100 years (36600d).");
            let value: i64 = number.parse().map_err(|_| too_large())?;
            total = value
                .checked_mul(unit)
                .and_then(|v| total.checked_add(v))
                .filter(|t| *t <= MAX_DELTA)
                .ok_or_else(too_large)?;
            number.clear();
            any = true;
        }
    }
    if !number.is_empty() || !any {
        bail!("{usage}");
    }
    if total == 0 {
        bail!("Shifting by zero changes nothing.");
    }
    Ok(sign * total)
}

/// "9-18", "09-18", "09:00-18:00" -> (9, 18).
fn parse_hours(text: &str) -> Result<(u32, u32)> {
    let hour = |s: &str| -> Result<u32> {
        let s = s.trim();
        let s = s.strip_suffix(":00").unwrap_or(s);
        s.parse()
            .map_err(|_| anyhow!("Working hours must look like 09-18."))
    };
    let (a, b) = text
        .split_once('-')
        .ok_or_else(|| anyhow!("Working hours must look like 09-18."))?;
    Ok((hour(a)?, hour(b)?))
}

/// New (author, committer) seconds per commit. `None` keeps a commit's dates; with `sync`
/// the committer date follows the new author date, otherwise only the author date changes.
fn plan_times(old: &[(i64, i64)], new_author: &[Option<i64>], sync: bool) -> Vec<(i64, i64)> {
    old.iter()
        .zip(new_author)
        .map(|(&(a, c), new)| match new {
            Some(t) => (*t, if sync { *t } else { c }),
            None => (a, c),
        })
        .collect()
}

/// New author dates for "edit one commit" (the chosen commit is index 0 of the range).
/// Refuses dates git cannot store and shifts that overflow (old dates come from commit
/// objects and may be anything).
fn edit_one_times(
    old_authors: &[i64],
    new_time: i64,
    shift_later: bool,
) -> Result<Vec<Option<i64>>> {
    check_ts(new_time)?;
    let first = old_authors.first().copied().unwrap_or(new_time);
    let delta = new_time
        .checked_sub(first)
        .ok_or_else(|| anyhow!("The shift is out of range."))?;
    old_authors
        .iter()
        .enumerate()
        .map(|(i, &a)| match (i, shift_later) {
            (0, _) => Ok(Some(new_time)),
            (_, true) => shift_ts(a, delta).map(Some),
            (_, false) => Ok(None),
        })
        .collect()
}

fn preview_rows(range: &Range, times: &[(i64, i64)]) -> Vec<String> {
    range
        .commits
        .iter()
        .zip(times)
        .map(|(c, &(a, _))| {
            let old = show_time(c.author.0, &c.author.1);
            let new = if a == c.author.0 {
                "(unchanged)".to_string()
            } else {
                show_time(a, &c.author.1)
            };
            format!("{}  {old}  ->  {new}  {}", short(&c.oid), c.subject)
        })
        .collect()
}

fn preview_warnings(
    range: &Range,
    times: &[(i64, i64)],
    published: bool,
    sync: bool,
) -> Vec<String> {
    let mut out = Vec::new();
    let signed = range.commits.iter().filter(|c| c.signed).count();
    if signed > 0 {
        out.push(screen::warning(format!(
            "! {signed} signed commit(s): the signature is dropped (it would no longer be valid)."
        )));
    }
    if published {
        out.push(screen::warning(
            "! Some of these commits are already pushed. You will need a force-with-lease push.",
        ));
    }
    if times.windows(2).any(|w| w[1].0 < w[0].0) {
        out.push(screen::warning(
            "! The new author dates are not in order (a commit is older than its parent).",
        ));
    }
    out.push(screen::muted(if sync {
        "Committer date = author date."
    } else {
        "Only the author date changes; committer dates stay as they are."
    }));
    out
}

fn short(oid: &str) -> &str {
    oid.get(..7).unwrap_or(oid)
}

// ---------------------------------------------------------------------------------------------
// Executors (run git)
// ---------------------------------------------------------------------------------------------

/// The current branch and its tip; refuses detached HEAD, unborn branches, operations in
/// progress and uncommitted changes (untracked files are fine: nothing on disk changes).
fn preflight() -> Result<(String, String)> {
    let state = repo_state::load()?;
    let name = match state.branch.head {
        Head::Branch { name, .. } => name,
        Head::Detached { .. } => {
            bail!("HEAD is detached. Switch to a branch first: time travel rewrites a branch.")
        }
        Head::Unborn { name } => bail!("Branch {name} has no commits yet."),
    };
    if let Some(op) = state.op {
        bail!("A {op:?} is in progress. Finish or abort it first.");
    }
    if state
        .entries
        .iter()
        .any(|e| !matches!(e.kind, EntryKind::Untracked | EntryKind::Ignored))
    {
        bail!("The working tree has uncommitted changes. Commit or stash them first.");
    }
    let tip = git::git_ok(
        &["rev-parse", "--verify", &format!("refs/heads/{name}")],
        &Opts::default(),
    )?;
    Ok((name, tip))
}

/// Reads `oldest..tip` (inclusive of `oldest`) after checking every precondition.
fn load_range(oldest: &str) -> Result<Range> {
    let (branch, tip) = preflight()?;
    if oldest.starts_with('-') {
        bail!("'{oldest}' is not a commit.");
    }
    let quiet = |args: &[&str]| -> Result<Option<String>> {
        let out = git::git_raw(args, &Opts::default())?;
        Ok(out
            .ok()
            .then(|| out.text().trim().to_string())
            .filter(|s| !s.is_empty()))
    };
    let oid = quiet(&[
        "rev-parse",
        "--verify",
        "--quiet",
        &format!("{oldest}^{{commit}}"),
    ])?
    .ok_or_else(|| anyhow!("'{oldest}' is not a commit."))?;
    if !git::git_raw(
        &["merge-base", "--is-ancestor", &oid, &tip],
        &Opts::default(),
    )?
    .ok()
    {
        bail!("Commit {} is not on branch {branch}.", short(&oid));
    }
    let base = quiet(&["rev-parse", "--verify", "--quiet", &format!("{oid}^")])?;
    let spec = match &base {
        Some(b) => format!("{b}..{tip}"),
        None => tip.clone(),
    };
    let merges = git::git_ok(&["rev-list", "--merges", &spec], &Opts::default())?;
    if !merges.trim().is_empty() {
        bail!("The range contains merge commits. Time travel only rewrites linear history.");
    }
    let list = git::git_ok(
        &["rev-list", "--reverse", "--parents", &spec],
        &Opts::default(),
    )?;
    let rows: Vec<Vec<&str>> = list
        .lines()
        .map(|l| l.split_whitespace().collect())
        .collect();
    if rows.len() > MAX_COMMITS {
        bail!(
            "{} commits selected; at most {MAX_COMMITS} can be rewritten at once.",
            rows.len()
        );
    }
    // Linear chain from `oid` (whose parent is `base`) to `tip`.
    let mut expected = base.clone();
    for row in &rows {
        let parent = row.get(1).map(|p| p.to_string());
        if row.len() > 2 || parent != expected {
            bail!("The range is not a simple line of commits. Time travel only rewrites linear history.");
        }
        expected = row.first().map(|o| o.to_string());
    }
    if rows.first().and_then(|r| r.first()) != Some(&oid.as_str())
        || expected.as_deref() != Some(tip.as_str())
    {
        bail!("Could not walk from {} to the branch tip.", short(&oid));
    }
    let oids: Vec<&str> = rows.iter().filter_map(|r| r.first().copied()).collect();
    let commits = read_commits(&oids)?;
    Ok(Range {
        branch,
        tip,
        base,
        commits,
    })
}

/// Reads raw commit objects with one `cat-file --batch` call (bytes, no lossy conversion).
fn read_commits(oids: &[&str]) -> Result<Vec<Commit>> {
    let mut input = oids.join("\n").into_bytes();
    input.push(b'\n');
    let out = git::git_raw(
        &["cat-file", "--batch"],
        &Opts {
            stdin: Some(&input),
            ..Opts::default()
        },
    )?;
    if !out.ok() {
        bail!("git cat-file failed: {}", out.stderr.trim());
    }
    let mut data = out.stdout.as_slice();
    let mut commits = Vec::with_capacity(oids.len());
    for oid in oids {
        let nl = data
            .iter()
            .position(|&b| b == b'\n')
            .ok_or_else(|| anyhow!("short cat-file output"))?;
        let head = String::from_utf8_lossy(&data[..nl]).to_string();
        let fields: Vec<&str> = head.split_whitespace().collect();
        let [got, "commit", size] = fields[..] else {
            bail!("cannot read commit {oid}: {head}");
        };
        let size: usize = size.parse()?;
        if got != *oid || data.len() < nl + 1 + size {
            bail!("unexpected cat-file output for {oid}");
        }
        let raw = data[nl + 1..nl + 1 + size].to_vec();
        data = data.get(nl + 2 + size..).unwrap_or(&[]);
        let p = parse_commit(&raw)?;
        commits.push(Commit {
            oid: oid.to_string(),
            raw,
            author: p.author,
            committer: p.committer,
            signed: p.signed,
            subject: p.subject,
        });
    }
    Ok(commits)
}

/// Backs up the old tip, writes the rewritten objects and moves the branch with one
/// compare-and-swap update-ref. If the branch moved meanwhile nothing is changed.
fn apply(range: &Range, times: &[(i64, i64)]) -> Result<Applied> {
    if times.len() != range.commits.len() || range.commits.is_empty() {
        bail!("internal error: plan does not match the range");
    }
    for (commit, &(a, c)) in range.commits.iter().zip(times) {
        if a != commit.author.0 {
            check_ts(a)?;
        }
        if c != commit.committer.0 {
            check_ts(c)?;
        }
    }
    let backup = safety::backup("timetravel", &range.tip)?;
    let mut parent = range.base.clone();
    for (commit, &(a, c)) in range.commits.iter().zip(times) {
        let raw = rewrite_commit_object(
            &commit.raw,
            parent.as_deref(),
            (a, &commit.author.1),
            (c, &commit.committer.1),
        );
        let oid = git::git_ok(
            &["hash-object", "-t", "commit", "-w", "--stdin"],
            &Opts {
                stdin: Some(&raw),
                ..Opts::default()
            },
        )?;
        parent = Some(oid);
    }
    let new_tip = parent.ok_or_else(|| anyhow!("nothing was written"))?;
    let tree =
        |rev: &str| git::git_ok(&["rev-parse", &format!("{rev}^{{tree}}")], &Opts::default());
    if tree(&new_tip)? != tree(&range.tip)? {
        bail!("Safety check failed: the rewritten tip has a different tree. Nothing was changed.");
    }
    let refname = format!("refs/heads/{}", range.branch);
    let out = git::git_raw(
        &[
            "update-ref",
            "-m",
            "gct timetravel",
            &refname,
            &new_tip,
            &range.tip,
        ],
        &Opts::default(),
    )?;
    if !out.ok() {
        bail!(
            "Branch {} moved since the plan was made, so nothing was changed. Try again. ({})",
            range.branch,
            out.stderr.trim()
        );
    }
    Ok(Applied { backup, new_tip })
}

// ---------------------------------------------------------------------------------------------
// UI glue
// ---------------------------------------------------------------------------------------------

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    loop {
        if let Err(e) = preflight() {
            return ui::notice(TITLE, &[screen::warning(e.to_string())]);
        }
        let mut context = vec![
            "Change the dates of commits on this branch. Files and messages stay exactly the same."
                .to_string(),
        ];
        context.extend(ui::explain(
            config,
            &[
                "Each commit is copied with new dates and the branch is moved to the copies.",
                "A backup ref keeps the old commits, so this can be undone.",
            ],
        ));
        let options = [
            "Edit one commit's date",
            "Spread commits across a time window",
            "Shift a range of commits by a fixed amount",
            "Back",
        ];
        let result = match ui::choose(TITLE, &context, &options)? {
            Some(0) => edit_one(config),
            Some(1) => spread(config),
            Some(2) => shift(config),
            _ => return Ok(()),
        };
        if let Err(e) = result {
            if e.to_string() == input::CANCELLED {
                return Err(e);
            }
            ui::notice(TITLE, &[screen::danger(format!("x {e}"))])?;
        }
    }
}

fn recent() -> Result<Vec<LogEntry>> {
    let format = format!("--format={}", history::LOG_FORMAT);
    let text = git::git_ok(&["log", "-n", "300", &format, "HEAD"], &Opts::default())?;
    Ok(history::parse_log(&text))
}

fn log_row(e: &LogEntry) -> String {
    let date = e.author_date.replacen('T', " ", 1);
    let date = date.get(..19).unwrap_or(&date);
    let merge = if e.parents.len() > 1 { "[merge] " } else { "" };
    format!("{}  {date}  {merge}{}", e.short, e.subject)
}

/// Lets the user pick one commit (`range == false`) or the oldest commit of a range (Enter
/// on a commit, or `n` for "last N"). Returns its full oid.
fn pick_commit(title: &str, range: bool) -> Result<Option<String>> {
    let entries = recent()?;
    if entries.is_empty() {
        ui::notice(TITLE, &["No commits yet. Make a commit first.".into()])?;
        return Ok(None);
    }
    let rows: Vec<String> = entries.iter().map(log_row).collect();
    let header = vec![if range {
        "Pick the OLDEST commit to change; it and every newer commit get new dates.".to_string()
    } else {
        "Pick the commit whose date you want to change.".to_string()
    }];
    let keys: &[Key] = if range {
        &[Key {
            key: 'n',
            label: "last N commits",
        }]
    } else {
        &[]
    };
    let mut index = 0usize;
    loop {
        match ui::action_list(title, &header, &rows, keys, &mut index)? {
            Choice::Back => return Ok(None),
            Choice::Open(i) if i < entries.len() => {
                if !range {
                    return Ok(Some(entries[i].oid.clone()));
                }
                let choice = ui::choose(
                    title,
                    &[rows[i].clone()],
                    &[
                        "Change this commit and every newer one",
                        "Choose the last N commits instead",
                        "Back",
                    ],
                )?;
                match choice {
                    Some(0) => return Ok(Some(entries[i].oid.clone())),
                    Some(1) => {
                        if let Some(oid) = ask_last_n(&entries)? {
                            return Ok(Some(oid));
                        }
                    }
                    _ => {}
                }
            }
            Choice::Action('n', _) if range => {
                if let Some(oid) = ask_last_n(&entries)? {
                    return Ok(Some(oid));
                }
            }
            _ => {}
        }
    }
}

fn ask_last_n(entries: &[LogEntry]) -> Result<Option<String>> {
    let max = entries.len().min(MAX_COMMITS);
    let Some(answer) = ui::ask(&format!("How many recent commits? (1-{max}):"), "")? else {
        return Ok(None);
    };
    match answer.trim().parse::<usize>() {
        Ok(n) if (1..=max).contains(&n) => Ok(Some(entries[n - 1].oid.clone())),
        _ => {
            ui::notice(
                TITLE,
                &[screen::warning(format!("Enter a number from 1 to {max}."))],
            )?;
            Ok(None)
        }
    }
}

fn ask_date(prompt: &str, initial: NaiveDate) -> Result<NaiveDate> {
    let text = input::masked(prompt, &initial.format("%Y-%m-%d").to_string(), true)?;
    NaiveDate::parse_from_str(&text, "%Y-%m-%d").map_err(|_| anyhow!("'{text}' is not a date."))
}

fn edit_one(cfg: &mut Config) -> Result<()> {
    let Some(oid) = pick_commit("Time travel: pick a commit", false)? else {
        return Ok(());
    };
    let range = load_range(&oid)?;
    let first = &range.commits[0];
    let (ts, tz) = (first.author.0, first.author.1.clone());
    let local = to_local(ts, &tz)?;
    let date = ask_date("Commit date (YYYY-MM-DD):", local.date())?;
    let time = input::masked(
        "Commit time (HH:MM:SS):",
        &local.format("%H:%M:%S").to_string(),
        false,
    )?;
    let time = chrono::NaiveTime::parse_from_str(&time, "%H:%M:%S")
        .map_err(|_| anyhow!("'{time}' is not a time."))?;
    let new_time = from_local(date.and_time(time), &tz)?;
    let later = range.commits.len() - 1;
    let options = [
        "Change only this commit".to_string(),
        format!("Shift this commit and the {later} newer one(s) by the same amount"),
    ];
    let refs: Vec<&str> = options.iter().map(String::as_str).collect();
    let shift_later = match ui::choose(
        TITLE,
        &[format!(
            "{} -> {}",
            show_time(ts, &tz),
            show_time(new_time, &tz)
        )],
        &refs,
    )? {
        Some(0) => false,
        Some(1) => true,
        _ => return Ok(()),
    };
    let authors: Vec<i64> = range.commits.iter().map(|c| c.author.0).collect();
    finish(
        cfg,
        &range,
        &edit_one_times(&authors, new_time, shift_later)?,
    )
}

fn spread(cfg: &mut Config) -> Result<()> {
    let Some(oid) = pick_commit("Time travel: commits to spread", true)? else {
        return Ok(());
    };
    let range = load_range(&oid)?;
    let first = &range.commits[0];
    let start = ask_date(
        "Window start date (YYYY-MM-DD):",
        to_local(first.author.0, &first.author.1)?.date(),
    )?;
    let end = ask_date(
        "Window end date (YYYY-MM-DD):",
        chrono::Local::now().date_naive(),
    )?;
    let Some(hours) = ui::ask("Working hours (start-end, 24h clock):", "09-18")? else {
        return Ok(());
    };
    let hours = parse_hours(&hours)?;
    let skip_weekends = match ui::choose(
        TITLE,
        &[],
        &["Skip weekends (Saturday and Sunday)", "Include weekends"],
    )? {
        Some(0) => true,
        Some(1) => false,
        _ => return Ok(()),
    };
    let Some(seed) = ui::ask(
        "Jitter seed (any number; the same seed gives the same dates):",
        "1",
    )?
    else {
        return Ok(());
    };
    let seed: u64 = seed
        .trim()
        .parse()
        .map_err(|_| anyhow!("The seed must be a whole number."))?;
    let midnight = |d: NaiveDate| d.and_hms_opt(0, 0, 0).ok_or_else(|| anyhow!("bad date"));
    let window_end = midnight(
        end.succ_opt()
            .ok_or_else(|| anyhow!("end date out of range"))?,
    )?;
    let dates = spread_dates(
        range.commits.len(),
        midnight(start)?,
        window_end,
        hours,
        skip_weekends,
        seed,
    )?;
    let new_author = range
        .commits
        .iter()
        .zip(&dates)
        .map(|(c, d)| from_local(*d, &c.author.1).and_then(check_ts).map(Some))
        .collect::<Result<Vec<_>>>()?;
    finish(cfg, &range, &new_author)
}

fn shift(cfg: &mut Config) -> Result<()> {
    let Some(oid) = pick_commit("Time travel: commits to shift", true)? else {
        return Ok(());
    };
    let range = load_range(&oid)?;
    let Some(text) = ui::ask("Shift by (e.g. +2d, -3h, +1d 2h 30m):", "+1d")? else {
        return Ok(());
    };
    let delta = parse_delta(&text)?;
    finish(cfg, &range, &shift_times(&range.commits, delta)?)
}

/// New author dates for "shift by a fixed amount" (checked: commit dates may be anything).
fn shift_times(commits: &[Commit], delta: i64) -> Result<Vec<Option<i64>>> {
    commits
        .iter()
        .map(|c| shift_ts(c.author.0, delta).map(Some))
        .collect()
}

/// Committer toggle, preview, policy gate, apply, result.
fn finish(cfg: &mut Config, range: &Range, new_author: &[Option<i64>]) -> Result<()> {
    let sync = match ui::choose(
        TITLE,
        &["Git stores two dates per commit: author date and committer date.".into()],
        &[
            "Set committer date = author date (recommended)",
            "Change only the author date",
        ],
    )? {
        Some(0) => true,
        Some(1) => false,
        _ => return Ok(()),
    };
    let old: Vec<(i64, i64)> = range
        .commits
        .iter()
        .map(|c| (c.author.0, c.committer.0))
        .collect();
    let times = plan_times(&old, new_author, sync);
    let published = safety::is_published(&range.commits[0].oid)?;
    let rows = preview_rows(range, &times);
    let warnings = preview_warnings(range, &times, published, sync);
    let n = range.commits.len();
    loop {
        let mut context = vec![format!(
            "{n} commit(s) on {} will get these author dates:",
            range.branch
        )];
        context.extend(rows.iter().take(PREVIEW_ROWS).cloned());
        if rows.len() > PREVIEW_ROWS {
            context.push(screen::muted(format!(
                "... and {} more",
                rows.len() - PREVIEW_ROWS
            )));
        }
        context.extend(warnings.iter().cloned());
        match ui::choose(
            "Preview",
            &context,
            &["Apply these dates", "Show the full preview", "Cancel"],
        )? {
            Some(0) => break,
            Some(1) => {
                let mut full = rows.clone();
                full.push(String::new());
                full.extend(warnings.iter().cloned());
                ui::pager("Preview", &full, "")?;
            }
            _ => return Ok(()),
        }
    }
    let refname = format!("refs/heads/{}", range.branch);
    let command = format!(
        "git hash-object -t commit -w --stdin (x{n}) && git update-ref -m \"gct timetravel\" {refname} <new tip> {}",
        short(&range.tip)
    );
    // `published` is checked on the OLDEST rewritten commit: if it is pushed, so is the rest
    // of what it replaces.
    let verdict = policy::check(
        cfg,
        &Op::RewriteHistory {
            branch: &range.branch,
            published,
        },
    );
    let what = format!(
        "Rewrite the dates of {n} commit(s) on {}.\nThe old tip {} is saved first as backup refs/gct/backup/<time>-timetravel (its exact name is shown afterwards; restore it from Undo & Rescue).",
        range.branch,
        short(&range.tip)
    );
    if !ui::gate(cfg, &verdict, &what, &command)? {
        return Ok(());
    }
    let applied = ui::git_job("Rewriting commit dates", || apply(range, &times))?;
    let mut lines = vec![
        screen::success(format!(
            "v Rewrote the dates of {n} commit(s) on {}.",
            range.branch
        )),
        format!(
            "$ git update-ref -m \"gct timetravel\" {refname} {} {}",
            applied.new_tip, range.tip
        ),
        format!("Backup of the old history: {}", applied.backup),
        screen::muted(format!("Undo with: git reset --keep {}", applied.backup)),
    ];
    if published {
        lines.push(screen::warning(
            "! This branch was already pushed. Publish the new history with Sync's force-with-lease push (gct never pushes for you).",
        ));
    }
    lines.extend(ui::explain(
        cfg,
        &[
            "Only the dates changed: every file and message is the same as before.",
            "The old commits still exist under the backup ref until you delete it.",
        ],
    ));
    ui::notice(TITLE, &lines)
}

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

    const TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
    const P1: &str = "1111111111111111111111111111111111111111";
    const P2: &str = "2222222222222222222222222222222222222222";

    fn dt(s: &str) -> NaiveDateTime {
        NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").unwrap()
    }

    #[test]
    fn rewrites_chain_commit_and_tz() {
        let raw = format!(
            "tree {TREE}\nparent {P1}\nauthor Ann <a@x.io> 1700000000 +0530\ncommitter Bob <b@x.io> 1700000100 -0800\n\nfix the parent pointer\n\nparent {P1} is mentioned here\n"
        );
        let out = rewrite_commit_object(
            raw.as_bytes(),
            Some(P2),
            (1600000000, "+0530"),
            (1600000005, "-0800"),
        );
        let expected = format!(
            "tree {TREE}\nparent {P2}\nauthor Ann <a@x.io> 1600000000 +0530\ncommitter Bob <b@x.io> 1600000005 -0800\n\nfix the parent pointer\n\nparent {P1} is mentioned here\n"
        );
        assert_eq!(String::from_utf8(out).unwrap(), expected);
        let p = parse_commit(raw.as_bytes()).unwrap();
        assert_eq!(p.parents, [P1]);
        assert_eq!(p.author, (1700000000, "+0530".into()));
        assert_eq!(p.committer, (1700000100, "-0800".into()));
        assert!(!p.signed);
        assert_eq!(p.subject, "fix the parent pointer");
    }

    #[test]
    fn rewrites_root_and_adds_or_removes_parent() {
        let root =
            format!("tree {TREE}\nauthor A <a@x> 1 +0000\ncommitter A <a@x> 2 +0000\n\nroot\n");
        let same = rewrite_commit_object(root.as_bytes(), None, (1, "+0000"), (2, "+0000"));
        assert_eq!(same, root.as_bytes());
        let with_parent =
            rewrite_commit_object(root.as_bytes(), Some(P1), (1, "+0000"), (2, "+0000"));
        assert!(String::from_utf8(with_parent)
            .unwrap()
            .starts_with(&format!("tree {TREE}\nparent {P1}\nauthor ")));
        let chain = format!(
            "tree {TREE}\nparent {P1}\nauthor A <a@x> 1 +0000\ncommitter A <a@x> 2 +0000\n\nm\n"
        );
        let new_root = rewrite_commit_object(chain.as_bytes(), None, (1, "+0000"), (2, "+0000"));
        assert_eq!(new_root, root.replace("root", "m").as_bytes());
    }

    #[test]
    fn drops_signatures_keeps_encoding_and_crlf() {
        let raw = format!(
            "tree {TREE}\nparent {P1}\nauthor Zo\u{eb} <z@x> 1700000000 +0000\ncommitter Zo\u{eb} <z@x> 1700000000 +0000\nencoding ISO-8859-1\ngpgsig -----BEGIN PGP SIGNATURE-----\n \n iQEzBAABCAAdFiEE\n -----END PGP SIGNATURE-----\ngpgsig-sha256 -----BEGIN SSH SIGNATURE-----\n abc\n -----END SSH SIGNATURE-----\nx-extra value\n continued\n\nsubject\r\n\r\nbody\r\n"
        );
        assert!(parse_commit(raw.as_bytes()).unwrap().signed);
        let mut bytes = raw.into_bytes();
        bytes.push(0xE9); // a Latin-1 byte in the message must survive untouched
        let out = rewrite_commit_object(&bytes, Some(P1), (5, "+0000"), (6, "+0000"));
        let mut expected = format!(
            "tree {TREE}\nparent {P1}\nauthor Zo\u{eb} <z@x> 5 +0000\ncommitter Zo\u{eb} <z@x> 6 +0000\nencoding ISO-8859-1\nx-extra value\n continued\n\nsubject\r\n\r\nbody\r\n"
        )
        .into_bytes();
        expected.push(0xE9);
        assert_eq!(out, expected);
    }

    #[test]
    fn timezones_and_shift_math() {
        assert_eq!(tz_offset("+0530").unwrap(), 19800);
        assert_eq!(tz_offset("-0800").unwrap(), -28800);
        assert!(tz_offset("0800").is_err() && tz_offset("+08").is_err());
        let local = dt("2024-03-10 01:30:00"); // a US DST switch day: offsets are fixed, so no gap
        let ts = from_local(local, "-0800").unwrap();
        assert_eq!(ts, 1710063000);
        assert_eq!(
            to_local(ts + 86_400, "-0800").unwrap(),
            dt("2024-03-11 01:30:00")
        );
        assert_eq!(to_local(ts, "+0530").unwrap(), dt("2024-03-10 15:00:00"));
        assert_eq!(parse_delta("+2d").unwrap(), 172_800);
        assert_eq!(
            parse_delta("-1d 2h 30m").unwrap(),
            -(86_400 + 7_200 + 1_800)
        );
        assert_eq!(parse_delta("90m").unwrap(), 5_400);
        assert_eq!(parse_delta("1W").unwrap(), 604_800);
        for bad in ["", "+", "5", "2x", "d", "0h", "3 h"] {
            assert!(parse_delta(bad).is_err(), "{bad}");
        }
        assert_eq!(parse_hours("09-18").unwrap(), (9, 18));
        assert_eq!(parse_hours("9:00 - 17:00").unwrap(), (9, 17));
        assert!(parse_hours("nine").is_err());
    }

    #[test]
    fn plans_times() {
        let old = [(100, 110), (200, 210), (300, 310)];
        assert_eq!(
            edit_one_times(&[100, 200, 300], 150, false).unwrap(),
            [Some(150), None, None]
        );
        assert_eq!(
            edit_one_times(&[100, 200, 300], 150, true).unwrap(),
            [Some(150), Some(250), Some(350)]
        );
        let new = [Some(150), None, Some(350)];
        assert_eq!(
            plan_times(&old, &new, true),
            [(150, 150), (200, 210), (350, 350)]
        );
        assert_eq!(
            plan_times(&old, &new, false),
            [(150, 110), (200, 210), (350, 310)]
        );
    }

    #[test]
    fn date_math_never_overflows() {
        // Huge user deltas are refused instead of overflowing.
        for bad in [
            "+15000000000000w",
            "-15000000000000w",
            "+99999999999999999999s",
            "36601d",
            "+36600d 1s",
            "5300w",
        ] {
            let err = parse_delta(bad).unwrap_err().to_string();
            assert!(err.contains("too large"), "{bad}: {err}");
        }
        assert_eq!(parse_delta("+36600d").unwrap(), MAX_DELTA);
        assert_eq!(parse_delta("-36600d").unwrap(), -MAX_DELTA);
        // Time zone extremes and timestamps near the i64 limits (a malicious commit object).
        assert_eq!(tz_offset("+9959").unwrap(), 99 * 3600 + 59 * 60);
        assert_eq!(tz_offset("-9959").unwrap(), -(99 * 3600 + 59 * 60));
        assert!(to_local(i64::MAX, "+9959").is_err());
        assert!(to_local(i64::MIN, "-9959").is_err());
        assert!(to_local(i64::MAX - 10, "+0000").is_err());
        assert_eq!(show_time(i64::MAX, "+0100"), format!("@{} +0100", i64::MAX));
        assert!(from_local(dt("2024-01-01 00:00:00"), "-9959").is_ok());
        assert!(from_local(NaiveDateTime::MAX, "-9959").is_ok());
        let big = format!(
            "tree {TREE}\nauthor A <a@x> {} +9959\ncommitter A <a@x> {} -9959\n\nm\n",
            i64::MAX,
            i64::MIN
        );
        let p = parse_commit(big.as_bytes()).unwrap();
        assert_eq!((p.author.0, p.committer.0), (i64::MAX, i64::MIN));
        assert!(parse_commit(format!("tree {TREE}\nauthor A <a@x> 99999999999999999999 +0000\ncommitter A <a@x> 1 +0000\n\nm\n").as_bytes()).is_err());
        // Shifts and edits are checked and stay inside 1970-9999.
        assert!(shift_ts(i64::MAX, 1).is_err());
        assert!(shift_ts(i64::MIN, -1).is_err());
        assert!(shift_ts(100, -101).is_err(), "before 1970");
        assert!(shift_ts(MAX_TS, 1).is_err(), "after 9999");
        assert_eq!(shift_ts(100, MAX_DELTA).unwrap(), 100 + MAX_DELTA);
        let commit = |ts: i64| Commit {
            oid: P1.into(),
            raw: Vec::new(),
            author: (ts, "+0000".into()),
            committer: (ts, "+0000".into()),
            signed: false,
            subject: String::new(),
        };
        assert!(shift_times(&[commit(1_700_000_000), commit(i64::MAX)], 60).is_err());
        assert_eq!(
            shift_times(&[commit(1_700_000_000)], -60).unwrap(),
            [Some(1_699_999_940)]
        );
        assert!(edit_one_times(&[i64::MIN, 5], 1_700_000_000, true).is_err());
        assert!(edit_one_times(&[100, i64::MAX], 200, true).is_err());
        assert_eq!(
            edit_one_times(&[100, i64::MAX], 200, false).unwrap(),
            [Some(200), None]
        );
        assert!(edit_one_times(&[100], -1, false).is_err());
        // Spread near the end of chrono's calendar errors instead of panicking.
        let last = NaiveDateTime::MAX.date().and_hms_opt(0, 0, 0).unwrap();
        assert!(spread_dates(1, last, NaiveDateTime::MAX, (0, 24), false, 0).is_err());
    }

    #[test]
    fn apply_refuses_unstorable_dates() {
        let repo = TempRepo::new(2);
        let tip = repo.git(&["rev-parse", "HEAD"]);
        repo.run(|| {
            let range = load_range("HEAD").unwrap();
            let c = &range.commits[0];
            assert!(apply(&range, &[(-5, c.committer.0)]).is_err());
            assert!(apply(&range, &[(c.author.0, MAX_TS + 1)]).is_err());
            assert!(
                safety::backups().unwrap().is_empty(),
                "refused before any backup or write"
            );
        });
        assert_eq!(repo.git(&["rev-parse", "HEAD"]), tip);
    }

    #[test]
    fn spread_dates_properties() {
        let (start, end) = (dt("2024-01-01 00:00:00"), dt("2024-01-15 00:00:00"));
        for skip in [false, true] {
            let dates = spread_dates(40, start, end, (9, 18), skip, 7).unwrap();
            assert_eq!(dates.len(), 40);
            assert!(dates.windows(2).all(|w| w[0] < w[1]), "strictly increasing");
            for d in &dates {
                assert!(*d >= start && *d < end);
                let hour = chrono::Timelike::hour(d);
                assert!((9..18).contains(&hour), "{d}");
                if skip {
                    assert!(!matches!(d.weekday(), Weekday::Sat | Weekday::Sun), "{d}");
                }
            }
            assert_eq!(
                dates,
                spread_dates(40, start, end, (9, 18), skip, 7).unwrap()
            );
        }
        assert_ne!(
            spread_dates(40, start, end, (9, 18), false, 1).unwrap(),
            spread_dates(40, start, end, (9, 18), false, 2).unwrap()
        );
        // Window narrower than the hours, inside a single day.
        let tight = spread_dates(
            3,
            dt("2024-01-02 10:00:00"),
            dt("2024-01-02 10:00:03"),
            (0, 24),
            false,
            0,
        )
        .unwrap();
        assert_eq!(
            tight,
            [
                dt("2024-01-02 10:00:00"),
                dt("2024-01-02 10:00:01"),
                dt("2024-01-02 10:00:02")
            ]
        );
        assert!(spread_dates(
            4,
            dt("2024-01-02 10:00:00"),
            dt("2024-01-02 10:00:03"),
            (0, 24),
            false,
            0
        )
        .is_err());
        // A weekend-only window has no time when weekends are skipped.
        assert!(spread_dates(
            1,
            dt("2024-01-06 00:00:00"),
            dt("2024-01-08 00:00:00"),
            (9, 18),
            true,
            0
        )
        .is_err());
        assert!(spread_dates(1, end, start, (9, 18), false, 0).is_err());
        assert!(spread_dates(1, start, end, (18, 9), false, 0).is_err());
        assert!(spread_dates(0, start, end, (9, 18), false, 0)
            .unwrap()
            .is_empty());
    }

    fn dates(repo: &TempRepo) -> Vec<String> {
        repo.git(&["log", "--format=%at %ct"])
            .lines()
            .map(String::from)
            .collect()
    }

    #[test]
    fn redates_from_root() {
        let repo = TempRepo::new(3).with_remote();
        let old_tip = repo.git(&["rev-parse", "HEAD"]);
        let old_trees = repo.git(&["log", "--format=%T %B"]);
        let root = repo.git(&["rev-list", "--max-parents=0", "HEAD"]);
        let applied = repo.run(|| {
            let range = load_range(&root).unwrap();
            assert_eq!(range.commits.len(), 3);
            assert!(range.base.is_none());
            assert!(safety::is_published(&root).unwrap());
            let new = [
                Some(1_800_000_000),
                Some(1_800_000_100),
                Some(1_800_000_200),
            ];
            let old: Vec<(i64, i64)> = range
                .commits
                .iter()
                .map(|c| (c.author.0, c.committer.0))
                .collect();
            apply(&range, &plan_times(&old, &new, true)).unwrap()
        });
        assert_eq!(repo.git(&["rev-parse", "HEAD"]), applied.new_tip);
        assert_ne!(applied.new_tip, old_tip);
        assert_eq!(repo.git(&["log", "--format=%T %B"]), old_trees);
        assert_eq!(
            dates(&repo),
            [
                "1800000200 1800000200",
                "1800000100 1800000100",
                "1800000000 1800000000"
            ]
        );
        assert_eq!(repo.git(&["rev-list", "--count", "HEAD"]), "3");
        repo.git(&["fsck", "--no-dangling"]);
        assert!(applied.backup.starts_with("refs/gct/backup/"));
        assert_eq!(repo.git(&["rev-parse", &applied.backup]), old_tip);
        assert_eq!(repo.git(&["status", "--porcelain"]), "");
    }

    #[test]
    fn redates_suffix_keeps_older_commits() {
        let repo = TempRepo::new(3);
        let first = repo.git(&["rev-parse", "HEAD~2"]);
        let applied = repo.run(|| {
            let range = load_range("HEAD~1").unwrap();
            assert_eq!(range.commits.len(), 2);
            let old: Vec<(i64, i64)> = range
                .commits
                .iter()
                .map(|c| (c.author.0, c.committer.0))
                .collect();
            let new: Vec<Option<i64>> = old.iter().map(|o| Some(o.0 + 3600)).collect();
            apply(&range, &plan_times(&old, &new, false)).unwrap()
        });
        assert_eq!(repo.git(&["rev-parse", "HEAD~2"]), first);
        assert_eq!(repo.git(&["rev-parse", "HEAD"]), applied.new_tip);
        let base = 1_704_110_400;
        assert_eq!(
            dates(&repo),
            [
                format!("{} {}", base + 180 + 3600, base + 180),
                format!("{} {}", base + 120 + 3600, base + 120),
                format!("{} {}", base + 60, base + 60),
            ]
        );
    }

    #[test]
    fn refuses_merges_dirty_and_detached() {
        let repo = TempRepo::new(2);
        repo.git(&["checkout", "-q", "-b", "side"]);
        repo.write("side.txt", "s\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-q", "-m", "side"]);
        repo.git(&["checkout", "-q", "main"]);
        repo.write("main.txt", "m\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-q", "-m", "main"]);
        repo.git(&["merge", "-q", "--no-ff", "-m", "merge", "side"]);
        let err = repo.run(|| load_range("HEAD~1").unwrap_err().to_string());
        assert!(err.contains("merge"), "{err}");
        let err = repo.run(|| load_range("-x").unwrap_err().to_string());
        assert!(err.contains("not a commit"), "{err}");

        let repo = TempRepo::new(2);
        repo.write("f1.txt", "changed\n");
        let err = repo.run(|| load_range("HEAD").unwrap_err().to_string());
        assert!(err.contains("uncommitted"), "{err}");

        let repo = TempRepo::new(2);
        repo.git(&["checkout", "-q", "--detach"]);
        let err = repo.run(|| load_range("HEAD").unwrap_err().to_string());
        assert!(err.contains("detached"), "{err}");
    }

    #[test]
    fn cas_fails_safely_when_branch_moved() {
        let repo = TempRepo::new(3);
        let range = repo.run(|| load_range("HEAD~2").unwrap());
        repo.write("late.txt", "late\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-q", "-m", "late"]);
        let moved = repo.git(&["rev-parse", "HEAD"]);
        let old: Vec<(i64, i64)> = range
            .commits
            .iter()
            .map(|c| (c.author.0 + 5, c.committer.0))
            .collect();
        let err = repo.run(|| apply(&range, &old).unwrap_err().to_string());
        assert!(err.contains("moved"), "{err}");
        assert_eq!(repo.git(&["rev-parse", "HEAD"]), moved);
        assert_eq!(repo.git(&["log", "-1", "--format=%s"]), "late");
    }
}