git-loom 0.25.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
use crate::core::graph;
use crate::core::test_helpers::TestRepo;

/// Wrapper so existing tests don't need to pass integration/patch/theme.
fn run(branch: Option<String>, message: Option<String>, files: Vec<String>) -> anyhow::Result<()> {
    super::run(
        branch,
        false,
        message,
        None,
        files,
        vec![],
        &graph::Theme::dark(),
    )
}

/// Wrapper for `-i`: commit to the integration branch.
fn run_integration(message: &str, files: Vec<String>) -> anyhow::Result<()> {
    super::run(
        None,
        true,
        Some(message.to_string()),
        None,
        files,
        vec![],
        &graph::Theme::dark(),
    )
}

/// Helper: set up a test repo with an empty feature branch at the merge-base.
///
/// Creates:
///   origin/main → (merge-base) ← feature-a (empty, at merge-base)
///                              ← integration (HEAD)
fn setup_with_woven_branch() -> TestRepo {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feature-a at merge-base (no merge — it's empty)
    test_repo.create_branch_at("feature-a", &base_oid.to_string());

    test_repo
}

/// Helper: set up a test repo with two woven feature branches, each with a commit.
///
/// Creates:
///   origin/main → A1 (feature-a)
///              ↘              ↘
///               B1 --------→ merge₁ → merge₂ (HEAD on integration)
///               (feature-b)       ↗
fn setup_with_two_branches() -> TestRepo {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");
    test_repo.commit("A1", "a1.txt");
    test_repo.switch_branch("integration");

    test_repo.create_branch_at("feature-b", &base_oid.to_string());
    test_repo.switch_branch("feature-b");
    test_repo.commit("B1", "b1.txt");
    test_repo.switch_branch("integration");

    test_repo.merge_no_ff("feature-a");
    test_repo.merge_no_ff("feature-b");

    test_repo
}

// ── Staging resolution ───────────────────────────────────────────────────

#[test]
fn commit_stages_specific_file() {
    let test_repo = setup_with_woven_branch();

    test_repo.write_file("new.txt", "content");
    test_repo.write_file("other.txt", "other");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Add new file".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    assert_eq!(test_repo.branch_commit_summary("feature-a"), "Add new file");
}

#[test]
fn commit_stages_zz_all_changes() {
    let test_repo = setup_with_woven_branch();

    test_repo.write_file("file1.txt", "content1");
    test_repo.write_file("file2.txt", "content2");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Add files".to_string()),
            vec!["zz".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    assert_eq!(test_repo.branch_commit_summary("feature-a"), "Add files");
}

#[test]
fn commit_uses_already_staged() {
    let test_repo = setup_with_woven_branch();

    test_repo.write_file("staged.txt", "content");
    test_repo.stage_files(&["staged.txt"]);

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Use staged".to_string()),
            vec![], // no file args = use index as-is
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    assert_eq!(test_repo.branch_commit_summary("feature-a"), "Use staged");
}

#[test]
fn commit_empty_index_fails() {
    let test_repo = setup_with_woven_branch();

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Message".to_string()),
            vec![],
        )
    });

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Nothing to commit")
    );
}

// ── Branch resolution ────────────────────────────────────────────────────

#[test]
fn commit_to_non_woven_branch_fails() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("A1", "a1.txt");

    // Create a branch that tracks the same upstream as integration.
    // find_branches_in_range excludes such branches, so it won't be "woven".
    test_repo.create_branch_tracking("not-woven", "origin/main");

    test_repo.write_file("file.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("not-woven".to_string()),
            Some("Message".to_string()),
            vec!["file.txt".to_string()],
        )
    });

    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("not woven"));
}

/// The worst window: the commit is made, but the state file that would carry
/// the set-aside work is not written yet, so nothing else can return it —
/// `loom abort` has no rollback to read. A file where `.git/loom` must be a
/// directory is what makes `transaction::save` fail here — which also blocks
/// the last-resort patch dump the restore falls back on, so the one asserted
/// below is the real one, not the fallback.
#[test]
fn a_commit_failing_after_it_is_created_puts_back_the_staging() {
    let test_repo = setup_with_woven_branch();
    test_repo.write_file("kept.txt", "staged before the commit");
    test_repo.stage_files(&["kept.txt"]);
    test_repo.write_file("file.txt", "content");
    std::fs::write(test_repo.repo.path().join("loom"), "not a directory").unwrap();
    let before = test_repo.head_oid();

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Message".to_string()),
            vec!["file.txt".to_string()],
        )
    });

    assert!(result.is_err(), "the state file cannot be written");
    // Without this the test still passes if the failure ever moves earlier,
    // leaving the window it is named after unguarded.
    assert_ne!(
        test_repo.head_oid(),
        before,
        "the commit must already exist"
    );
    let status = test_repo.status_porcelain();
    assert!(status.contains("A  kept.txt"), "{status}");
}

