jj-cli 0.44.0

Jujutsu - an experimental version control system
Documentation
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
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
// Copyright 2024 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use std::fs;

use insta::assert_snapshot;

use crate::common::TestEnvironment;
use crate::common::TestWorkDir;
use crate::common::create_commit_with_files;

#[test]
fn test_run_simple() {
    let mut test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    test_env.add_paths_to_normalize(fake_formatter.clone(), "$FAKE_FORMATTER_PATH");
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    work_dir.write_file("c.txt", "test to replace");
    work_dir.run_jj(&["commit", "-m", "C"]).success();
    insta::assert_snapshot!(get_log_output(&work_dir), @r"
    @  zsuskulnrvyrovkzqrwmxqlsskqntxvp
    ○  kkmpptxzrspxrzommnulwmwkkqwworplC
    │
    ○  rlvkpnrzqnoowoytxnquwvuryrwnrmlpB
    │
    ○  qpvuntsmwlqtpsluzzsnyyzlmlwvmlnuA
    │
    ◆  zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    [EOF]
    ");
    // `--tee touched.txt` creates a file in each working copy, so every commit's
    // tree gets rewritten.
    let stdout = work_dir
        .run_jj(&[
            "run",
            "-r",
            "..@",
            "--",
            &fake_formatter_path,
            "--stdout",
            "x",
            "--tee",
            "touched.txt",
        ])
        .success()
        .stdout;
    insta::assert_snapshot!(stdout, @"xxxx[EOF]");
}

#[test]
fn test_run_on_immutable() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy();
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    work_dir.write_file("c.txt", "test to replace");
    work_dir.run_jj(&["commit", "-m", "C"]).success();
    insta::assert_snapshot!(get_log_output(&work_dir), @r"
    @  zsuskulnrvyrovkzqrwmxqlsskqntxvp
    ○  kkmpptxzrspxrzommnulwmwkkqwworplC
    │
    ○  rlvkpnrzqnoowoytxnquwvuryrwnrmlpB
    │
    ○  qpvuntsmwlqtpsluzzsnyyzlmlwvmlnuA
    │
    ◆  zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    [EOF]
    ");
    let output = work_dir.run_jj(&[
        "run",
        "-r",
        "all()",
        "--",
        &fake_formatter_path,
        "--uppercase",
    ]);
    insta::assert_snapshot!(output, @r"
    ------- stderr -------
    Error: The root commit 000000000000 is immutable
    [EOF]
    [exit status: 1]
    ");
}

#[test]
fn test_run_noop() {
    let mut test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    test_env.add_paths_to_normalize(fake_formatter.clone(), "$FAKE_FORMATTER_PATH");
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    work_dir.write_file("c.txt", "test to replace");
    work_dir.run_jj(&["commit", "-m", "C"]).success();
    insta::assert_snapshot!(get_log_output(&work_dir), @r"
    @  zsuskulnrvyrovkzqrwmxqlsskqntxvp
    ○  kkmpptxzrspxrzommnulwmwkkqwworplC
    │
    ○  rlvkpnrzqnoowoytxnquwvuryrwnrmlpB
    │
    ○  qpvuntsmwlqtpsluzzsnyyzlmlwvmlnuA
    │
    ◆  zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    [EOF]
    ");
    // `--stdout foo` writes to the subprocess's stdout, which `jj run` buffers
    // and emits to its own stdout. No tracked files in the working copy change,
    // so no commits get rewritten. Using a fixed string keeps the per-commit
    // output identical, so the concatenated stdout is stable regardless of the
    // (non-deterministic) order in which the parallel jobs finish.
    let output = work_dir
        .run_jj(&[
            "run",
            "-r",
            "..@",
            "--",
            &fake_formatter_path,
            "--stdout",
            "foo",
        ])
        .success();
    insta::assert_snapshot!(output.stdout, @"foofoofoofoo[EOF]");
    insta::assert_snapshot!(output.stderr, @r"
    Nothing changed.
    [EOF]
    ");
}

#[test]
fn test_run_sets_env_vars() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "seed"]).success();

    // Show the change_id and commit_id so the reader can match them against
    // the values the subprocess writes into the per-commit working copy.
    let log_template = r#"change_id ++ " " ++ commit_id ++ " " ++ description ++ "\n""#;
    insta::assert_snapshot!(
        work_dir.run_jj(&["log", "-T", log_template]),
        @r"
    @  rlvkpnrzqnoowoytxnquwvuryrwnrmlp fc4c875c9bc90128cbb9e8084dd5f5f336b383d9
    ○  qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu 5fbe90560fed1c39d46a46a672ba98abd53bdc6d seed
    │
    ◆  zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 0000000000000000000000000000000000000000
    [EOF]
    "
    );

    // Each subprocess echoes its JJ_CHANGE_ID and JJ_COMMIT_ID into files in
    // the per-commit working copy, modifying the tree so the commit gets
    // rewritten with those files.
    let jj_args: &[&str] = if cfg!(windows) {
        &[
            "run",
            "-r",
            "@-",
            "--",
            "cmd",
            "/c",
            "echo %JJ_CHANGE_ID%>change_id.txt && echo %JJ_COMMIT_ID%>commit_id.txt",
        ]
    } else {
        &[
            "run",
            "-r",
            "@-",
            "--",
            "sh",
            "-c",
            "echo $JJ_CHANGE_ID > change_id.txt && echo $JJ_COMMIT_ID > commit_id.txt",
        ]
    };
    work_dir.run_jj(jj_args).success();

    let normalize_whitespace = |s: String| {
        s.replace("\r\n", "\n")
            .lines()
            .map(|line| line.trim_end())
            .collect::<Vec<_>>()
            .join("\n")
            + "\n"
    };
    insta::assert_snapshot!(
        work_dir
            .run_jj(&["file", "show", "-r", "@-", "change_id.txt"])
            .normalize_stdout_with(normalize_whitespace),
        @r"
    qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
    [EOF]
    "
    );
    insta::assert_snapshot!(
        work_dir
            .run_jj(&["file", "show", "-r", "@-", "commit_id.txt"])
            .normalize_stdout_with(normalize_whitespace),
        @r"
    5fbe90560fed1c39d46a46a672ba98abd53bdc6d
    [EOF]
    "
    );
}

#[test]
fn test_run_from_subdir_skips_commits_without_it() {
    let mut test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    // `fake-formatter --tee ran.txt` is a portable way to create an empty
    // `ran.txt`, equivalent to `touch ran.txt` but available on all platforms.
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    test_env.add_paths_to_normalize(fake_formatter.clone(), "$FAKE_FORMATTER_PATH");
    let work_dir = test_env.work_dir("repo");

    // First commit has only root-level files; no `sub/` exists yet.
    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "no-sub"]).success();
    // Second commit adds `sub/file.txt`, so `sub/` exists from here on.
    work_dir.write_file("sub/file.txt", "x");
    work_dir.run_jj(&["commit", "-m", "with-sub"]).success();

    // Run from inside sub/ on both ancestors. The command creates `ran.txt`
    // in cwd, so we can later tell where it ran. The `no-sub` commit has no
    // `sub/` directory and should be skipped; the `with-sub` commit has
    // `sub/` and should be rewritten with `sub/ran.txt` added.
    let sub_dir = work_dir.dir("sub");
    let output = sub_dir
        .run_jj(&[
            "run",
            "-r",
            "@-|@--",
            "--",
            &fake_formatter_path,
            "--tee",
            "ran.txt",
        ])
        .success()
        .normalize_backslash();
    insta::assert_snapshot!(output.stderr, @r"
    Skipped commit 3bb1f1ca3c09a8e6be46ef48515803464b16b426: directory does not exist: sub
    Rewrote 1 commits.
    Working copy  (@) now at: kkmpptxz 3548431a (empty) (no description set)
    Parent commit (@-)      : rlvkpnrz 3aa9a235 with-sub
    Added 1 files, modified 0 files, removed 0 files
    [EOF]
    ");

    // The rewritten `with-sub` commit has `sub/ran.txt`, alongside the
    // pre-existing `sub/file.txt`.
    insta::assert_snapshot!(
        work_dir
            .run_jj(&["file", "list", "-r", "@-"])
            .normalize_backslash(),
        @r"
    seed.txt
    sub/file.txt
    sub/ran.txt
    [EOF]
    "
    );
}

