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
// Copyright 2022 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::ffi::OsString;

use indoc::indoc;
use itertools::Itertools as _;
use regex::Regex;
use testutils::TestResult;

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

#[test]
fn test_non_utf8_arg() {
    let test_env = TestEnvironment::default();
    #[cfg(unix)]
    let invalid_utf = {
        use std::os::unix::ffi::OsStringExt as _;
        OsString::from_vec(vec![0x66, 0x6f, 0x80, 0x6f])
    };
    #[cfg(windows)]
    let invalid_utf = {
        use std::os::windows::prelude::*;
        OsString::from_wide(&[0x0066, 0x006f, 0xD800, 0x006f])
    };
    let output = test_env.run_jj_in(".", [&invalid_utf]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Error: Non-UTF-8 argument
    [EOF]
    [exit status: 2]
    ");
}

#[test]
fn test_version() {
    let test_env = TestEnvironment::default();

    let output = test_env.run_jj_in(".", ["--version"]).success();
    let stdout = output.stdout.into_raw();
    let sanitized = stdout.replace(|c: char| c.is_ascii_hexdigit(), "?");
    let expected = [
        "jj ?.??.?\n",
        "jj ?.??.?-????????????????????????????????????????\n",
        // This test could be made to succeed when `jj` is compiled at a merge commit by adding a
        // few entries like "jj ?.??.?-????????????????????????????????????????-?????????????????
        // ???????????????????????\n" here. However, it might be best to keep it failing, so that
        // we avoid releasing `jj` with such `--version` output.
    ];
    assert!(
        expected.contains(&sanitized.as_str()),
        "`jj version` output: {stdout:?}.\nSanitized: {sanitized:?}\nExpected one of: {expected:?}"
    );
}

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

    // Outside of a repo.
    let output = test_env.run_jj_in(".", [""; 0]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Hint: Use `jj -h` for a list of available commands.
    Run `jj config set --user ui.default-command log` to disable this message.
    Error: There is no jj repo in "."
    [EOF]
    [exit status: 1]
    "#);

    test_env.add_config(r#"ui.default-command="log""#);
    let output = test_env.run_jj_in(".", [""; 0]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Error: There is no jj repo in "."
    [EOF]
    [exit status: 1]
    "#);

    let output = test_env.run_jj_in(".", ["--help"]).success();
    insta::assert_snapshot!(
        output.stdout.normalized().lines().next().unwrap(),
        @"Jujutsu (An experimental VCS)");
    insta::assert_snapshot!(output.stderr, @"");

    let output = test_env.run_jj_in(".", ["-R", "repo"]).success();
    assert_eq!(output, work_dir.run_jj(["log"]));

    // Inside of a repo.
    let output = work_dir.run_jj([""; 0]).success();
    assert_eq!(output, work_dir.run_jj(["log"]));

    // Command argument that looks like a command name.
    work_dir
        .run_jj(["bookmark", "create", "-r@", "help"])
        .success();
    work_dir
        .run_jj(["bookmark", "create", "-r@", "log"])
        .success();
    work_dir
        .run_jj(["bookmark", "create", "-r@", "show"])
        .success();
    // TODO: test_env.run_jj(["-r", "help"]).success()
    insta::assert_snapshot!(work_dir.run_jj(["-r", "log"]), @"
    @  qpvuntsm test.user@example.com 2001-02-03 08:05:07 help log show e8849ae1
    │  (empty) (no description set)
    ~
    [EOF]
    ");
    insta::assert_snapshot!(work_dir.run_jj(["-r", "show"]), @"
    @  qpvuntsm test.user@example.com 2001-02-03 08:05:07 help log show e8849ae1
    │  (empty) (no description set)
    ~
    [EOF]
    ");

    // Multiple default command strings work.
    test_env.add_config(r#"ui.default-command=["commit", "-m", "foo"]"#);
    work_dir.run_jj(["new"]).success();
    work_dir.write_file("file.txt", "file");
    let output = work_dir.run_jj([""; 0]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Working copy  (@) now at: kxryzmor 8db1ba9a (empty) (no description set)
    Parent commit (@-)      : lylxulpl 19f3adb2 foo
    [EOF]
    ");

    // We get a warning if the default command isn't recognized and looks like
    // it should have been specified as an array.
    test_env.add_config(r#"ui.default-command="log -n 10""#);
    let output = work_dir.run_jj([""; 0]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Warning: To include flags/arguments in `ui.default-command`, use an array instead of a string: `ui.default-command = ["log", "-n", "10"]`
    error: unrecognized subcommand 'log -n 10'

      tip: a similar subcommand exists: 'log'

    Usage: jj [OPTIONS] <COMMAND>

    For more information, try '--help'.
    [EOF]
    [exit status: 2]
    "#);

    // Hint isn't printed for explicit subcommands.
    let output = work_dir.run_jj(["foobar"]);
    insta::assert_snapshot!(output, @r"
    ------- stderr -------
    error: unrecognized subcommand 'foobar'

      tip: a similar subcommand exists: 'bookmark'

    Usage: jj [OPTIONS] <COMMAND>

    For more information, try '--help'.
    [EOF]
    [exit status: 2]
    ");

    // Hint isn't printed for explicit subcommands with spaces.
    let output = work_dir.run_jj(["log -n 10"]);
    insta::assert_snapshot!(output, @r"
    ------- stderr -------
    error: unrecognized subcommand 'log -n 10'

      tip: a similar subcommand exists: 'log'

    Usage: jj [OPTIONS] <COMMAND>

    For more information, try '--help'.
    [EOF]
    [exit status: 2]
    ");

    // While the default command is invalid, explicit subcommands still work.
    let output = work_dir.run_jj(["status"]);
    insta::assert_snapshot!(output, @r"
    The working copy has no changes.
    Working copy  (@) : kxryzmor 8db1ba9a (empty) (no description set)
    Parent commit (@-): lylxulpl 19f3adb2 foo
    [EOF]
    ");
}

#[test]
fn test_ignore_working_copy() {
    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", "initial");
    let output = work_dir.run_jj(["log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  82a10a4d9ef783fd68b661f40ce10dd80d599d9e
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // Modify the file. With --ignore-working-copy, we still get the same commit
    // ID.
    work_dir.write_file("file", "modified");
    let output_again = work_dir.run_jj(["log", "-T", "commit_id", "--ignore-working-copy"]);
    assert_eq!(output_again, output);

    // But without --ignore-working-copy, we get a new commit ID.
    let output = work_dir.run_jj(["log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  00fc09f48ccf5c8b025a0f93b0ec3b0e4294a598
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");
}

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

    let repo_path = test_env.env_root().join("repo");

    std::fs::write(repo_path.join("file1"), "initial").unwrap();
    test_env
        .run_jj_in(&repo_path, &["commit", "-m=initial"])
        .success();
    let op_log_output = test_env.run_jj_in(&repo_path, &["op", "log"]);
    let working_copy_output = test_env.run_jj_in(&repo_path, &["debug", "working-copy"]);

    // Modify the working copy and run a mutating operation. With
    // --no-integrate-operation, the working copy gets snapshotted and the operation
    // gets created, but there's no new operation in the operation log, and the
    // working copy state is not updated.
    std::fs::write(repo_path.join("file2"), "initial").unwrap();
    let output = test_env.run_jj_in(&repo_path, &["squash", "--no-integrate-operation"]);
    insta::assert_snapshot!(output.stdout, @"");
    insta::assert_snapshot!(output.stderr, @"
    Snapshot operation left uncommitted because --no-integrate-operation was requested: 13357990b38a
    Operation left uncommitted because --no-integrate-operation was requested: a028de7aa4f4
    [EOF]
    ");
    let stderr = output.stderr.into_raw();
    let last_line = stderr.lines().last().unwrap();
    let op_id_hex = last_line[last_line.len() - 12..].to_string();
    let output = test_env.run_jj_in(&repo_path, &["op", "log", "--ignore-working-copy"]);
    assert_eq!(output.stdout, op_log_output.stdout);
    let output = test_env.run_jj_in(&repo_path, &["debug", "working-copy"]);
    assert_eq!(output.stdout, working_copy_output.stdout);

    // We can see the resulting log and op log with --at-op
    let stdout = test_env.run_jj_in(&repo_path, &["log", "-s", "--at-op", op_id_hex.as_str()]);
    insta::assert_snapshot!(stdout, @"
    @  mzvwutvl test.user@example.com 2001-02-03 08:05:11 10644da4
    │  (empty) (no description set)
    ○  qpvuntsm test.user@example.com 2001-02-03 08:05:11 599772f7
    │  initial
    │  A file1
    │  A file2
    ◆  zzzzzzzz root() 00000000
    [EOF]
    ");
    let stdout = test_env.run_jj_in(&repo_path, &["op", "log", "--at-op", op_id_hex.as_str()]);
    insta::assert_snapshot!(stdout, @"
    @  a028de7aa4f4 test-username@host.example.com default@ 2001-02-03 04:05:11.000 +07:00 - 2001-02-03 04:05:11.000 +07:00
    │  squash commits into e6fc2362ee5fdd5eb879befc0ae556a2f57b94a0
    │  args: jj squash --no-integrate-operation
    ○  13357990b38a test-username@host.example.com default@ 2001-02-03 04:05:11.000 +07:00 - 2001-02-03 04:05:11.000 +07:00
    │  snapshot working copy
    │  args: jj squash --no-integrate-operation
    ○  e167310e1125 test-username@host.example.com default@ 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
    │  commit 289d54a4554ed0d7df9c47d566480a6b773ee431
    │  args: jj commit '-m=initial'
    ○  55b88fdb1890 test-username@host.example.com default@ 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
    │  snapshot working copy
    │  args: jj commit '-m=initial'
    ○  90267f31f904 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
    │  add workspace 'default'
    ○  000000000000 root()
    [EOF]
    ");
}

#[test]
fn test_no_integrate_operation_colocated() {
    let test_env = TestEnvironment::default();
    test_env
        .run_jj_in(test_env.env_root(), &["git", "init", "--colocate", "repo"])
        .success();

    let repo_path = test_env.env_root().join("repo");

    std::fs::write(repo_path.join("file1"), "initial").unwrap();
    test_env
        .run_jj_in(&repo_path, &["commit", "-m=initial"])
        .success();
    let op_log_output = test_env.run_jj_in(&repo_path, &["op", "log"]);
    let working_copy_output = test_env.run_jj_in(&repo_path, &["debug", "working-copy"]);

    // Modify the working copy and run a mutating operation. With
    // --no-integrate-operation, the working copy gets snapshotted and the operation
    // gets created, but there's no new operation in the operation log, and the
    // working copy state is not updated.
    std::fs::write(repo_path.join("file2"), "initial").unwrap();
    let output = test_env.run_jj_in(&repo_path, &["squash", "--no-integrate-operation"]);
    insta::assert_snapshot!(output.stdout, @"");
    insta::assert_snapshot!(output.stderr, @"
    Snapshot operation left uncommitted because --no-integrate-operation was requested: f9d2255ff5a3
    Operation left uncommitted because --no-integrate-operation was requested: 0eccbf94f56f
    [EOF]
    ");
    let stderr = output.stderr.into_raw();
    let last_line = stderr.lines().last().unwrap();
    let op_id_hex = last_line[last_line.len() - 12..].to_string();
    let output = test_env.run_jj_in(&repo_path, &["op", "log", "--ignore-working-copy"]);
    assert_eq!(output.stdout, op_log_output.stdout);
    let output = test_env.run_jj_in(&repo_path, &["debug", "working-copy"]);
    assert_eq!(output.stdout, working_copy_output.stdout);

    // We can see the resulting log and op log with --at-op
    let stdout = test_env.run_jj_in(&repo_path, &["log", "-s", "--at-op", op_id_hex.as_str()]);
    insta::assert_snapshot!(stdout, @"
    @  mzvwutvl test.user@example.com 2001-02-03 08:05:11 10644da4
    │  (empty) (no description set)
    ○  qpvuntsm test.user@example.com 2001-02-03 08:05:11 599772f7
    │  initial
    │  A file1
    │  A file2
    ◆  zzzzzzzz root() 00000000
    [EOF]
    ");
    let stdout = test_env.run_jj_in(&repo_path, &["op", "log", "--at-op", op_id_hex.as_str()]);
    insta::assert_snapshot!(stdout, @"
    @  0eccbf94f56f test-username@host.example.com default@ 2001-02-03 04:05:11.000 +07:00 - 2001-02-03 04:05:11.000 +07:00
    │  squash commits into e6fc2362ee5fdd5eb879befc0ae556a2f57b94a0
    │  args: jj squash --no-integrate-operation
    ○  f9d2255ff5a3 test-username@host.example.com default@ 2001-02-03 04:05:11.000 +07:00 - 2001-02-03 04:05:11.000 +07:00
    │  snapshot working copy
    │  args: jj squash --no-integrate-operation
    ○  30e6a62058cc test-username@host.example.com default@ 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
    │  commit 289d54a4554ed0d7df9c47d566480a6b773ee431
    │  args: jj commit '-m=initial'
    ○  55b88fdb1890 test-username@host.example.com default@ 2001-02-03 04:05:08.000 +07:00 - 2001-02-03 04:05:08.000 +07:00
    │  snapshot working copy
    │  args: jj commit '-m=initial'
    ○  90267f31f904 test-username@host.example.com 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
    │  add workspace 'default'
    ○  000000000000 root()
    [EOF]
    ");
}

#[test]
fn test_repo_arg_with_git_init() {
    let test_env = TestEnvironment::default();
    let output = test_env.run_jj_in(".", ["git", "init", "-R=.", "repo"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Error: There is no jj repo in "."
    [EOF]
    [exit status: 1]
    "#);
}

#[test]
fn test_repo_arg_with_git_clone() {
    let test_env = TestEnvironment::default();
    let output = test_env.run_jj_in(".", ["git", "clone", "-R=.", "remote"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Error: There is no jj repo in "."
    [EOF]
    [exit status: 1]
    "#);
}

#[test]
fn test_resolve_workspace_directory() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    let sub_dir = work_dir.create_dir_all("dir/subdir");

    // Ancestor of cwd
    let output = sub_dir.run_jj(["status"]);
    insta::assert_snapshot!(output, @"
    The working copy has no changes.
    Working copy  (@) : qpvuntsm e8849ae1 (empty) (no description set)
    Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
    [EOF]
    ");

    // Explicit subdirectory path
    let output = sub_dir.run_jj(["status", "-R", "."]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Error: There is no jj repo in "."
    [EOF]
    [exit status: 1]
    "#);

    // Valid explicit path
    let output = sub_dir.run_jj(["status", "-R", "../.."]);
    insta::assert_snapshot!(output, @"
    The working copy has no changes.
    Working copy  (@) : qpvuntsm e8849ae1 (empty) (no description set)
    Parent commit (@-): zzzzzzzz 00000000 (empty) (no description set)
    [EOF]
    ");

    // "../../..".ancestors() contains "../..", but it should never be looked up.
    let output = sub_dir.run_jj(["status", "-R", "../../.."]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Error: There is no jj repo in "../../.."
    [EOF]
    [exit status: 1]
    "#);
}

#[test]
fn test_no_workspace_directory() {
    let test_env = TestEnvironment::default();
    let work_dir = test_env.work_dir("repo");
    work_dir.create_dir_all("");

    let output = work_dir.run_jj(["status"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Error: There is no jj repo in "."
    [EOF]
    [exit status: 1]
    "#);

    let output = test_env.run_jj_in(".", ["status", "-R", "repo"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Error: There is no jj repo in "repo"
    [EOF]
    [exit status: 1]
    "#);

    work_dir.create_dir_all(".git");
    let output = work_dir.run_jj(["status"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Error: There is no jj repo in "."
    Hint: It looks like this is a git repo. You can create a jj repo backed by it by running this:
    jj git init
    [EOF]
    [exit status: 1]
    "#);
}

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

    // cwd == workspace_root
    let output = work_dir.run_jj(["file", "show", "../out"]);
    insta::assert_snapshot!(output.normalize_backslash(), @r#"
    ------- stderr -------
    Error: Failed to parse fileset: Invalid file pattern
    Caused by:
    1:  --> 1:1
      |
    1 | ../out
      | ^----^
      |
      = Invalid file pattern
    2: Path "../out" is not in the repo "."
    3: Invalid component ".." in repo-relative path "../out"
    [EOF]
    [exit status: 1]
    "#);

    // cwd != workspace_root, can't be parsed as repo-relative path
    let output = sub_dir.run_jj(["file", "show", "../.."]);
    insta::assert_snapshot!(output.normalize_backslash(), @r#"
    ------- stderr -------
    Error: Failed to parse fileset: Invalid file pattern
    Caused by:
    1:  --> 1:1
      |
    1 | ../..
      | ^---^
      |
      = Invalid file pattern
    2: Path "../.." is not in the repo ".."
    3: Invalid component ".." in repo-relative path ".."
    [EOF]
    [exit status: 1]
    "#);

    // cwd != workspace_root, can be parsed as repo-relative path
    let output = test_env.run_jj_in(".", ["file", "show", "-Rrepo", "out"]);
    insta::assert_snapshot!(output.normalize_backslash(), @r#"
    ------- stderr -------
    Error: Failed to parse fileset: Invalid file pattern
    Caused by:
    1:  --> 1:1
      |
    1 | out
      | ^-^
      |
      = Invalid file pattern
    2: Path "out" is not in the repo "repo"
    3: Invalid component ".." in repo-relative path "../out"
    Hint: Consider using root:"out" to specify repo-relative path
    [EOF]
    [exit status: 1]
    "#);
}

#[test]
fn test_invalid_filesets_looking_like_filepaths() {
    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(["file", "show", "abc~"]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Error: Failed to parse fileset: Syntax error
    Caused by:  --> 1:5
      |
    1 | abc~
      |     ^---
      |
      = expected `~` or <primary>
    Hint: See https://docs.jj-vcs.dev/latest/filesets/ or use `jj help -k filesets` for filesets syntax and how to match file paths.
    [EOF]
    [exit status: 1]
    ");
}

#[test]
fn test_broken_repo_structure() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    let store_path = work_dir.root().join(".jj").join("repo").join("store");
    let store_type_path = store_path.join("type");

    // Test the error message when the git repository can't be located.
    work_dir.remove_file(store_path.join("git_target"));
    let output = work_dir.run_jj(["log"]);
    insta::assert_snapshot!(output.strip_stderr_last_line(), @"
    ------- stderr -------
    Internal error: The repository appears broken or inaccessible
    Caused by:
    1: Cannot access $TEST_ENV/repo/.jj/repo/store/git_target
    [EOF]
    [exit status: 255]
    ");

    // Test the error message when the commit backend is of unknown type.
    work_dir.write_file(&store_type_path, "unknown");
    let output = work_dir.run_jj(["log"]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Internal error: This version of the jj binary doesn't support this type of repo
    Caused by: Unsupported commit backend type 'unknown'
    [EOF]
    [exit status: 255]
    ");

    // Test the error message when the file indicating the commit backend type
    // cannot be read.
    work_dir.remove_file(&store_type_path);
    work_dir.create_dir(&store_type_path);
    let output = work_dir.run_jj(["log"]);
    insta::assert_snapshot!(output.strip_stderr_last_line(), @"
    ------- stderr -------
    Internal error: The repository appears broken or inaccessible
    Caused by:
    1: Failed to read commit backend type
    2: Cannot access $TEST_ENV/repo/.jj/repo/store/type
    [EOF]
    [exit status: 255]
    ");

    // Test when the .jj directory is empty. The error message is identical to
    // the previous one, but writing the default type file would also fail.
    work_dir.remove_dir_all(".jj");
    work_dir.create_dir(".jj");
    let output = work_dir.run_jj(["log"]);
    insta::assert_snapshot!(output.strip_stderr_last_line(), @"
    ------- stderr -------
    Internal error: The repository appears broken or inaccessible
    Caused by:
    1: Failed to read commit backend type
    2: Cannot access $TEST_ENV/repo/.jj/repo/store/type
    [EOF]
    [exit status: 255]
    ");
}

#[test]
fn test_color_config() {
    let mut test_env = TestEnvironment::default();

    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    // Test that --color=always is respected.
    let output = work_dir.run_jj(["--color=always", "log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  e8849ae12c709f2321908879bc724fdb2ab8a781
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // Test that color is used if it's requested in the config file
    test_env.add_config(r#"ui.color="always""#);
    let output = work_dir.run_jj(["log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  e8849ae12c709f2321908879bc724fdb2ab8a781
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // Test that --color=never overrides the config.
    let output = work_dir.run_jj(["--color=never", "log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  e8849ae12c709f2321908879bc724fdb2ab8a781
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // Test that --color=auto overrides the config.
    let output = work_dir.run_jj(["--color=auto", "log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  e8849ae12c709f2321908879bc724fdb2ab8a781
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // Test that --config 'ui.color=never' overrides the config.
    let output = work_dir.run_jj(["--config=ui.color=never", "log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  e8849ae12c709f2321908879bc724fdb2ab8a781
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // --color overrides --config 'ui.color=...'.
    let output = work_dir.run_jj([
        "--color",
        "never",
        "--config=ui.color=always",
        "log",
        "-T",
        "commit_id",
    ]);
    insta::assert_snapshot!(output, @"
    @  e8849ae12c709f2321908879bc724fdb2ab8a781
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // Test that NO_COLOR does NOT override the request for color in the config file
    test_env.add_env_var("NO_COLOR", "1");
    let work_dir = test_env.work_dir("repo");
    let output = work_dir.run_jj(["log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  e8849ae12c709f2321908879bc724fdb2ab8a781
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // Test that per-repo config overrides the user config.
    work_dir
        .run_jj(["config", "set", "--repo", "ui.color", "never"])
        .success();

    let output = work_dir.run_jj(["log", "-T", "commit_id"]);
    insta::assert_snapshot!(output, @"
    @  e8849ae12c709f2321908879bc724fdb2ab8a781
    ◆  0000000000000000000000000000000000000000
    [EOF]
    ");

    // Invalid --color
    let output = work_dir.run_jj(["log", "--color=foo"]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    error: invalid value 'foo' for '--color <WHEN>'
      [possible values: always, never, debug, auto]

    For more information, try '--help'.
    [EOF]
    [exit status: 2]
    ");
    // Invalid ui.color
    let stderr = work_dir.run_jj(["log", "--config=ui.color=true"]);
    insta::assert_snapshot!(stderr, @"
    ------- stderr -------
    Config error: Invalid type or value for ui.color
    Caused by: wanted string or table

    For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
    [EOF]
    [exit status: 1]
    ");
}

#[test]
fn test_pager_env_config() {
    let mut test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    test_env.add_config(r#"ui.pager = "user""#);
    test_env.add_env_var("PAGER", "env-base");
    test_env.add_env_var("JJ_PAGER", "env-override");
    let work_dir = test_env.work_dir("repo");

    let output = work_dir.run_jj(["config", "list", "ui.pager", "--include-overridden"]);
    insta::assert_snapshot!(output, @r#"
        # ui.pager = "user"
        ui.pager = "env-override"
        [EOF]
    "#);

    let output = work_dir.run_jj([
        "config",
        "list",
        "ui.pager",
        "--include-overridden",
        "--config=ui.pager=\"command-arg\"",
    ]);
    insta::assert_snapshot!(output, @r#"
        # ui.pager = "user"
        # ui.pager = "env-override"
        ui.pager = "command-arg"
        [EOF]
    "#);
}

#[test]
fn test_color_ui_messages() {
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");
    test_env.add_config("ui.color = 'always'");

    // hint and error
    let output = test_env.run_jj_in(".", ["-R."]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Hint: Use `jj -h` for a list of available commands.
    Run `jj config set --user ui.default-command log` to disable this message.
    Error: There is no jj repo in "."
    [EOF]
    [exit status: 1]
    "#);

    // error source
    let output = work_dir.run_jj(["log", ".."]);
    insta::assert_snapshot!(output.normalize_backslash(), @r#"
    ------- stderr -------
    Error: Failed to parse fileset: Invalid file pattern
    Caused by:
    1:  --> 1:1
      |
    1 | ..
      | ^^
      |
      = Invalid file pattern
    2: Path ".." is not in the repo "."
    3: Invalid component ".." in repo-relative path ".."
    [EOF]
    [exit status: 1]
    "#);

    // warning
    let output = work_dir.run_jj(["log", "@"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Warning: No matching entries for paths: @
    Warning: The argument "@" is being interpreted as a fileset expression. To specify a revset, pass -r "@" instead.
    [EOF]
    "#);

    // error inlined in template output
    work_dir.run_jj(["new"]).success();
    let output = work_dir.run_jj([
        "log",
        "-r@|@--",
        "--config=templates.log_node=commit_id",
        "-Tdescription",
    ]);
    insta::assert_snapshot!(output, @"
    8afc18ff677d32e40043e1bc8c1683c2f9c2e916
    <Error: No Commit available>  (elided revisions)
    0000000000000000000000000000000000000000
    [EOF]
    ");

    // formatted hint
    let output = work_dir.run_jj(["edit", ".."]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Error: Revset `..` resolved to more than one revision
    Hint: The revset `..` resolved to these revisions:
      mzvwutvl 8afc18ff (empty) (no description set)
      qpvuntsm e8849ae1 (empty) (no description set)
    [EOF]
    [exit status: 1]
    ");

    // commit_summary template with debugging colors
    let output = work_dir.run_jj(["st", "--color", "debug"]);
    insta::assert_snapshot!(output, @"
    The working copy has no changes.
    Working copy  (@) : <<commit working_copy change_id shortest prefix::m>><<commit working_copy change_id shortest rest::zvwutvl>><<commit working_copy:: >><<commit working_copy commit_id shortest prefix::8>><<commit working_copy commit_id shortest rest::afc18ff>><<commit working_copy:: >><<commit working_copy empty::(empty)>><<commit working_copy:: >><<commit working_copy empty description placeholder::(no description set)>>
    Parent commit (@-): <<commit change_id shortest prefix::q>><<commit change_id shortest rest::pvuntsm>><<commit:: >><<commit commit_id shortest prefix::e>><<commit commit_id shortest rest::8849ae1>><<commit:: >><<commit empty::(empty)>><<commit:: >><<commit empty description placeholder::(no description set)>>
    [EOF]
    ");

    // commit_summary template in transaction
    let output = work_dir.run_jj(["revert", "--color=debug", "-r@", "-d@"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Reverted 1 commits as follows:
      <<commit change_id shortest prefix::y>><<commit change_id shortest rest::ostqsxw>><<commit:: >><<commit commit_id shortest prefix::8b>><<commit commit_id shortest rest::f82eec>><<commit:: >><<commit empty::(empty)>><<commit:: >><<commit description first_line::Revert "">>
    [EOF]
    "#);
}

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

    // Can skip message about new working copy with `--quiet`
    work_dir.write_file("file1", "contents");
    let output = work_dir.run_jj(["--quiet", "describe", "-m=new description"]);
    insta::assert_snapshot!(output, @"");
}

#[test]
fn test_repeated_args() {
    // Repeating an argument should be harmless rather than an error, so that an
    // argument baked into an alias (or a wrapper command) can also be passed
    // explicitly. See https://github.com/jj-vcs/jj/issues/9859 and
    // https://github.com/jj-vcs/jj/issues/8101.
    let test_env = TestEnvironment::default();
    test_env.run_jj_in(".", ["git", "init", "repo"]).success();
    let work_dir = test_env.work_dir("repo");

    // `--no-pager` is parsed by the early args parser, `--ignore-working-copy`
    // is not. The repetition is accepted wherever the occurrences sit relative
    // to the subcommand.
    for flag in ["--no-pager", "--ignore-working-copy"] {
        work_dir.run_jj([flag, flag, "status"]).success();
        work_dir.run_jj([flag, "status", flag]).success();
        work_dir.run_jj(["status", flag, flag]).success();
    }

    // Arguments of subcommands are covered as well.
    let output = work_dir.run_jj(["log", "--no-graph", "-T=description"]);
    let repeated_output = work_dir.run_jj(["log", "--no-graph", "--no-graph", "-T=description"]);
    assert_eq!(repeated_output, output);

    // Repeating a flag must not disable it: `--quiet` twice still suppresses
    // the message about the new working-copy commit.
    let output = work_dir.run_jj(["--quiet", "--quiet", "describe", "-m=new description"]);
    insta::assert_snapshot!(output, @"");

    // For an option that takes a value, the last occurrence wins.
    work_dir.run_jj(["new", "-m=child"]).success();
    let output = work_dir.run_jj(["log", "--no-graph", "-T=description", "-n=1", "-n=2"]);
    insta::assert_snapshot!(output, @r"
    child
    new description
    [EOF]
    ");
    work_dir.run_jj(["status", "-R=.", "-R=."]).success();

    // Options that can be specified multiple times keep all of their values.
    let output = work_dir.run_jj([
        "--config=user.name=Custom User",
        "--config=user.email=custom@example.com",
        "config",
        "list",
        "user",
    ]);
    insta::assert_snapshot!(output, @r#"
    user.name = "Custom User"
    user.email = "custom@example.com"
    [EOF]
    "#);
    let output = work_dir.run_jj(["log", "--no-graph", "-T=description", "-r=@", "-r=@-"]);
    insta::assert_snapshot!(output, @r"
    child
    new description
    [EOF]
    ");
}

#[test]
fn test_early_args() {
    // Test that help output parses early args
    let test_env = TestEnvironment::default();

    // The default is no color.
    let output = test_env.run_jj_in(".", ["help"]).success();
    insta::assert_snapshot!(
        output.stdout.normalized().lines().find(|l| l.contains("Commands:")).unwrap(),
        @"Commands:");

    // Check that output is colorized.
    let output = test_env
        .run_jj_in(".", ["--color=always", "help"])
        .success();
    insta::assert_snapshot!(
        output.stdout.normalized().lines().find(|l| l.contains("Commands:")).unwrap(),
        @"Commands:");

    // Check that early args are accepted after the help command
    let output = test_env
        .run_jj_in(".", ["help", "--color=always"])
        .success();
    insta::assert_snapshot!(
        output.stdout.normalized().lines().find(|l| l.contains("Commands:")).unwrap(),
        @"Commands:");

    // Check that early args are accepted after -h/--help
    let output = test_env.run_jj_in(".", ["-h", "--color=always"]).success();
    insta::assert_snapshot!(
        output.stdout.normalized().lines().find(|l| l.contains("Usage:")).unwrap(),
        @"Usage: jj [OPTIONS] <COMMAND>");
    let output = test_env
        .run_jj_in(".", ["log", "--help", "--color=always"])
        .success();
    insta::assert_snapshot!(
        output.stdout.normalized().lines().find(|l| l.contains("Usage:")).unwrap(),
        @"Usage: jj log [OPTIONS] [FILESETS]...");

    // Early args are parsed with clap's ignore_errors(), but there is a known
    // bug that causes defaults to be unpopulated. Test that the early args are
    // tolerant of this bug and don't cause a crash.
    test_env.run_jj_in(".", ["--no-pager", "help"]).success();
    test_env
        .run_jj_in(".", ["--config=ui.color=always", "help"])
        .success();
}

#[test]
fn test_config_args() -> TestResult {
    let test_env = TestEnvironment::default();
    let list_config = |args: &[&str]| {
        test_env.run_jj_in(
            ".",
            [&["config", "list", "--include-overridden", "test"], args].concat(),
        )
    };

    std::fs::write(
        test_env.env_root().join("file1.toml"),
        indoc! {"
            test.key1 = 'file1'
            test.key2 = 'file1'
        "},
    )?;
    std::fs::write(
        test_env.env_root().join("file2.toml"),
        indoc! {"
            test.key3 = 'file2'
        "},
    )?;

    let output = list_config(&["--config=test.key1=arg1"]);
    insta::assert_snapshot!(output, @r#"
    test.key1 = "arg1"
    [EOF]
    "#);
    let output = list_config(&["--config-file=file1.toml"]);
    insta::assert_snapshot!(output, @"
    test.key1 = 'file1'
    test.key2 = 'file1'
    [EOF]
    ");

    // --config items are inserted to a single layer internally
    let output = list_config(&[
        "--config=test.key1='arg1'",
        "--config=test.key2.sub=true",
        "--config=test.key1=arg3",
    ]);
    insta::assert_snapshot!(output, @r#"
    test.key1 = "arg3"
    test.key2.sub = true
    [EOF]
    "#);

    // --config* arguments are processed in order of appearance
    let output = list_config(&[
        "--config=test.key1=arg1",
        "--config-file=file1.toml",
        "--config=test.key2=arg3",
        "--config-file=file2.toml",
    ]);
    insta::assert_snapshot!(output, @r#"
    # test.key1 = "arg1"
    test.key1 = 'file1'
    # test.key2 = 'file1'
    test.key2 = "arg3"
    test.key3 = 'file2'
    [EOF]
    "#);

    let output = test_env.run_jj_in(".", ["config", "list", "--config=foo"]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Config error: --config must be specified as NAME=VALUE
    For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
    [EOF]
    [exit status: 1]
    ");

    let output = test_env.run_jj_in(".", ["config", "list", "--config-file=unknown.toml"]);
    insta::with_settings!({
        filters => [("(?m)^([2-9]): .*", "$1: <redacted>")],
    }, {
        insta::assert_snapshot!(output, @"
        ------- stderr -------
        Config error: Failed to read configuration file
        Caused by:
        1: Cannot access unknown.toml
        2: <redacted>
        For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
        [EOF]
        [exit status: 1]
        ");
    });
    Ok(())
}

#[test]
fn test_invalid_config() {
    // Test that we get a reasonable error if the config is invalid (#55)
    let test_env = TestEnvironment::default();

    test_env.add_config("[section]key = value-missing-quotes");
    let output = test_env.run_jj_in(".", ["git", "init", "repo"]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Config error: Configuration cannot be parsed as TOML document
    Caused by: TOML parse error at line 1, column 10
      |
    1 | [section]key = value-missing-quotes
      |          ^
    unexpected key or value, expected newline, `#`

    Hint: Check the config file: $TEST_ENV/config/config0002.toml
    For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
    [EOF]
    [exit status: 1]
    ");
}

#[test]
fn test_invalid_config_value() {
    // Test that we get a reasonable error if a config value is invalid
    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(["status", "--config=snapshot.auto-track=[0]"]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Config error: Invalid type or value for snapshot.auto-track
    Caused by: invalid type: sequence, expected a string

    For help, see https://docs.jj-vcs.dev/latest/config/ or use `jj help -k config`.
    [EOF]
    [exit status: 1]
    ");
}

#[test]
#[cfg_attr(windows, ignore = "dirs::home_dir() can't be overridden by $HOME")] // TODO
fn test_conditional_config() {
    let test_env = TestEnvironment::default();
    test_env
        .run_jj_in(test_env.home_dir(), ["git", "init", "repo1"])
        .success();
    test_env
        .run_jj_in(test_env.home_dir(), ["git", "init", "repo2"])
        .success();
    test_env.add_config(indoc! {"
        aliases.foo = ['new', 'root()', '-mglobal']
        [[--scope]]
        --when.repositories = ['~']
        aliases.foo = ['new', 'root()', '-mhome']
        [[--scope]]
        --when.repositories = ['~/repo1']
        aliases.foo = ['new', 'root()', '-mrepo1']
    "});

    // Sanity check
    let output = test_env.run_jj_in(".", ["config", "list", "--include-overridden", "aliases"]);
    insta::assert_snapshot!(output, @"
    aliases.foo = ['new', 'root()', '-mglobal']
    [EOF]
    ");
    let output = test_env.run_jj_in(
        &test_env.home_dir().join("repo1"),
        ["config", "list", "--include-overridden", "aliases"],
    );
    insta::assert_snapshot!(output, @"
    # aliases.foo = ['new', 'root()', '-mglobal']
    # aliases.foo = ['new', 'root()', '-mhome']
    aliases.foo = ['new', 'root()', '-mrepo1']
    [EOF]
    ");
    let output = test_env.run_jj_in(
        &test_env.home_dir().join("repo2"),
        ["config", "list", "--include-overridden", "aliases"],
    );
    insta::assert_snapshot!(output, @"
    # aliases.foo = ['new', 'root()', '-mglobal']
    aliases.foo = ['new', 'root()', '-mhome']
    [EOF]
    ");

    // Aliases can be expanded by using the conditional tables
    let output = test_env.run_jj_in(&test_env.home_dir().join("repo1"), ["foo"]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Working copy  (@) now at: royxmykx 7c486962 (empty) repo1
    Parent commit (@-)      : zzzzzzzz 00000000 (empty) (no description set)
    [EOF]
    ");
    let output = test_env.run_jj_in(&test_env.home_dir().join("repo2"), ["foo"]);
    insta::assert_snapshot!(output, @"
    ------- stderr -------
    Working copy  (@) now at: yqosqzyt 072741b8 (empty) home
    Parent commit (@-)      : zzzzzzzz 00000000 (empty) (no description set)
    [EOF]
    ");
}

#[test]
fn test_conditional_config_environments() {
    let mut test_env = TestEnvironment::default();
    test_env
        .run_jj_in(test_env.home_dir(), ["git", "init", "repo"])
        .success();
    let repo_dir = test_env.home_dir().join("repo");
    test_env.add_config(indoc! {"
        ui.pager = 'base'
        [[--scope]]
        --when.environments = ['MY_JJ_ENV=on']
        ui.pager = 'kv-match'
        [[--scope]]
        --when.environments = ['MY_JJ_ENV']
        ui.pager = 'key-exists'
        [[--scope]]
        --when.environments = ['ABSENT_VAR']
        ui.pager = 'absent'
    "});

    test_env.add_env_var("MY_JJ_ENV", "on");
    let output = test_env.run_jj_in(
        &repo_dir,
        ["config", "list", "--include-overridden", "ui.pager"],
    );
    insta::assert_snapshot!(output, @r"
    # ui.pager = 'base'
    # ui.pager = 'kv-match'
    ui.pager = 'key-exists'
    [EOF]
    ");
}

/// Test that `jj` command works with the default configuration.
#[test]
fn test_default_config() -> TestResult {
    let mut test_env = TestEnvironment::default();
    let config_dir = test_env.env_root().join("empty-config");
    std::fs::create_dir(&config_dir)?;
    test_env.set_config_path(&config_dir);

    let envs_to_drop = test_env
        .new_jj_cmd()
        .get_envs()
        .filter_map(|(name, _)| name.to_str())
        .filter(|&name| name.starts_with("JJ_") && name != "JJ_CONFIG")
        .map(|name| name.to_owned())
        .sorted_unstable()
        .collect_vec();
    insta::assert_debug_snapshot!(envs_to_drop, @r#"
    [
        "JJ_EMAIL",
        "JJ_OP_HOSTNAME",
        "JJ_OP_TIMESTAMP",
        "JJ_OP_USERNAME",
        "JJ_RANDOMNESS_SEED",
        "JJ_TIMESTAMP",
        "JJ_TZ_OFFSET_MINS",
        "JJ_USER",
    ]
    "#);
    let run_jj = |work_dir: &TestWorkDir, args: &[&str]| {
        work_dir.run_jj_with(|cmd| {
            for name in &envs_to_drop {
                cmd.env_remove(name);
            }
            cmd.args(args)
        })
    };

    let mut insta_settings = insta::Settings::clone_current();
    insta_settings.add_filter(r"\b[a-zA-Z0-9\-._]+@[a-zA-Z0-9\-._]+\b", "<user>@<host>");
    insta_settings.add_filter(
        r"\b[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\b",
        "<date-time>",
    );
    insta_settings.add_filter(r"\b[k-z]{8,12}\b", "<change-id>");
    insta_settings.add_filter(r"\b[0-9a-f]{8,12}\b", "<id>");
    let _guard = insta_settings.bind_to_scope();

    let maskable_op_user = {
        let maskable_re = Regex::new(r"^[a-zA-Z0-9\-._]+$")?;
        let hostname = whoami::hostname().expect("hostname should be set");
        let username = whoami::username().expect("username should be set");
        maskable_re.is_match(&hostname) && maskable_re.is_match(&username)
    };

    let output = run_jj(
        &test_env.work_dir(""),
        &["config", "list", r#"-Tname ++ "\n""#],
    );
    insta::assert_snapshot!(output, @"
    operation.hostname
    operation.username
    [EOF]
    ");

    let output = run_jj(&test_env.work_dir(""), &["git", "init", "repo"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Initialized repo in "repo"
    [EOF]
    "#);

    let work_dir = test_env.work_dir("repo");
    let output = run_jj(&work_dir, &["new"]);
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Working copy  (@) now at: <change-id> <id> (empty) (no description set)
    Parent commit (@-)      : <change-id> <id> (empty) (no description set)
    Warning: Name and email not configured. Until configured, your commits will be created with the empty identity, and can't be pushed to remotes.
    Hint: To configure, run:
      jj config set --user user.name "Some One"
      jj config set --user user.email "<user>@<host>"
    [EOF]
    "#);

    let output = run_jj(&work_dir, &["log"]);
    insta::assert_snapshot!(output, @"
    @  <change-id> (no email set) <date-time> <id>
    │  (empty) (no description set)
    ○  <change-id> (no email set) <date-time> <id>
    │  (empty) (no description set)
    ◆  <change-id> root() <id>
    [EOF]
    ");

    let time_config =
        "--config=template-aliases.'format_time_range(t)'='format_timestamp(t.end())'";
    let output = run_jj(&work_dir, &["op", "log", time_config]);
    if maskable_op_user {
        insta::assert_snapshot!(output, @"
        @  <id> <user>@<host> default@ <date-time>
        │  new empty commit
        │  args: jj new
        ○  <id> <user>@<host> <date-time>
        │  add workspace 'default'
        ○  <id> root()
        [EOF]
        ");
    }
    Ok(())
}

#[test]
fn test_no_user_configured() {
    // Test that the user is reminded if they haven't configured their name or email
    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_with(|cmd| {
        cmd.args(["describe", "-m", "without name"])
            .env_remove("JJ_USER")
    });
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Working copy  (@) now at: qpvuntsm 7e7014c2 (empty) without name
    Parent commit (@-)      : zzzzzzzz 00000000 (empty) (no description set)
    Warning: Name not configured. Until configured, your commits will be created with the empty identity, and can't be pushed to remotes.
    Hint: To configure, run:
      jj config set --user user.name "Some One"
    [EOF]
    "#);
    let output = work_dir.run_jj_with(|cmd| {
        cmd.args(["describe", "-m", "without email"])
            .env_remove("JJ_EMAIL")
    });
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Working copy  (@) now at: qpvuntsm 876580e3 (empty) without email
    Parent commit (@-)      : zzzzzzzz 00000000 (empty) (no description set)
    Warning: Email not configured. Until configured, your commits will be created with the empty identity, and can't be pushed to remotes.
    Hint: To configure, run:
      jj config set --user user.email "someone@example.com"
    [EOF]
    "#);
    let output = work_dir.run_jj_with(|cmd| {
        cmd.args(["describe", "-m", "without name and email"])
            .env_remove("JJ_USER")
            .env_remove("JJ_EMAIL")
    });
    insta::assert_snapshot!(output, @r#"
    ------- stderr -------
    Working copy  (@) now at: qpvuntsm f87356a1 (empty) without name and email
    Parent commit (@-)      : zzzzzzzz 00000000 (empty) (no description set)
    Warning: Name and email not configured. Until configured, your commits will be created with the empty identity, and can't be pushed to remotes.
    Hint: To configure, run:
      jj config set --user user.name "Some One"
      jj config set --user user.email "someone@example.com"
    [EOF]
    "#);
}

#[test]
fn test_help() {
    // Test that global options are separated out in the help output
    let test_env = TestEnvironment::default();

    let output = test_env.run_jj_in(".", ["diffedit", "-h"]);
    insta::assert_snapshot!(output, @"
    Touch up the content changes in a revision with a diff editor

    Usage: jj diffedit [OPTIONS] [FILESETS]...

    Arguments:
      [FILESETS]...  Edit only these paths (unmatched paths will remain unchanged)

    Options:
      -r, --revision <REVSET>    The revision to touch up
      -f, --from <REVSET>        Show changes from this revision
      -t, --to <REVSET>          Edit changes in this revision
          --tool <NAME>          Specify diff editor to be used
          --restore-descendants  Preserve the content (not the diff) when rebasing descendants
      -h, --help                 Print help (see more with '--help')

    Global Options:
      -R, --repository <REPOSITORY>      Path to repository to operate on
          --ignore-working-copy          Don't snapshot the working copy, and don't update it
          --no-integrate-operation       Run the command as usual but don't integrate any operations
          --ignore-immutable             Allow rewriting immutable commits
          --at-operation <AT_OPERATION>  Operation to load the repo at [alias: --at-op]
          --debug                        Enable debug logging
          --color <WHEN>                 When to colorize output [possible values: always, never, debug,
                                         auto]
          --quiet                        Silence non-primary command output
          --no-pager                     Disable the pager
          --config <NAME=VALUE>          Additional configuration options (can be repeated)
          --config-file <PATH>           Additional configuration files (can be repeated)
    [EOF]
    ");
}

#[test]
fn test_debug_logging_enabled() {
    // Test that the debug flag enabled debug logging
    let test_env = TestEnvironment::default();

    let output = test_env.run_jj_in(".", ["version", "--debug"]).success();
    // Split the first log line into a timestamp and the rest.
    // The timestamp is constant sized so this is a robust operation.
    // Example timestamp: 2022-11-20T06:24:05.477703Z
    let (_timestamp, log_line) = output
        .stderr
        .normalized()
        .lines()
        .next()
        .expect("debug logging on first line")
        .split_at(36);
    // The log format is currently Pretty so we include the terminal markup.
    // Luckily, insta will print this in color when reviewing.
    insta::assert_snapshot!(log_line, @" INFO jj_cli::cli_util: debug logging enabled");
}