/// A failure between staging and the commit puts the set-aside work back too:
/// which files were staged is state git keeps no second copy of.
#[test]
fn a_failed_commit_puts_back_the_staging_it_set_aside() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("A1", "a1.txt");
    test_repo.create_branch_tracking("not-woven", "origin/main");

    test_repo.write_file("kept.txt", "staged before the commit");
    test_repo.stage_files(&["kept.txt"]);
    test_repo.write_file("file.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("not-woven".to_string()),
            Some("Message".to_string()),
            vec!["file.txt".to_string()],
        )
    });

    assert!(result.is_err());
    let status = test_repo.status_porcelain();
    assert!(status.contains("A  kept.txt"), "{status}");
}

#[test]
fn commit_to_new_branch_creates_and_weaves() {
    let test_repo = TestRepo::new_with_remote();

    test_repo.write_file("new.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-new".to_string()),
            Some("Add file".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);
    assert!(test_repo.branch_exists("feature-new"));

    assert_eq!(test_repo.branch_commit_summary("feature-new"), "Add file");

    // Integration HEAD should be a merge commit (proper weave topology)
    let head = test_repo.head_commit();
    assert_eq!(
        head.parent_count(),
        2,
        "HEAD should be a merge commit with 2 parents"
    );

    // The branch commit should be reachable as the second parent of the merge
    let second_parent = head.parent(1).unwrap();
    assert_eq!(second_parent.summary().unwrap().unwrap(), "Add file");
}

// ── Merge topology ──────────────────────────────────────────────────────

#[test]
fn commit_to_empty_branch_creates_merge_topology() {
    let test_repo = setup_with_woven_branch();

    test_repo.write_file("new.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("New commit".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    let branch_oid = test_repo.get_branch_target("feature-a");
    let commit = test_repo.find_commit(branch_oid);
    assert_eq!(commit.summary().unwrap().unwrap(), "New commit");

    // Integration HEAD should be a merge commit (not the same as feature-a)
    let head = test_repo.head_commit();
    assert_eq!(
        head.parent_count(),
        2,
        "HEAD should be a merge commit (branch woven into integration)"
    );

    // feature-a's commit should be the second parent of the merge
    let second_parent = head.parent(1).unwrap();
    assert_eq!(second_parent.id(), branch_oid);
}

/// Helper: set up a test repo with one woven branch (with a commit) and one empty branch.
///
/// Creates:
///   origin/main → (merge-base)
///   feature-a has A1 commit, merged into integration
///   feature-b at merge-base (empty)
///   HEAD = integration = Merge feature-a
fn setup_with_one_woven_one_empty() -> TestRepo {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");
    test_repo.commit("A1", "a1.txt");
    test_repo.switch_branch("integration");

    test_repo.merge_no_ff("feature-a");

    // Create feature-b at merge-base (empty, no commits)
    test_repo.create_branch_at("feature-b", &base_oid.to_string());

    test_repo
}

#[test]
fn commit_to_second_empty_branch_creates_parallel_topology() {
    let test_repo = setup_with_one_woven_one_empty();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.write_file("b1.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-b".to_string()),
            Some("B1".to_string()),
            vec!["b1.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    let branch_b_oid = test_repo.get_branch_target("feature-b");
    let commit_b = test_repo.find_commit(branch_b_oid);
    assert_eq!(commit_b.summary().unwrap().unwrap(), "B1");

    // feature-b's commit should have the merge-base as its parent,
    // NOT the merge commit of feature-a (parallel topology, not stacked)
    let parent = commit_b.parent(0).unwrap();
    assert_eq!(
        parent.id(),
        base_oid,
        "feature-b's commit should fork from merge-base, not from the merge commit"
    );

    // HEAD should be a merge commit (merge of feature-b into integration)
    let head = test_repo.head_commit();
    assert_eq!(head.parent_count(), 2, "HEAD should be a merge commit");

    // The first parent should be the merge of feature-a (the old integration tip)
    let first_parent = head.parent(0).unwrap();
    assert_eq!(
        first_parent.parent_count(),
        2,
        "first parent should also be a merge commit (feature-a merge)"
    );

    // The second parent should be feature-b
    let second_parent = head.parent(1).unwrap();
    assert_eq!(second_parent.id(), branch_b_oid);
}

// ── Move via rebase ──────────────────────────────────────────────────────

#[test]
fn commit_moves_to_correct_branch_in_topology() {
    let test_repo = setup_with_two_branches();

    test_repo.write_file("new.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("New on A".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    let branch_oid = test_repo.get_branch_target("feature-a");
    let commit = test_repo.find_commit(branch_oid);
    assert_eq!(commit.summary().unwrap().unwrap(), "New on A");

    // Its parent should be A1
    let parent = commit.parent(0).unwrap();
    assert_eq!(parent.summary().unwrap().unwrap(), "A1");

    assert_eq!(test_repo.branch_commit_summary("feature-b"), "B1");
}

/// The target is a branch stacked inside another: the commit becomes its tip
/// and the outer branch is replayed on top of it.
#[test]
fn commit_to_inner_branch_lands_at_its_tip() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.create_branch_at("inner", &base_oid.to_string());
    test_repo.switch_branch("inner");
    let i1_oid = test_repo.commit("I1", "i1.txt");
    test_repo.create_branch_at("outer", &i1_oid.to_string());
    test_repo.switch_branch("outer");
    test_repo.commit("O1", "o1.txt");
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("outer");

    test_repo.write_file("new.txt", "content");
    let result = test_repo.in_dir(|| {
        run(
            Some("inner".to_string()),
            Some("New on inner".to_string()),
            vec!["new.txt".to_string()],
        )
    });
    assert!(result.is_ok(), "commit failed: {:?}", result);

    let inner = test_repo.find_commit(test_repo.get_branch_target("inner"));
    assert_eq!(inner.summary().unwrap().unwrap(), "New on inner");
    assert_eq!(inner.parent_id(0).unwrap(), i1_oid);
    let outer = test_repo.find_commit(test_repo.get_branch_target("outer"));
    assert_eq!(outer.summary().unwrap().unwrap(), "O1");
    assert_eq!(outer.parent_id(0).unwrap(), inner.id());
}

/// Bug: committing to a new branch when the file conflicts with an existing
/// woven branch would lose working-tree changes. Now that conflicts pause the
/// operation instead of aborting, the operation is kept alive for `loom continue`
/// or `loom abort`.
#[test]
fn commit_conflict_pauses_operation() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.create_branch_at("feat1", &base_oid.to_string());
    test_repo.switch_branch("feat1");
    test_repo.write_file("feature1", "feat 1 content");
    test_repo.stage_files(&["feature1"]);
    test_repo.commit_staged("Feature 1");
    test_repo.switch_branch("integration");

    test_repo.merge_no_ff("feat1");

    // Modify feature1 in the working tree (same file as feat1 commit)
    test_repo.write_file("feature1", "conflicting content");

    let result = test_repo.in_dir(|| {
        run(
            Some("new-line".to_string()),
            Some("New line".to_string()),
            vec!["zz".to_string()],
        )
    });

    // The commit should succeed (operation paused, not aborted)
    assert!(result.is_ok(), "commit should pause on conflict, not fail");

    // The state file should exist indicating a paused operation
    let state_path = test_repo.repo.path().join("loom").join("state.json");
    assert!(
        state_path.exists(),
        "loom state file should exist when paused"
    );

    // The new branch should still exist (kept for potential abort)
    assert!(
        test_repo.branch_exists("new-line"),
        "new-line branch should be kept while operation is paused"
    );
}

#[test]
fn commit_conflict_preserves_existing_empty_branch() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.create_branch_at("feat1", &base_oid.to_string());
    test_repo.switch_branch("feat1");
    test_repo.write_file("shared.txt", "feat1 content");
    test_repo.stage_files(&["shared.txt"]);
    test_repo.commit_staged("Feature 1");
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("feat1");

    // Create an empty branch at merge-base (pre-existing, not created by commit)
    test_repo.create_branch_at("empty-branch", &base_oid.to_string());

    // Stage a conflicting change and try to commit to the empty branch
    test_repo.write_file("shared.txt", "conflicting content");

    let result = test_repo.in_dir(|| {
        run(
            Some("empty-branch".to_string()),
            Some("Should conflict".to_string()),
            vec!["zz".to_string()],
        )
    });

    // The commit should pause (not abort) on conflict
    assert!(result.is_ok(), "commit should pause on conflict, not fail");

    let state_path = test_repo.repo.path().join("loom").join("state.json");
    assert!(
        state_path.exists(),
        "loom state file should exist when paused"
    );

    // Critical: the pre-existing empty branch must NOT be deleted while paused
    assert!(
        test_repo.branch_exists("empty-branch"),
        "Pre-existing empty branch should be preserved while operation is paused"
    );
}