#[test]
fn test_run_root_flag() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    // `fake-formatter --tee ran.txt` is a portable way to create an empty
    // `ran.txt`, equivalent to `touch ran.txt` but available on all platforms.
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("sub/file.txt", "x");
    work_dir.run_jj(&["commit", "-m", "with-sub"]).success();

    // Invoke `jj run` from inside sub/, but pass `--root` so the command
    // executes from the workspace root and `ran.txt` lands at the top level.
    let sub_dir = work_dir.dir("sub");
    sub_dir
        .run_jj(&[
            "run",
            "--root",
            "-r",
            "@-",
            "--",
            &fake_formatter_path,
            "--tee",
            "ran.txt",
        ])
        .success();

    insta::assert_snapshot!(
        work_dir
            .run_jj(&["file", "list", "-r", "@-"])
            .normalize_backslash(),
        @r"
    ran.txt
    sub/file.txt
    [EOF]
    "
    );
}

#[test]
fn test_run_uses_revsets_run_as_default() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    // `fake-formatter --tee ran.txt` is a portable way to create an empty
    // `ran.txt`, equivalent to `touch ran.txt` but available on all platforms.
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    let work_dir = test_env.work_dir("repo");

    // Two sibling commits, `foo` and `bar`.
    work_dir.write_file("file", "foo");
    work_dir
        .run_jj(["bookmark", "create", "-r@", "foo"])
        .success();
    work_dir.run_jj(["new", "root()"]).success();
    work_dir.write_file("file", "bar");
    work_dir
        .run_jj(["bookmark", "create", "-r@", "bar"])
        .success();
    work_dir.run_jj(["edit", "foo"]).success();

    test_env.add_config(r#"revsets.run = "bar""#);

    // Running `jj run` with `revsets.run=bar` should only modify bar
    work_dir
        .run_jj([
            "--config=revsets.run=\"bar\"",
            "run",
            "--",
            &fake_formatter_path,
            "--tee",
            "ran.txt",
        ])
        .success();

    insta::assert_snapshot!(
        work_dir.run_jj(["file", "list", "-r", "foo"]),
        @r"
    file
    [EOF]
    "
    );
    insta::assert_snapshot!(
        work_dir.run_jj(["file", "list", "-r", "bar"]),
        @r"
    file
    ran.txt
    [EOF]
    "
    );

    // Run again but now with foo in the config
    work_dir.run_jj(["undo"]).success();
    work_dir
        .run_jj([
            "--config=revsets.run=\"foo\"",
            "run",
            "--",
            &fake_formatter_path,
            "--tee",
            "ran.txt",
        ])
        .success();

    insta::assert_snapshot!(
        work_dir.run_jj(["file", "list", "-r", "foo"]),
        @r"
    file
    ran.txt
    [EOF]
    "
    );
    insta::assert_snapshot!(
        work_dir.run_jj(["file", "list", "-r", "bar"]),
        @r"
    file
    [EOF]
    "
    );
}

#[test]
fn test_run_failure_rewrites_nothing() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    let log_before = get_log_output(&work_dir);
    insta::assert_snapshot!(log_before, @r"
    @  kkmpptxzrspxrzommnulwmwkkqwworpl
    ○  rlvkpnrzqnoowoytxnquwvuryrwnrmlpB
    │
    ○  qpvuntsmwlqtpsluzzsnyyzlmlwvmlnuA
    │
    ◆  zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    [EOF]
    ");

    // Fail on commit B; succeed (modify the tree) on every other commit. If
    // any subprocess fails, `jj run` must roll back: no commit gets rewritten,
    // even the ones whose commands ran to completion before B's failure
    // propagated.
    let cmd = "if [ \"$JJ_CHANGE_ID\" = 'rlvkpnrzqnoowoytxnquwvuryrwnrmlp' ]; then exit 1; fi; \
               touch ran.txt";
    let output = work_dir.run_jj(&["run", "-r", "..@", "--", "sh", "-c", cmd]);
    assert!(!output.status.success(), "expected `jj run` to fail");

    // Log is unchanged: same change_ids, same shape, no descendants of B got
    // rebased onto a new commit.
    assert_eq!(get_log_output(&work_dir), log_before);
}