// ── Loose commits ────────────────────────────────────────────────────────

#[test]
fn commit_loose_when_no_branch_and_at_remote() {
    // When no -b flag and branch name matches the upstream's local name
    // (e.g. "main" tracking "origin/main"), the commit should land
    // directly on the integration branch (loose).
    let test_repo = TestRepo::new_on_main_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.write_file("loose.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            None, // no -b flag
            Some("Loose commit".to_string()),
            vec!["loose.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "loose commit failed: {:?}", result);

    // HEAD should be a regular (non-merge) commit
    let head = test_repo.head_commit();
    assert_eq!(head.parent_count(), 1, "Loose commit should have 1 parent");
    assert_eq!(head.summary().unwrap().unwrap(), "Loose commit");

    // Parent should be the merge-base (the remote tip)
    let parent = head.parent(0).unwrap();
    assert_eq!(parent.id(), base_oid);
}

#[test]
fn commit_loose_works_with_existing_local_commits() {
    // Loose commits should work even when local commits already exist
    // on the integration branch (HEAD != merge-base).
    let test_repo = TestRepo::new_on_main_with_remote();

    // Create a first loose commit so HEAD diverges from merge-base
    test_repo.write_file("first.txt", "first");
    test_repo
        .in_dir(|| {
            run(
                None,
                Some("First loose commit".to_string()),
                vec!["first.txt".to_string()],
            )
        })
        .unwrap();

    // Now create a second loose commit — should still work
    test_repo.write_file("second.txt", "second");
    let result = test_repo.in_dir(|| {
        run(
            None,
            Some("Second loose commit".to_string()),
            vec!["second.txt".to_string()],
        )
    });

    assert!(
        result.is_ok(),
        "loose commit with existing local commits failed: {:?}",
        result
    );

    let head = test_repo.head_commit();
    assert_eq!(head.summary().unwrap().unwrap(), "Second loose commit");
    assert_eq!(head.parent_count(), 1);
    assert_eq!(
        head.parent(0).unwrap().summary().unwrap().unwrap(),
        "First loose commit"
    );
}

#[test]
fn commit_with_branch_flag_does_not_create_loose() {
    // When -b is provided, even if HEAD == merge-base, a branch-targeted
    // commit should be created (not loose).
    let test_repo = TestRepo::new_with_remote();

    test_repo.write_file("file.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-new".to_string()), // explicit -b flag
            Some("Branch commit".to_string()),
            vec!["file.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    // Should have created the branch and woven it
    assert!(test_repo.branch_exists("feature-new"));
    let head = test_repo.head_commit();
    assert_eq!(
        head.parent_count(),
        2,
        "HEAD should be a merge commit (branch woven)"
    );
}

#[test]
fn commit_integration_flag_forces_loose_on_custom_named_branch() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.write_file("loose.txt", "content");

    let result =
        test_repo.in_dir(|| run_integration("Loose commit", vec!["loose.txt".to_string()]));

    assert!(result.is_ok(), "loose commit failed: {:?}", result);

    let head = test_repo.head_commit();
    assert_eq!(head.parent_count(), 1, "Loose commit should have 1 parent");
    assert_eq!(head.summary().unwrap().unwrap(), "Loose commit");
    assert_eq!(head.parent(0).unwrap().id(), base_oid);
}

#[test]
fn commit_integration_flag_commits_on_top_of_merges() {
    let test_repo = setup_with_two_branches();
    let old_head = test_repo.head_commit().id();

    test_repo.write_file("loose.txt", "content");

    let result =
        test_repo.in_dir(|| run_integration("Loose commit", vec!["loose.txt".to_string()]));

    assert!(result.is_ok(), "loose commit failed: {:?}", result);

    let head = test_repo.head_commit();
    assert_eq!(head.summary().unwrap().unwrap(), "Loose commit");
    assert_eq!(head.parent_count(), 1);
    assert_eq!(head.parent(0).unwrap().id(), old_head);

    assert_eq!(test_repo.branch_commit_summary("feature-a"), "A1");
    assert_eq!(test_repo.branch_commit_summary("feature-b"), "B1");
}

#[test]
fn commit_integration_flag_keeps_other_staged_files_staged() {
    let test_repo = TestRepo::new_with_remote();

    test_repo.write_file("other.txt", "other content");
    test_repo.stage_files(&["other.txt"]);
    test_repo.write_file("mine.txt", "mine content");

    let result = test_repo.in_dir(|| run_integration("Only mine", vec!["mine.txt".to_string()]));
    assert!(result.is_ok(), "loose commit failed: {:?}", result);

    assert_eq!(
        test_repo.commit_file_paths(test_repo.head_commit().id()),
        vec!["mine.txt"]
    );

    let status = test_repo.status_porcelain();
    assert!(
        status.lines().any(|l| l == "A  other.txt"),
        "other.txt must still be staged, got: {status:?}"
    );
    assert_eq!(test_repo.read_file("other.txt"), "other content");
}

#[test]
fn commit_not_on_integration_branch_fails() {
    let test_repo = TestRepo::new();
    test_repo.commit("A1", "a1.txt");
    test_repo.write_file("new.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Message".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("integration branch")
    );
}

#[test]
fn commit_nonexistent_file_fails() {
    let test_repo = setup_with_woven_branch();

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Message".to_string()),
            vec!["nonexistent.txt".to_string()],
        )
    });

    assert!(result.is_err());
    assert!(
        result.unwrap_err().to_string().contains("file"),
        "Error should mention file"
    );
}