#[test]
fn test_run_ignore_errors_rewrites_successes() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    create_commit_with_files(&work_dir, "a", &[], &[("a.txt", "a")]);
    create_commit_with_files(&work_dir, "b", &["a"], &[("b.txt", "b")]);

    // Fail on A; succeed on B. A should be untouched, B should be rewritten.
    let jj_args: &[&str] = if cfg!(windows) {
        &[
            "run",
            "--ignore-errors",
            "-r",
            "..b",
            "--",
            "cmd",
            "/c",
            "type nul >ran.txt & (if not exist b.txt exit 1)",
        ]
    } else {
        &[
            "run",
            "--ignore-errors",
            "-r",
            "..b",
            "--",
            "sh",
            "-c",
            "touch ran.txt; if [ ! -f b.txt ]; then exit 1; fi",
        ]
    };
    let output = work_dir.run_jj(jj_args);
    assert_snapshot!(
        output.success(), @r"
    ------- stderr -------
    Rewrote 1 commits.
    Working copy  (@) now at: zsuskuln f3c3b6ac b | b
    Parent commit (@-)      : rlvkpnrz 2385de9f a | a
    Added 1 files, modified 0 files, removed 0 files
    [EOF]
    "
    );
    insta::assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r=a"]),
        @r"
    a.txt
    [EOF]
    "
    );
    insta::assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r=b"]),
        @r"
    a.txt
    b.txt
    ran.txt
    [EOF]
    "
    );
}

#[test]
fn test_run_ignore_errors_all_fail() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();

    let log_before = get_log_output(&work_dir);

    let output = work_dir.run_jj(&[
        "run",
        "--ignore-errors",
        "-r",
        "@-",
        "--",
        &fake_formatter_path,
        "--fail",
    ]);
    assert_snapshot!(
        output.success(), @r"
    ------- stderr -------
    Nothing changed.
    [EOF]
    "
    );

    // Log is unchanged: no commits were rewritten.
    assert_eq!(get_log_output(&work_dir), log_before);
}

#[test]
fn test_run_recovers_after_failure() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    // `fake-formatter --fail` exits non-zero (like `false`) and
    // `fake-formatter --tee ran.txt` creates an empty `ran.txt` (like `touch`);
    // both are portable across platforms.
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();

    // First run fails; snapshot+persist still runs, leaving each slot with a
    // valid tree_state on disk.
    let first = work_dir.run_jj(&["run", "-r", "..@", "--", &fake_formatter_path, "--fail"]);
    assert!(!first.status.success(), "expected first `jj run` to fail");

    // A second run with a working command must succeed: the persisted
    // tree_state lets each slot be reused without a wipe-and-reinit.
    work_dir
        .run_jj(&[
            "run",
            "-r",
            "..@",
            "--",
            &fake_formatter_path,
            "--tee",
            "ran.txt",
        ])
        .success();

    // Both commits in `..@` now carry `ran.txt`.
    insta::assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r", "@-"]),
        @r"
    A.txt
    b.txt
    ran.txt
    [EOF]
    "
    );
    insta::assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r", "@--"]),
        @r"
    A.txt
    ran.txt
    [EOF]
    "
    );
}

#[test]
fn test_run_shell_command() {
    // The new positional-args interface means users have to invoke a shell
    // explicitly to use shell features. This verifies that path works
    // end-to-end: each per-commit subprocess sees its `JJ_COMMIT_ID` and the
    // shell echoes it to stdout.
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    work_dir.write_file("c.txt", "test to replace");
    work_dir.run_jj(&["commit", "-m", "C"]).success();

    // Show the commit_ids so the reader can match them against the values
    // the snapshot below was captured with.
    let log_template = r#"change_id ++ " " ++ commit_id ++ " " ++ description ++ "\n""#;
    insta::assert_snapshot!(
        work_dir.run_jj(&["log", "-T", log_template, "-r", "..@"]),
        @r"
    @  zsuskulnrvyrovkzqrwmxqlsskqntxvp 8d0cb96bac2cfefd56a8691b9301ef44cc94a368
    ○  kkmpptxzrspxrzommnulwmwkkqwworpl 3406218c99ce8076f3a28434ebda109cbd84de9e C
    │
    ○  rlvkpnrzqnoowoytxnquwvuryrwnrmlp 9453b0f03bbda20fa849b10eb051d1e3eed1ec5d B
    │
    ○  qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu 26d8ff9bba4faa4da6735ced959c57280e49afa7 A
    │
    ~
    [EOF]
    "
    );

    let jj_args: &[&str] = if cfg!(windows) {
        &["run", "-r", "..@", "--", "cmd", "/c", "echo %JJ_COMMIT_ID%"]
    } else {
        &[
            "run",
            "-r",
            "..@",
            "--",
            "sh",
            "-c",
            r#"echo "$JJ_COMMIT_ID""#,
        ]
    };
    let output = work_dir.run_jj(jj_args).success();

    // Parallel jobs finish in non-deterministic order, so sort before
    // asserting.
    let mut lines: Vec<&str> = output.stdout.raw().lines().collect();
    lines.sort_unstable();
    let sorted_stdout = lines.join("\n");
    insta::assert_snapshot!(sorted_stdout, @r"
    26d8ff9bba4faa4da6735ced959c57280e49afa7
    3406218c99ce8076f3a28434ebda109cbd84de9e
    8d0cb96bac2cfefd56a8691b9301ef44cc94a368
    9453b0f03bbda20fa849b10eb051d1e3eed1ec5d
    ");
}

#[test]
fn test_run_sets_workspace_root_env_var() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "seed"]).success();

    // Each subprocess writes $JJ_WORKSPACE_ROOT into a file so we can assert
    // it equals the actual workspace root (not the per-commit working copy).
    let jj_args: &[&str] = if cfg!(windows) {
        &[
            "run",
            "-r",
            "@-",
            "--",
            "cmd",
            "/c",
            "echo %JJ_WORKSPACE_ROOT%>workspace_root.txt",
        ]
    } else {
        &[
            "run",
            "-r",
            "@-",
            "--",
            "sh",
            "-c",
            "echo $JJ_WORKSPACE_ROOT > workspace_root.txt",
        ]
    };
    work_dir.run_jj(jj_args).success();

    // Trim trailing whitespace per line and normalize CRLF to LF so the
    // snapshot is identical on Windows and Unix.
    let normalize_whitespace = |s: String| {
        s.replace("\r\n", "\n")
            .lines()
            .map(|line| line.trim_end().to_string())
            .collect::<Vec<_>>()
            .join("\n")
            + "\n"
    };
    // $TEST_ENV is the normalized placeholder for the test environment's temp
    // root directory. JJ_WORKSPACE_ROOT should point to the slot working copy
    // under .jj/run/default/1/working_copy, not to the original workspace.
    insta::assert_snapshot!(
        work_dir
            .run_jj(&["file", "show", "-r", "@-", "workspace_root.txt"])
            .normalize_stdout_with(normalize_whitespace),
        @r"
    $TEST_ENV/repo/.jj/run/default/1/working_copy
    [EOF]
    "
    );
}

/// After a failed `jj run`, the pool slot must be reusable: ignored files
/// (build artifacts) survive and non-ignored stray files are cleaned up.
#[test]
fn test_run_pool_reuses_slot_after_failure() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    let work_dir = test_env.work_dir("repo");

    work_dir.write_file(".gitignore", "cache/\n");
    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "seed"]).success();

    // Failing command writes an ignored artifact and a non-ignored stray file.
    let first = work_dir.run_jj(&[
        "run",
        "--config",
        "run.jobs=1",
        "-r",
        "@-",
        "--",
        "sh",
        "-c",
        &format!(
            "mkdir -p cache && echo artifact > cache/artifact.txt && touch stray.txt && \
             {fake_formatter_path} --fail"
        ),
    ]);
    assert!(!first.status.success(), "expected first run to fail");

    let slot_state = work_dir.root().join(".jj/run/default/1/state/tree_state");
    assert!(
        slot_state.exists(),
        "tree_state must be persisted even after failure"
    );

    // Succeeding second run: ignored artifact must still be present on disk;
    // the non-ignored stray.txt must have been cleaned up (not leaked into
    // the new commit).
    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "sh",
            "-c",
            "if [ -f cache/artifact.txt ]; then cp cache/artifact.txt result.txt; else echo \
             MISSING > result.txt; fi",
        ])
        .success();

    assert_snapshot!(
        work_dir.run_jj(&["file", "show", "-r", "@-", "result.txt"]),@r"
    artifact
    [EOF]
    "
    );
    assert_snapshot!(
        work_dir
        .run_jj(&["file", "list", "-r", "@-"]),
        @r"
    .gitignore
    result.txt
    seed.txt
    [EOF]
    "
    );
}

#[test]
fn test_run_pool_persists_between_runs() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "seed"]).success();

    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "touch",
            "ran.txt",
        ])
        .success();

    // The pool slot directory survives the run.
    let pool_slot = work_dir.root().join(".jj/run/default/1");
    assert!(
        pool_slot.exists(),
        "expected pool slot 1 to persist between runs at {pool_slot:?}",
    );
    assert!(pool_slot.join("working_copy").exists());
    assert!(pool_slot.join("state").exists());

    // A second run reuses the existing slot rather than recreating it from
    // scratch.
    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "touch",
            "ran2.txt",
        ])
        .success();
    assert!(pool_slot.join("working_copy").exists());
}

#[test]
fn test_run_pool_size_from_config() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("a.txt", "a");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    work_dir.write_file("c.txt", "c");
    work_dir.run_jj(&["commit", "-m", "C"]).success();

    // `run.jobs = 1` forces all three commits to share a single slot
    // and be processed sequentially.
    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=2",
            "-r",
            "..@",
            "--",
            "sh",
            "-c",
            "touch ran-$JJ_CHANGE_ID.txt",
        ])
        .success();

    let pool_dir = work_dir.root().join(".jj/run/default");
    assert!(pool_dir.join("1").exists(), "pool/1 should exist");
    assert!(pool_dir.join("2").exists(), "pool/2 should exist");
    assert!(
        !pool_dir.join("3").exists(),
        "pool/3 should NOT exist with size=2",
    );

    // All three commits picked up `ran.txt`.
    assert_snapshot!(work_dir.run_jj(&["file", "list", "-r", "@---"]), @r"
        a.txt
        ran-qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu.txt
        [EOF]
        ");
    assert_snapshot!(work_dir.run_jj(&["file", "list", "-r", "@--"]), @r"
        a.txt
        b.txt
        ran-qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu.txt
        ran-rlvkpnrzqnoowoytxnquwvuryrwnrmlp.txt
        [EOF]
        ");
    assert_snapshot!(work_dir.run_jj(&["file", "list", "-r", "@-"]), @r"
        a.txt
        b.txt
        c.txt
        ran-kkmpptxzrspxrzommnulwmwkkqwworpl.txt
        ran-qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu.txt
        ran-rlvkpnrzqnoowoytxnquwvuryrwnrmlp.txt
        [EOF]
        ");
}

/// `--jobs N` controls pool size when `run.jobs` is not set.
#[test]
fn test_run_pool_size_from_jobs_flag() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("a.txt", "a");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    work_dir.write_file("c.txt", "c");
    work_dir.run_jj(&["commit", "-m", "C"]).success();

    // `--jobs 2` with pool: expect exactly 2 slots, no more.
    work_dir
        .run_jj(&["run", "--jobs", "2", "-r", "..@", "--", "touch", "ran.txt"])
        .success();

    let pool_dir = work_dir.root().join(".jj/run/default");
    assert!(pool_dir.join("1").exists(), "pool/1 should exist");
    assert!(pool_dir.join("2").exists(), "pool/2 should exist");
    assert!(
        !pool_dir.join("3").exists(),
        "pool/3 must NOT exist with --jobs 2",
    );
}

#[test]
fn test_run_pool_preserves_untracked_artifacts() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    // The .gitignore keeps `cache/` out of the snapshot's tracking set, so
    // files there persist on disk between jobs without being committed.
    work_dir.write_file(".gitignore", "cache/\n");
    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "seed"]).success();

    // Run 1: drop a marker into the gitignored cache directory.
    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "sh",
            "-c",
            "mkdir -p cache && echo run1 > cache/marker && touch ran1.txt",
        ])
        .success();

    // Run 2: assert the marker is still there, write its contents into a
    // tracked file so we can verify from outside.
    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "sh",
            "-c",
            "if [ -f cache/marker ]; then cp cache/marker result.txt; else echo MISSING > \
             result.txt; fi",
        ])
        .success();

    assert_snapshot!(
        work_dir
        .run_jj(&["file", "show", "-r", "@-", "result.txt"])
        .success()
        .stdout,
        @r"
        run1
        [EOF]
        ",
    );
}