#[test]
fn commit_accepts_staged_rename_only() {
    let test_repo = setup_with_woven_branch();

    test_repo.write_file("original.txt", "content");
    test_repo.stage_files(&["original.txt"]);
    test_repo.commit_staged("Add original");

    let workdir = test_repo.workdir();
    std::process::Command::new("git")
        .current_dir(&workdir)
        .args(["mv", "original.txt", "renamed.txt"])
        .output()
        .unwrap();

    let result = crate::core::repo::verify_has_staged_changes(&test_repo.repo);
    assert!(
        result.is_ok(),
        "staged rename should be accepted, got: {:?}",
        result.err()
    );
}

/// Regression: loom abort after a commit conflict must preserve staged changes
/// on other files, unstaged changes, and new untracked files.
///
/// Conflict setup: feat1 branch commits `shared.txt`; we then try to commit
/// `shared.txt` to a new branch — the weave rebase conflicts because both
/// branches touch the same file.
#[test]
fn commit_abort_preserves_working_state() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.create_branch_at("feat1", &base_oid.to_string());
    test_repo.switch_branch("feat1");
    test_repo.commit("feat1-content", "shared.txt");

    test_repo.switch_branch("integration");
    test_repo.commit("int", "int.txt"); // prevent fast-forward
    test_repo.merge_no_ff("feat1");

    test_repo.write_file("other-staged.txt", "staged-content");
    test_repo.stage_files(&["other-staged.txt"]);
    test_repo.write_file("other-unstaged.txt", "unstaged-content");
    test_repo.write_file("new-file.txt", "new-content");

    test_repo.write_file("shared.txt", "conflicting-write");

    let result = test_repo.in_dir(|| {
        run(
            Some("new-line".to_string()),
            Some("New line".to_string()),
            vec!["shared.txt".to_string()],
        )
    });
    assert!(
        result.is_ok(),
        "commit should pause on conflict: {:?}",
        result
    );

    let state_path = test_repo.repo.path().join("loom").join("state.json");
    assert!(
        state_path.exists(),
        "loom state must exist when commit is paused on conflict"
    );

    let workdir = test_repo.workdir();
    let git_dir = test_repo.repo.path().to_path_buf();
    crate::core::transaction::abort_cmd(&workdir, &git_dir).unwrap();

    assert_eq!(test_repo.read_file("shared.txt"), "conflicting-write");
    assert_eq!(test_repo.read_file("other-staged.txt"), "staged-content");
    assert_eq!(
        test_repo.read_file("other-unstaged.txt"),
        "unstaged-content"
    );
    assert!(
        workdir.join("new-file.txt").exists(),
        "new untracked file must survive abort"
    );
    assert_eq!(test_repo.read_file("new-file.txt"), "new-content");
}