/// Pool correctly removes a file that is present in one commit's tree but
/// absent in the next commit processed by the same slot.
#[test]
fn test_run_pool_removes_file_absent_in_next_commit() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    // Commit A has only_in_a.txt.
    work_dir.write_file("only_in_a.txt", "a");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    // After commit -m A the WC inherits A's files. Delete the file so that
    // commit B's tree is empty (no only_in_a.txt).
    std::fs::remove_file(work_dir.root().join("only_in_a.txt")).unwrap();
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    // Stack: root → A (only_in_a.txt) → B ({}) → @

    // Pool size 1 forces both commits through the same slot sequentially.
    // @-- = A, @- = B (WC is above B).
    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=1",
            "-r",
            "@--::@-",
            "--",
            "touch",
            "ran.txt",
        ])
        .success();

    // A's rewrite (@--) keeps only_in_a.txt (and gains ran.txt).
    assert_snapshot!(
        work_dir
        .run_jj(&["file", "list", "-r", "@--"])
        .success()
        .stdout,
        @r"
        only_in_a.txt
        ran.txt
        [EOF]
        ",
    );

    // B's rewrite (@-) must NOT have only_in_a.txt leaked from A's slot.
    assert_snapshot!(
        work_dir
        .run_jj(&["file", "list", "-r", "@-"])
        .success()
        .stdout,
        @r"
        ran.txt
        [EOF]
        ",
    );
}

/// When a pool slot is reused, files left on disk that the previous commit's
/// .gitignore excluded must be removed before the next commit runs. Otherwise
/// the next commit (which may not ignore the same paths) would pick them up at
/// snapshot time and incorrectly add them to its rewritten tree.
#[test]
fn test_run_pool_removes_previously_ignored_files() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    let work_dir = test_env.work_dir("repo");

    // Commit a: no .gitignore.
    work_dir.write_file("seed.txt", "seed");
    work_dir.write_file(".gitignore", "always_ignored.txt\n");
    work_dir
        .run_jj(&["bookmark", "create", "-r@", "a"])
        .success();
    work_dir.run_jj(&["commit", "-m", "a"]).success();
    // Commit b: adds a .gitignore that excludes `ignored.txt`.
    work_dir.write_file(".gitignore", "always_ignored.txt\nignored.txt\n");
    work_dir
        .run_jj(&["bookmark", "create", "-r@", "b"])
        .success();
    work_dir.run_jj(&["commit", "-m", "b"]).success();

    let run_wc = work_dir.root().join(".jj/run/default/1/working_copy");

    // Leave two ignored files in the run workspace
    work_dir
        .run_jj(&[
            "run",
            "-r=b",
            "--",
            &fake_formatter_path,
            "--tee=always_ignored.txt",
            "--tee=ignored.txt",
        ])
        .success();
    assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r", "b"]),
        @r"
    .gitignore
    seed.txt
    [EOF]
    "
    );
    assert!(fs::exists(run_wc.join("always_ignored.txt")).unwrap());
    assert!(fs::exists(run_wc.join("ignored.txt")).unwrap());

    // Run against a version that only ignores always_ignored.txt, ensure that
    // ignored.txt is removed, not amended into 'a'.
    work_dir
        .run_jj(&[
            "run",
            "-r=a",
            "--",
            &fake_formatter_path,
            "--stdout",
            "done",
        ])
        .success();
    assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r", "a"]),
        @r"
    .gitignore
    seed.txt
    [EOF]
    "
    );
    // Remove files that are no longer ignored in the new revision, but don't
    // unnecessarily remove files that are still ignored
    assert!(fs::exists(run_wc.join("always_ignored.txt")).unwrap());
    assert!(!fs::exists(run_wc.join("ignored.txt")).unwrap());

    // Passing --clean removes even always-ignored files
    work_dir
        .run_jj(&[
            "run",
            "-r=a",
            "--clean",
            "--",
            &fake_formatter_path,
            "--stdout",
            "done",
        ])
        .success();
    assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r", "a"]),
        @r"
    .gitignore
    seed.txt
    [EOF]
    "
    );
    assert!(!fs::exists(run_wc.join("always_ignored.txt")).unwrap());
    assert!(!fs::exists(run_wc.join("ignored.txt")).unwrap());
}

/// A slot whose tree_state is absent (simulating a crash mid-job) should be
/// wiped and reinitialized on the next acquisition, not produce garbage.
#[test]
fn test_run_pool_recovers_from_missing_tree_state() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "seed"]).success();

    // Prime the slot so working_copy/ exists.
    work_dir
        .run_jj(&["run", "--config", "run.jobs=1", "-r", "@-", "--", "true"])
        .success();

    // Simulate a crash: plant a stale file in the slot and delete tree_state.
    let slot = work_dir.root().join(".jj/run/default/1");
    std::fs::write(slot.join("working_copy/stale.txt"), "crash leftovers").unwrap();
    std::fs::remove_file(slot.join("state/tree_state")).unwrap();

    // A second run should wipe the stale state and produce a clean rewrite.
    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "touch",
            "ran.txt",
        ])
        .success();

    assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r", "@-"]).success().stdout,
        @r"
        ran.txt
        seed.txt
        [EOF]
        ",
    );
}