#[test]
fn commit_forwards_an_option_after_the_separator() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.write_file("forwarded.txt", "content");

    let result = test_repo.in_dir(|| {
        super::run(
            None,
            true,
            Some("Forwarded commit".to_string()),
            None,
            vec!["forwarded.txt".to_string()],
            vec!["--author=Someone Else <someone@example.com>".to_string()],
            &graph::Theme::dark(),
        )
    });
    assert!(result.is_ok(), "commit should forward --author: {result:?}");

    let head = test_repo.repo.head().unwrap().peel_to_commit().unwrap();
    assert_eq!(head.author().name().unwrap(), "Someone Else");
}

#[test]
fn commit_unknown_option_reaches_git() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.write_file("bogus.txt", "content");

    let result = test_repo.in_dir(|| {
        super::run(
            None,
            true,
            Some("Bogus commit".to_string()),
            None,
            vec!["bogus.txt".to_string()],
            vec!["--definitely-not-a-git-option".to_string()],
            &graph::Theme::dark(),
        )
    });
    assert!(
        result.is_err(),
        "git should reject an option loom passed through"
    );
}

#[test]
fn commit_refuses_when_the_new_commit_replays_empty() {
    // The branch section resets to the weave base, so a change the base
    // already has replays empty there. Dropped, the branch ref would never
    // move and `post_commit` would name the tip it was appended to.
    let test_repo = TestRepo::new_with_remote();
    let base = test_repo
        .find_remote_branch_target("origin/main")
        .to_string();

    test_repo.create_branch_at("upstream-work", &base);
    test_repo.switch_branch("upstream-work");
    test_repo.commit_multi(&[("f.txt", "final\n")], "upstream adds f");
    test_repo.push_branch_to_remote_main("upstream-work");

    test_repo.switch_branch("integration");
    test_repo.reset_hard(test_repo.find_remote_branch_target("origin/main"));
    test_repo.commit_multi(&[("f.txt", "old\n")], "revert f");
    let head_before = test_repo.head_oid();

    // Putting `f.txt` back is new at HEAD but is what the base already holds.
    test_repo.write_file("f.txt", "final\n");

    let err = test_repo
        .in_dir(|| {
            run(
                Some("feature-a".to_string()),
                Some("Restore f".to_string()),
                vec!["f.txt".to_string()],
            )
        })
        .unwrap_err()
        .to_string();

    assert!(err.contains("is redundant"), "{err}");
    assert!(
        !err.contains("loom drop"),
        "the rollback takes the commit with it: {err}"
    );
    assert!(err.contains("rolled back"), "{err}");
    assert_eq!(test_repo.head_oid(), head_before, "{err}");
    assert!(!test_repo.branch_exists("feature-a"), "{err}");
    assert_eq!(test_repo.read_file("f.txt"), "final\n", "{err}");
    assert!(
        !crate::git::rebase_is_in_progress(test_repo.repo.path()),
        "{err}"
    );
    assert!(
        !test_repo
            .repo
            .path()
            .join("loom")
            .join("state.json")
            .exists(),
        "{err}"
    );
}