/// A failed command (non-zero exit) must not poison the pool slot for the
/// next `jj run` invocation.
#[test]
fn test_run_pool_failed_command_does_not_poison_slot() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "seed"]).success();

    // Run 1: command fails, but writes a file first.
    drop(work_dir.run_jj(&[
        "run",
        "--config",
        "run.jobs=1",
        "-r",
        "@-",
        "--",
        "sh",
        "-c",
        "touch poison.txt; exit 1",
    ]));

    // Run 2: a clean command. poison.txt must not appear in the rewrite.
    work_dir
        .run_jj(&[
            "run",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "touch",
            "ran.txt",
        ])
        .success();

    assert_snapshot!(
        work_dir.run_jj(&["file", "list", "-r", "@-"]).success().stdout,
        @r"
        ran.txt
        seed.txt
        [EOF]
        ",
    );
}

#[test]
fn test_run_restore_descendants_preserves_content() {
    let mut test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    test_env.add_paths_to_normalize(fake_formatter.clone(), "$FAKE_FORMATTER_PATH");
    let work_dir = test_env.work_dir("repo");

    create_commit_with_files(&work_dir, "a", &[], &[("file", "a\n")]);
    create_commit_with_files(&work_dir, "b", &["a"], &[("file", "b\n")]);
    create_commit_with_files(&work_dir, "c", &["b"], &[("file", "c\n")]);

    let command = if cfg!(windows) {
        format!("{fake_formatter_path} --tee ran-%JJ_CHANGE_ID%.txt")
    } else {
        format!("{fake_formatter_path} --tee ran-$JJ_CHANGE_ID.txt")
    };
    let args: &[&str] = if cfg!(windows) {
        &[
            "run",
            "-r",
            "a::b",
            "--restore-descendants",
            "--",
            "cmd",
            "/c",
            command.as_str(),
        ]
    } else {
        &[
            "run",
            "-r",
            "a::b",
            "--restore-descendants",
            "--",
            "sh",
            "-c",
            command.as_str(),
        ]
    };
    let output = work_dir.run_jj(args).success();
    assert_snapshot!(output.stderr, @r"
    Rewrote 2 commits.
    Rebased 1 descendant commits (while preserving their content).
    Working copy  (@) now at: royxmykx a741a7d3 c | c
    Parent commit (@-)      : zsuskuln 43c5a714 b | b
    [EOF]
    ");

    assert_snapshot!(
        work_dir
        .run_jj(&["file", "list", "-r", "a"])
        .success()
        .stdout,
        @r"
    file
    ran-rlvkpnrzqnoowoytxnquwvuryrwnrmlp.txt
    [EOF]
    "
    );
    assert_snapshot!(
        work_dir
        .run_jj(&["file", "list", "-r", "b"])
        .success()
        .stdout,
        @r"
    file
    ran-zsuskulnrvyrovkzqrwmxqlsskqntxvp.txt
    [EOF]
    "
    );
    assert_snapshot!(
        work_dir
        .run_jj(&["file", "list", "-r", "c"])
        .success()
        .stdout,
        @r"
    file
    [EOF]
    "
    );

    assert_snapshot!(
        work_dir.run_jj(&["diff", "--from=a", "--to=b", "--git"]).success().stdout,
        @r"
    diff --git a/file b/file
    index 7898192261..6178079822 100644
    --- a/file
    +++ b/file
    @@ -1,1 +1,1 @@
    -a
    +b
    diff --git a/ran-rlvkpnrzqnoowoytxnquwvuryrwnrmlp.txt b/ran-rlvkpnrzqnoowoytxnquwvuryrwnrmlp.txt
    deleted file mode 100644
    index e69de29bb2..0000000000
    diff --git a/ran-zsuskulnrvyrovkzqrwmxqlsskqntxvp.txt b/ran-zsuskulnrvyrovkzqrwmxqlsskqntxvp.txt
    new file mode 100644
    index 0000000000..e69de29bb2
    [EOF]
    "
    );
    assert_snapshot!(
        work_dir.run_jj(&["diff", "--from=b", "--to=c", "--git"]).success().stdout,
        @r"
    diff --git a/file b/file
    index 6178079822..f2ad6c76f0 100644
    --- a/file
    +++ b/file
    @@ -1,1 +1,1 @@
    -b
    +c
    diff --git a/ran-zsuskulnrvyrovkzqrwmxqlsskqntxvp.txt b/ran-zsuskulnrvyrovkzqrwmxqlsskqntxvp.txt
    deleted file mode 100644
    index e69de29bb2..0000000000
    [EOF]
    "
    );
}

#[test]
fn test_run_failure_shows_output() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();

    let output = work_dir.run_jj(&[
        "run",
        "-r",
        "@-",
        "--",
        &fake_formatter_path,
        "--stdout",
        "hello stdout\n",
        "--stderr",
        "hello stderr\n",
        "--fail",
    ]);
    assert!(!output.status.success());
    insta::with_settings!({
        filters => [
            ("exit code", "exit status"), // Windows
        ],
    }, {
        insta::assert_snapshot!(&output.normalize_stderr_with(|stderr| stderr.replace(&fake_formatter_path.clone(), "fake-formatter")), @"
        hello stdout
        [EOF]
        ------- stderr -------
        hello stderr
        Error: the command 'fake-formatter --stdout hello stdout
         --stderr hello stderr
         --fail' failed with exit status: 1
        Hint: Failed revision: qpvuntsm 26d8ff9b A
        [EOF]
        [exit status: 1]
        ");
    });
}

/// Changes made to an ancestor commit must still propagate into descendant
/// commits after rebasing.
#[test]
fn test_run_parallel_changes_propagate_to_descendants() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("a.txt", "a");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    work_dir.write_file("c.txt", "c");
    work_dir.run_jj(&["commit", "-m", "C"]).success();

    // Add a unique file to each change
    work_dir
        .run_jj(&[
            "run",
            "--jobs=3",
            "-r=..@",
            "--",
            "sh",
            "-c",
            "touch newfile-$JJ_CHANGE_ID.txt",
        ])
        .success();

    assert_snapshot!(work_dir.run_jj(&["file", "list", "-r=@---"]).success().stdout,@r"
    a.txt
    newfile-qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu.txt
    [EOF]
    ");
    assert_snapshot!(work_dir.run_jj(&["file", "list", "-r=@--"]).success().stdout,@r"
    a.txt
    b.txt
    newfile-qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu.txt
    newfile-rlvkpnrzqnoowoytxnquwvuryrwnrmlp.txt
    [EOF]
    ");
    assert_snapshot!(work_dir.run_jj(&["file", "list", "-r=@-"]).success().stdout,@r"
    a.txt
    b.txt
    c.txt
    newfile-kkmpptxzrspxrzommnulwmwkkqwworpl.txt
    newfile-qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu.txt
    newfile-rlvkpnrzqnoowoytxnquwvuryrwnrmlp.txt
    [EOF]
    ");
}

#[test]
fn test_run_ignore_changes_does_not_rewrite() {
    let mut test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    test_env.add_paths_to_normalize(fake_formatter.clone(), "$FAKE_FORMATTER_PATH");
    let work_dir = test_env.work_dir("repo");

    crate::common::create_commit_with_files(&work_dir, "a", &[], &[("file.txt", "a\n")]);
    crate::common::create_commit_with_files(&work_dir, "b", &["a"], &[("file.txt", "b\n")]);

    let log_before = get_log_output(&work_dir);

    // --tee touched.txt writes a new file in each working copy. Without
    // --ignore-changes this would amend the commits; with it nothing is rewritten.
    let output = work_dir
        .run_jj(&[
            "run",
            "--ignore-changes",
            "--config",
            "run.jobs=1",
            "-r",
            "a",
            "--",
            &fake_formatter_path,
            "--tee",
            "touched.txt",
        ])
        .success();
    insta::assert_snapshot!(output.stderr, @r"
    Nothing changed.
    [EOF]
    ");

    // Log must be identical to before.
    assert_eq!(get_log_output(&work_dir), log_before);

    // touched.txt must not appear in commit a's tree.
    assert_snapshot!(
        work_dir
        .run_jj(&["file", "list", "-r", "a"])
        .success(),
        @r"
    file.txt
    [EOF]
    "
    );
}

#[test]
fn test_run_ignore_changes_does_not_leak_between_invocations() {
    // Mirrors test_run_pool_no_file_leak_between_invocations but run 1 uses
    // --ignore-changes. The pool slot's tree_state is still updated by the snapshot
    // during run 1, so run 2 correctly removes artifact.txt from the slot
    // before checking out commit1.
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    work_dir.write_file("seed.txt", "seed");
    work_dir.run_jj(&["commit", "-m", "commit1"]).success();
    work_dir.run_jj(&["commit", "-m", "commit2"]).success();

    // Run 1 (--ignore-changes): writes artifact.txt in the pool slot for commit2
    // but does not amend any commit. The slot's tree_state must record
    // artifact.txt so run 2 can remove it when checking out a different tree.
    let touch_cmd: &[&str] = if cfg!(windows) {
        &[
            "run",
            "--ignore-changes",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "cmd",
            "/c",
            "echo. > artifact.txt",
        ]
    } else {
        &[
            "run",
            "--ignore-changes",
            "--config",
            "run.jobs=1",
            "-r",
            "@-",
            "--",
            "touch",
            "artifact.txt",
        ]
    };
    work_dir.run_jj(touch_cmd).success();

    // Run 2: no-op on commit1 (@--) using the same pool slot that held
    // artifact.txt. The checkout diff should remove artifact.txt from the slot.
    work_dir
        .run_jj(&["run", "--config", "run.jobs=1", "-r", "@--", "--", "true"])
        .success();

    let files = work_dir
        .run_jj(&["file", "list", "-r", "@--"])
        .success()
        .stdout
        .to_string();
    assert!(
        !files.contains("artifact.txt"),
        "artifact.txt must not leak into commit1 from --ignore-changes slot state; got:\n{files}",
    );
    assert!(
        files.contains("seed.txt"),
        "expected seed.txt in commit1; got:\n{files}",
    );
}

#[test]
fn test_run_ignore_changes_works_on_immutable() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    // Set up commits and bookmark BEFORE configuring immutable_heads, so
    // setup commands don't trip over the missing revset.
    work_dir.write_file("file.txt", "content");
    work_dir.run_jj(&["commit", "-m", "the commit"]).success();
    work_dir
        .run_jj(&["bookmark", "create", "-r", "@-", "main"])
        .success();
    test_env.add_config(r#"revset-aliases."immutable_heads()" = "main""#);

    // Without --ignore-changes, running on an immutable commit must fail.
    let err_output = work_dir.run_jj(&["run", "-r", "main", "--", "true"]);
    assert!(
        !err_output.status.success(),
        "expected failure on immutable commit"
    );
    let stderr = err_output.stderr.to_string();
    assert!(
        stderr.contains("immutable"),
        "expected 'immutable' in error; got:\n{stderr}",
    );

    // With --ignore-changes the same commit is allowed.
    work_dir
        .run_jj(&["run", "--ignore-changes", "-r", "main", "--", "true"])
        .success();
}

#[test]
fn test_run_ignore_changes_conflicts_with_restore_descendants() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    let output = work_dir.run_jj(&[
        "run",
        "--ignore-changes",
        "--restore-descendants",
        "--",
        "true",
    ]);
    assert!(!output.status.success());
    insta::assert_snapshot!(output.stderr, @r"
    error: the argument '--ignore-changes' cannot be used with '--restore-descendants'

    Usage: jj run --ignore-changes <COMMAND> [ARGS]...

    For more information, try '--help'.
    [EOF]
    ");
}

fn get_log_output(work_dir: &TestWorkDir) -> String {
    work_dir
        .run_jj(&["log", "-T", r#"change_id ++ description ++ "\n""#])
        .success()
        .stdout
        .to_string()
}

#[test]
fn test_run_order() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("file.txt", "a");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("file.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    work_dir.write_file("file.txt", "c");
    work_dir.run_jj(&["commit", "-m", "C"]).success();

    let jj_args: &[&str] = if cfg!(windows) {
        &["run", "-r=..@", "--", "cmd", "/c", "echo %JJ_CHANGE_ID%"]
    } else {
        &["run", "-r=..@", "--", "sh", "-c", "echo $JJ_CHANGE_ID"]
    };
    assert_snapshot!(work_dir.run_jj(jj_args).success().stdout,@"
    qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu
    rlvkpnrzqnoowoytxnquwvuryrwnrmlp
    kkmpptxzrspxrzommnulwmwkkqwworpl
    zsuskulnrvyrovkzqrwmxqlsskqntxvp
    [EOF]
    ");
}

#[test]
fn test_run_passthrough() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();

    insta::assert_snapshot!(
        work_dir.run_jj(&["log", "-T", r#"change_id ++ " " ++ description ++ "\n""#, "-r", "..@"]),
        @r"
    @  kkmpptxzrspxrzommnulwmwkkqwworpl
    ○  rlvkpnrzqnoowoytxnquwvuryrwnrmlp B
    │
    ○  qpvuntsmwlqtpsluzzsnyyzlmlwvmlnu A
    │
    ~
    [EOF]
    "
    );

    // --passthrough passes the child's stdout/stderr directly through. The output
    // appears in `jj run`'s own stdout/stderr (captured by the test harness).
    let jj_args: &[&str] = if cfg!(windows) {
        &[
            "run",
            "--passthrough",
            "-r",
            "..@",
            "--",
            "cmd",
            "/c",
            "echo hello from passthrough",
        ]
    } else {
        &[
            "run",
            "--passthrough",
            "-r",
            "..@",
            "--",
            "echo",
            "hello from passthrough",
        ]
    };
    let output = work_dir.run_jj(jj_args).success();
    insta::assert_snapshot!(output.stdout, @"hello from passthrough
hello from passthrough
hello from passthrough
[EOF]
");
}

#[test]
fn test_run_passthrough_failure_rewrites_nothing() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    work_dir.write_file("A.txt", "A");
    work_dir.run_jj(&["commit", "-m", "A"]).success();
    work_dir.write_file("b.txt", "b");
    work_dir.run_jj(&["commit", "-m", "B"]).success();
    let log_before = get_log_output(&work_dir);
    insta::assert_snapshot!(log_before, @r"
    @  kkmpptxzrspxrzommnulwmwkkqwworpl
    ○  rlvkpnrzqnoowoytxnquwvuryrwnrmlpB
    │
    ○  qpvuntsmwlqtpsluzzsnyyzlmlwvmlnuA
    │
    ◆  zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    [EOF]
    ");

    // A failing command run with --passthrough should not rewrite any commits.
    let output = work_dir.run_jj(&["run", "--passthrough", "-r", "..@", "--", "false"]);
    assert!(!output.status.success(), "expected `jj run` to fail");
    assert_eq!(get_log_output(&work_dir), log_before);
}

#[test]
fn test_run_passthrough_rejects_multi_job() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    let output = work_dir.run_jj(&[
        "run",
        "--passthrough",
        "--jobs",
        "2",
        "-r",
        "@",
        "--",
        "true",
    ]);
    assert!(!output.status.success());
    insta::assert_snapshot!(output.stderr, @r"
    Error: cannot use --passthrough with more than one job
    [EOF]
    ");
}

#[test]
fn test_run_on_conflicted_commit() {
    // Regression test for https://github.com/jj-vcs/jj/issues/9747: `jj run`
    // panicked when its revset contained a conflicted commit. The post-command
    // snapshot of such a commit is a conflicted (unresolved) tree, and the code
    // assumed the result always resolved to a single tree.
    let mut test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let fake_formatter = assert_cmd::cargo::cargo_bin("fake-formatter");
    assert!(fake_formatter.is_file());
    let fake_formatter_path = fake_formatter.to_string_lossy().into_owned();
    test_env.add_paths_to_normalize(fake_formatter.clone(), "$FAKE_FORMATTER_PATH");
    let work_dir = test_env.work_dir("repo");

    // Build a merge whose two sides change `file` differently, so the merge
    // commit `conflict` (and the working copy on it) conflicts in `file`.
    create_commit_with_files(&work_dir, "base", &[], &[("file", "base\n")]);
    create_commit_with_files(&work_dir, "a", &["base"], &[("file", "a\n")]);
    create_commit_with_files(&work_dir, "b", &["base"], &[("file", "b\n")]);
    create_commit_with_files(&work_dir, "conflict", &["a", "b"], &[]);
    insta::assert_snapshot!(work_dir.run_jj(&["resolve", "--list"]).success().stdout, @r"
    file    2-sided conflict
    [EOF]
    ");

    // `jj run` over the conflicted commit used to panic. `--tee` writes a file in
    // its working copy so the commit is actually rewritten, proving the conflict
    // survives the rewrite instead of crashing.
    let output = work_dir.run_jj(&[
        "run",
        "-r",
        "conflict",
        "--",
        &fake_formatter_path,
        "--stdout",
        "x",
        "--tee",
        "touched.txt",
    ]);
    insta::assert_snapshot!(output, @r"
    x[EOF]
    ------- stderr -------
    Rewrote 1 commits.
    Working copy  (@) now at: vruxwmqv 74643194 conflict | (conflict) conflict
    Parent commit (@-)      : zsuskuln 45537d53 a | a
    Parent commit (@-)      : royxmykx 89d1b299 b | b
    Added 1 files, modified 0 files, removed 0 files
    Warning: There are unresolved conflicts at these paths:
    file    2-sided conflict
    New conflicts appeared in 1 commits:
      vruxwmqv 74643194 conflict | (conflict) conflict
    Hint: To resolve the conflicts, start by creating a commit on top of
    the conflicted commit:
      jj new vruxwmqv
    Then use `jj resolve`, or edit the conflict markers in the file directly.
    Once the conflicts are resolved, you can inspect the result with `jj diff`.
    Then run `jj squash` to move the resolution into the conflicted commit.
    [EOF]
    ");

    // The rewritten commit still conflicts in `file` and gained touched.txt.
    insta::assert_snapshot!(work_dir.run_jj(&["resolve", "--list", "-r", "conflict"]).success().stdout, @r"
    file    2-sided conflict
    [EOF]
    ");
    insta::assert_snapshot!(work_dir.run_jj(&["file", "list", "-r", "conflict"]).success().stdout, @r"
    file
    touched.txt
    [EOF]
    ");
}