#[test]
fn commit_refuses_with_no_file_arguments_too() {
    // Without file arguments nothing is saved aside, so the rollback is the
    // `reset --mixed` alone — the changes come back, unstaged.
    let test_repo = TestRepo::new_with_remote();
    let base = test_repo
        .find_remote_branch_target("origin/main")
        .to_string();

    test_repo.create_branch_at("upstream-work", &base);
    test_repo.switch_branch("upstream-work");
    test_repo.commit_multi(&[("f.txt", "final\n")], "upstream adds f");
    test_repo.push_branch_to_remote_main("upstream-work");

    test_repo.switch_branch("integration");
    test_repo.reset_hard(test_repo.find_remote_branch_target("origin/main"));
    test_repo.commit_multi(&[("f.txt", "old\n")], "revert f");
    let head_before = test_repo.head_oid();

    test_repo.write_file("f.txt", "final\n");
    test_repo.stage_files(&["f.txt"]);
    let staged_before = crate::git::diff_cached(&test_repo.workdir()).unwrap();

    let err = test_repo
        .in_dir(|| {
            run(
                Some("feature-a".to_string()),
                Some("Restore f".to_string()),
                vec![],
            )
        })
        .unwrap_err()
        .to_string();

    assert!(err.contains("is redundant"), "{err}");
    assert!(!err.contains("loom drop"), "{err}");
    assert_eq!(test_repo.head_oid(), head_before, "{err}");
    assert_eq!(test_repo.read_file("f.txt"), "final\n", "{err}");
    assert!(!test_repo.branch_exists("feature-a"), "{err}");
    assert_eq!(
        crate::git::diff_cached(&test_repo.workdir()).unwrap(),
        staged_before,
        "the index must come back staged, not just the content: {err}"
    );
}

/// A `loom commit` paused by an older binary stored the set-aside patch in the
/// rollback; the resume must still find it there.
#[test]
fn after_continue_reads_a_state_file_without_the_saved_staged_field() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit_multi(&[("kept.txt", "kept\n")], "base");
    test_repo.write_file("kept.txt", "kept\nset aside\n");
    test_repo.stage_files(&["kept.txt"]);
    let aside = crate::git::diff_cached(&test_repo.workdir()).unwrap();
    crate::git::run_git(&test_repo.workdir(), &["restore", "--staged", "."]).unwrap();

    let rollback = crate::core::transaction::Rollback {
        saved_staged_patch: aside.clone(),
        ..Default::default()
    };
    test_repo.create_branch("feature-a");
    let context = serde_json::json!({ "branch_name": "feature-a" });

    super::after_continue(&test_repo.workdir(), &rollback, &context).unwrap();

    assert_eq!(
        crate::git::diff_cached(&test_repo.workdir()).unwrap(),
        aside
    );
}

// ── Change-Id ────────────────────────────────────────────────────────────

const CHANGE_ID: &str = "I0123456789abcdef0123456789abcdef01234567";

fn full_message(test_repo: &TestRepo, rev: &str) -> String {
    test_repo
        .repo
        .revparse_single(rev)
        .unwrap()
        .peel_to_commit()
        .unwrap()
        .message()
        .unwrap()
        .to_string()
}

/// A `commit-msg` hook that adds its own Change-Id when the message has none,
/// as Gerrit's does.
fn write_gerrit_like_hook(test_repo: &TestRepo) {
    write_hook(
        test_repo,
        "commit-msg",
        "grep -q '^Change-Id:' \"$1\" || printf '\\nChange-Id: I%s\\n' \
         0000000000000000000000000000000000000000 >> \"$1\"",
    );
}

fn write_hook(test_repo: &TestRepo, name: &str, body: &str) {
    write_script(test_repo, &format!(".git/hooks/{name}"), body);
}

/// A `sh` script under the workdir; returns its path, slashes forward so git
/// config accepts it on Windows too.
fn write_script(test_repo: &TestRepo, relative: &str, body: &str) -> String {
    let script = test_repo.workdir().join(relative);
    std::fs::create_dir_all(script.parent().unwrap()).unwrap();
    std::fs::write(&script, format!("#!/bin/sh\n{body}\nexit 0\n")).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    script.display().to_string().replace('\\', "/")
}

/// A `commit-msg` hook that logs every run to `runs` in the workdir.
fn write_counting_hook(test_repo: &TestRepo) {
    let log = test_repo
        .workdir()
        .join("runs")
        .display()
        .to_string()
        .replace('\\', "/");
    write_hook(test_repo, "commit-msg", &format!("echo run >> \"{log}\""));
}

#[test]
fn commit_adds_a_change_id_trailer() {
    let test_repo = setup_with_woven_branch();
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Add a".to_string()),
            vec!["a.txt".to_string()],
        )
    });
    assert!(result.is_ok(), "{result:?}");

    let msg = full_message(&test_repo, "feature-a");
    assert!(msg.starts_with("Add a\n\nChange-Id: I"), "{msg}");
    assert!(crate::core::changeid::from_message(&msg).is_some());
}

#[test]
fn commit_respects_the_change_id_opt_out() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.set_config("loom.changeId", "false");
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| run_integration("Plain", vec!["a.txt".to_string()]));
    assert!(result.is_ok(), "{result:?}");

    assert_eq!(full_message(&test_repo, "HEAD"), "Plain\n");
}

#[test]
fn commit_keeps_a_change_id_already_in_the_message() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.write_file("a.txt", "a");
    let message = format!("Has one\n\nChange-Id: {CHANGE_ID}");

    let result = test_repo.in_dir(|| run_integration(&message, vec!["a.txt".to_string()]));
    assert!(result.is_ok(), "{result:?}");

    let msg = full_message(&test_repo, "HEAD");
    assert_eq!(msg.matches("Change-Id:").count(), 1, "{msg}");
    assert!(msg.contains(CHANGE_ID));
}

#[test]
fn commit_editor_path_gets_a_change_id_after_editing() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.set_fake_editor("Reworded by editor");
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| {
        super::run(
            None,
            true,
            None,
            None,
            vec!["a.txt".to_string()],
            vec![],
            &graph::Theme::dark(),
        )
    });
    assert!(result.is_ok(), "{result:?}");

    let msg = full_message(&test_repo, "HEAD");
    assert!(
        msg.starts_with("Reworded by editor\n\nChange-Id: I"),
        "{msg}"
    );
    assert_eq!(
        test_repo.commit_file_paths(test_repo.head_oid()),
        vec!["a.txt"]
    );
}

/// The amend that adds the trailer after the editor runs no hooks: they
/// already ran on the commit the user made.
#[test]
fn commit_editor_path_runs_hooks_once() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.set_fake_editor("Reworded by editor");
    write_counting_hook(&test_repo);
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| {
        super::run(
            None,
            true,
            None,
            None,
            vec!["a.txt".to_string()],
            vec![],
            &graph::Theme::dark(),
        )
    });
    assert!(result.is_ok(), "{result:?}");

    let runs = std::fs::read_to_string(test_repo.workdir().join("runs")).unwrap();
    assert_eq!(runs.lines().count(), 1, "{runs}");
    assert!(full_message(&test_repo, "HEAD").contains("Change-Id: I"));
}

/// The trailer amend failing must not turn a commit that exists into an error
/// and leave it stranded on the integration branch.
#[test]
fn commit_editor_path_survives_a_failing_trailer_amend() {
    let test_repo = setup_with_woven_branch();
    test_repo.set_fake_editor("Reworded by editor");
    // Only the amend carries the trailer; the editor commit and the weave's
    // picks pass.
    write_hook(
        &test_repo,
        "prepare-commit-msg",
        "grep -q Change-Id \"$1\" && exit 1",
    );
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            None,
            vec!["a.txt".to_string()],
        )
    });
    assert!(result.is_ok(), "{result:?}");

    assert_eq!(
        test_repo.branch_commit_summary("feature-a"),
        "Reworded by editor"
    );
    assert!(!full_message(&test_repo, "feature-a").contains("Change-Id"));
}

/// The trailer amend builds a new object, so it must still honor the signing
/// config. A fake gpg that git accepts stands in for a key.
#[test]
fn commit_editor_path_keeps_a_configured_signature() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.set_fake_editor("Reworded by editor");
    let gpg = write_script(
        &test_repo,
        ".git/fake-gpg",
        "printf '\\n[GNUPG:] SIG_CREATED D 1 8 00 1 X\\n' >&2\n\
         printf -- '-----BEGIN PGP SIGNATURE-----\\n\\nfake\\n-----END PGP SIGNATURE-----\\n'",
    );
    test_repo.set_config("gpg.program", &gpg);
    test_repo.set_config("user.signingkey", "fake");
    test_repo.set_config("commit.gpgsign", "true");
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| {
        super::run(
            None,
            true,
            None,
            None,
            vec!["a.txt".to_string()],
            vec![],
            &graph::Theme::dark(),
        )
    });
    assert!(result.is_ok(), "{result:?}");

    let head = test_repo.head_commit();
    assert!(head.raw_header().unwrap().contains("gpgsig"));
    assert!(full_message(&test_repo, "HEAD").contains("Change-Id: I"));
}

/// The trailer amend appends to the stored message as is: a `#` line the
/// user's forwarded `--cleanup=verbatim` kept must not fall to `commit.cleanup`.
#[test]
fn commit_editor_path_amend_keeps_the_stored_message_verbatim() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.set_config("commit.cleanup", "strip");
    test_repo.set_fake_editor("Reworded by editor\n\n# kept");
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| {
        super::run(
            None,
            true,
            None,
            None,
            vec!["a.txt".to_string()],
            vec!["--cleanup=verbatim".to_string()],
            &graph::Theme::dark(),
        )
    });
    assert!(result.is_ok(), "{result:?}");

    let msg = full_message(&test_repo, "HEAD");
    assert!(
        msg.starts_with("Reworded by editor\n\n# kept\n\nChange-Id: I"),
        "{msg}"
    );
}

#[test]
fn commit_msg_hook_sees_looms_change_id() {
    let test_repo = TestRepo::new_with_remote();
    write_gerrit_like_hook(&test_repo);
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| run_integration("Hooked", vec!["a.txt".to_string()]));
    assert!(result.is_ok(), "{result:?}");

    let msg = full_message(&test_repo, "HEAD");
    assert_eq!(msg.matches("Change-Id:").count(), 1, "{msg}");
    assert!(
        !msg.contains("I0000000000"),
        "the hook id must not win: {msg}"
    );
}

#[test]
fn commit_no_verify_still_adds_a_change_id() {
    let test_repo = TestRepo::new_with_remote();
    write_gerrit_like_hook(&test_repo);
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| {
        super::run(
            None,
            true,
            Some("Unverified".to_string()),
            None,
            vec!["a.txt".to_string()],
            vec!["--no-verify".to_string()],
            &graph::Theme::dark(),
        )
    });
    assert!(result.is_ok(), "{result:?}");

    let msg = full_message(&test_repo, "HEAD");
    assert!(msg.starts_with("Unverified\n\nChange-Id: I"), "{msg}");
}

/// Stamping runs before anything is set aside, so its failure cannot leave
/// the user's other staged files unstaged.
#[test]
fn commit_restores_other_staged_files_when_the_change_id_cannot_be_generated() {
    let test_repo = TestRepo::new_with_remote();
    // SAFETY: removals only, so concurrent tests cannot disagree, and every
    // fixture sets its identity in repo config. An exported one would
    // otherwise satisfy `git var`.
    unsafe {
        for var in ["GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "EMAIL"] {
            std::env::remove_var(var);
        }
    }
    test_repo.set_config("user.useConfigOnly", "true");
    test_repo.set_config("user.name", "");
    test_repo.set_config("user.email", "");
    test_repo.write_file("other.txt", "other");
    test_repo.stage_files(&["other.txt"]);
    test_repo.write_file("mine.txt", "mine");

    let result = test_repo.in_dir(|| run_integration("Nobody", vec!["mine.txt".to_string()]));
    let err = result.unwrap_err().to_string();
    assert!(err.contains("committer identity"), "{err}");

    let status = test_repo.status_porcelain();
    assert!(
        status.lines().any(|l| l == "A  other.txt"),
        "other.txt must still be staged, got: {status:?}"
    );
}

/// Loom writes the trailer into the message itself, so `trailer.*` config
/// cannot rename, move, or suppress it.
#[test]
fn commit_ignores_trailer_config() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.set_config("trailer.Change-Id.key", "Nope");
    test_repo.set_config("trailer.ifexists", "doNothing");
    test_repo.set_config("trailer.where", "start");
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| run_integration("Configured", vec!["a.txt".to_string()]));
    assert!(result.is_ok(), "{result:?}");

    let msg = full_message(&test_repo, "HEAD");
    assert!(msg.starts_with("Configured\n\nChange-Id: I"), "{msg}");
    assert_eq!(msg.lines().count(), 3, "{msg}");
    assert!(crate::core::changeid::from_message(&msg).is_some(), "{msg}");
}

/// A forwarded option that creates no commit leaves HEAD alone: the
/// editor-path stamping must never amend a commit loom did not create.
#[test]
fn commit_dry_run_does_not_amend_head() {
    let test_repo = TestRepo::new_with_remote();
    let head = test_repo.head_oid();
    test_repo.write_file("a.txt", "a");

    let result = test_repo.in_dir(|| {
        super::run(
            None,
            true,
            None,
            None,
            vec!["a.txt".to_string()],
            vec!["--dry-run".to_string()],
            &graph::Theme::dark(),
        )
    });
    assert!(result.is_ok(), "{result:?}");

    assert_eq!(test_repo.head_oid(), head);
    assert!(!full_message(&test_repo, "HEAD").contains("Change-Id"));
}

/// A rebase that refuses to start — the target branch is checked out in another
/// worktree — still has `commit`'s own commit to take back: it was made before
/// the rebase existed, and the state file that holds the undo is deleted here,
/// so nothing later can. Guards the commit being stranded on integration with
/// the user's staging left behind it.
#[test]
fn commit_rolls_back_when_the_rebase_refuses_to_start() {
    let test_repo = setup_with_two_branches();
    let workdir = test_repo.workdir();

    let wt = workdir.parent().unwrap().join("wt");
    crate::git::run_git(
        &workdir,
        &["worktree", "add", wt.to_str().unwrap(), "feature-a"],
    )
    .unwrap();

    let head_before = test_repo.head_oid();
    test_repo.write_file(
        "other.txt",
        "staged by the user
",
    );
    test_repo.stage_files(&["other.txt"]);
    let staged_before = crate::git::diff_cached(&workdir).unwrap();
    test_repo.write_file(
        "new.txt",
        "for the commit
",
    );

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Add new file".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(
        result.is_err(),
        "the rebase cannot start, so the commit fails"
    );
    assert_eq!(
        test_repo.head_oid(),
        head_before,
        "the commit must not be left on integration"
    );
    assert_eq!(
        crate::git::diff_cached(&workdir).unwrap(),
        staged_before,
        "the user's own staging comes back exactly as it was"
    );
    assert_eq!(
        test_repo.read_file("new.txt"),
        "for the commit\n",
        "the content loom committed comes back to the working tree"
    );
    assert!(
        !test_repo.repo.path().join("loom/state.json").exists(),
        "the state file goes with the rollback"
    );
}