quinjet 0.0.9

A fast, live, keyboard-first Git source-control interface for the terminal
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
pub(crate) mod command;
mod render;
mod watch;

use std::collections::HashMap;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;

use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand};
pub(crate) use command::{Command, Outcome, Session};
use serde::Serialize;

use crate::git::diff::{DiffDocument, DiffIndex};
use crate::git::github::{
    GitHubRepository, PullRequest, PullRequestCheck, PullRequestCheckStatus, PullRequestDiffIndex,
};
use crate::git::status::{Change, ChangeArea};
use crate::git::{ConflictChoice, GitOperation, LocalDiffRequest, Repository};

pub(crate) const EXIT_FAILURE: u8 = 1;
pub(crate) const EXIT_NOT_FOUND: u8 = 3;
pub(crate) const EXIT_UNAVAILABLE: u8 = 4;

const CHECK_WATCH_INTERVAL: u64 = 5;
const CHECK_WATCH_FLOOR: u64 = 2;
const LOG_WATCH_INTERVAL: u64 = 8;
const LOG_WATCH_FLOOR: u64 = 3;

#[derive(Debug)]
pub(crate) struct Failure {
    pub code: u8,
    pub message: String,
    pub hint: Option<String>,
}

impl Failure {
    pub(crate) fn new(code: u8, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            hint: None,
        }
    }

    pub(crate) fn hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }
}

impl std::fmt::Display for Failure {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}", self.message)
    }
}

impl std::error::Error for Failure {}

pub(crate) struct TerminalOptions {
    pub path: PathBuf,
    pub no_mouse: bool,
    pub webhook_listen: Option<String>,
}

#[expect(
    variant_size_differences,
    reason = "the terminal options are already boxed; the only way to level this is to box one byte"
)]
pub(crate) enum Launch {
    Terminal(Box<TerminalOptions>),
    Finished(u8),
}

#[derive(Debug, Parser)]
#[command(name = "quinjet", version, about)]
#[command(subcommand_negates_reqs = true)]
struct Cli {
    #[command(subcommand)]
    command: Option<Verb>,

    /// Git repository to open in the terminal interface
    #[arg(default_value = ".")]
    path: PathBuf,

    /// Disable mouse capture (all features remain keyboard-accessible)
    #[arg(long)]
    no_mouse: bool,

    /// Refresh the open pull request the moment a forwarded GitHub webhook
    /// arrives, given a port or host:port to listen on. Pair with
    /// `gh webhook forward --repo <repo> --events '*' --url http://127.0.0.1:<port>`.
    /// Only loopback connections are accepted.
    #[arg(long, value_name = "ADDRESS")]
    webhook_listen: Option<String>,

    /// Repository to run a subcommand against
    #[arg(
        short = 'C',
        long = "path",
        value_name = "DIR",
        default_value = ".",
        global = true
    )]
    repository: PathBuf,

    /// Print one JSON document on stdout instead of text
    #[arg(long, global = true)]
    json: bool,
}

#[derive(Debug, Subcommand)]
enum Verb {
    /// Open the terminal interface
    Tui(TuiArgs),
    /// Show the working tree, the index and the branch
    Status(WatchableArgs),
    /// Print the working-tree diff
    Diff(DiffArgs),
    /// Stage paths, or everything
    Stage(SelectionArgs),
    /// Unstage paths, or everything
    Unstage(SelectionArgs),
    /// Throw away changes to paths
    Discard(DiscardArgs),
    /// Record the staged changes
    Commit(CommitArgs),
    /// Fetch every remote and prune deleted refs
    Fetch,
    /// Pull the current branch
    Pull,
    /// Push the current branch
    Push,
    /// Pull, then push
    Sync,
    /// List commits
    Log(LogArgs),
    /// Show one commit and its patch
    Show(ShowArgs),
    /// Work with branches
    Branch {
        #[command(subcommand)]
        command: BranchVerb,
    },
    /// Work with stashes
    Stash {
        #[command(subcommand)]
        command: StashVerb,
    },
    /// Apply a commit onto the current branch
    CherryPick(RevisionArgs),
    /// Record a commit that undoes another
    Revert(RevisionArgs),
    /// Take one side of a merge conflict
    Resolve(ResolveArgs),
    /// List the GitHub repositories this checkout points at
    Repos(ReposArgs),
    /// Read a pull request, its files, its conversation and its checks
    Pr {
        #[command(subcommand)]
        command: PrVerb,
    },
}

#[derive(Debug, Args)]
struct TuiArgs {
    /// Git repository to open
    #[arg(default_value = ".")]
    path: PathBuf,
    /// Disable mouse capture
    #[arg(long)]
    no_mouse: bool,
    /// Listen for forwarded GitHub webhooks on a port or host:port
    #[arg(long, value_name = "ADDRESS")]
    webhook_listen: Option<String>,
}

#[derive(Debug, Args)]
struct WatchableArgs {
    /// Keep the reading on screen and refresh it
    #[arg(long)]
    watch: bool,
    /// Seconds between refreshes
    #[arg(long, value_name = "SECONDS", default_value_t = 2)]
    interval: u64,
}

#[derive(Debug, Args)]
struct DiffArgs {
    /// Limit the diff to these paths
    paths: Vec<PathBuf>,
    /// Only what is staged
    #[arg(long)]
    staged: bool,
    /// Only what is not staged
    #[arg(long, conflicts_with = "staged")]
    unstaged: bool,
    /// Print whole files instead of three lines of context
    #[arg(long)]
    expanded: bool,
}

#[derive(Debug, Args)]
struct SelectionArgs {
    /// Paths to act on
    paths: Vec<PathBuf>,
    /// Act on every change instead
    #[arg(long, conflicts_with = "paths")]
    all: bool,
}

#[derive(Debug, Args)]
struct DiscardArgs {
    /// Paths whose changes are thrown away
    paths: Vec<PathBuf>,
    /// Throw away every change instead
    #[arg(long, conflicts_with = "paths")]
    all: bool,
    /// Confirm; without it the command reports what it would discard
    #[arg(long)]
    yes: bool,
}

#[derive(Debug, Args)]
struct CommitArgs {
    /// Commit message
    #[arg(short, long)]
    message: String,
    /// Replace the previous commit
    #[arg(long)]
    amend: bool,
}

#[derive(Debug, Args)]
struct LogArgs {
    /// Branch, tag, or commit to read from
    #[arg(default_value = "HEAD")]
    revision: String,
    /// Commits to skip
    #[arg(long, default_value_t = 0)]
    skip: usize,
    /// Commits to print
    #[arg(long, short = 'n', default_value_t = 30)]
    limit: usize,
}

#[derive(Debug, Args)]
struct ShowArgs {
    /// Commit to show
    #[arg(default_value = "HEAD")]
    revision: String,
    /// Print whole files instead of three lines of context
    #[arg(long)]
    expanded: bool,
}

#[derive(Debug, Args)]
struct RevisionArgs {
    /// Commit to apply
    revision: String,
}

#[derive(Debug, Args)]
struct ResolveArgs {
    /// Conflicted path
    path: PathBuf,
    /// Keep the version already on this branch
    #[arg(long, group = "side")]
    ours: bool,
    /// Keep the version being merged in
    #[arg(long, group = "side")]
    theirs: bool,
    /// Accept the file as it stands and stage it
    #[arg(long, group = "side")]
    stage: bool,
}

#[derive(Debug, Args)]
struct ReposArgs {
    /// Read the remotes again instead of answering from the cache
    #[arg(long)]
    refresh: bool,
}

#[derive(Debug, Subcommand)]
enum BranchVerb {
    /// List local branches
    List(BranchListArgs),
    /// Switch to a branch
    Switch { name: String },
    /// Create a branch and switch to it
    Create {
        name: String,
        /// Commit to branch from
        start: Option<String>,
    },
    /// Rename a branch
    Rename { old: String, new: String },
    /// Delete a branch
    Delete {
        name: String,
        /// Confirm; without it the command reports what it would delete
        #[arg(long)]
        yes: bool,
    },
    /// Diff a branch against the current one without checking anything out
    Compare {
        reference: String,
        /// Print whole files instead of three lines of context
        #[arg(long)]
        expanded: bool,
    },
}

#[derive(Debug, Args)]
struct BranchListArgs {
    /// Include remote-tracking branches
    #[arg(long)]
    all: bool,
}

#[derive(Debug, Subcommand)]
enum StashVerb {
    /// List stashes
    List,
    /// Stash the current changes
    Push {
        /// Message to record
        #[arg(short, long, default_value = "")]
        message: String,
        /// Include untracked files
        #[arg(long)]
        include_untracked: bool,
        /// Stash only what is staged
        #[arg(long, conflicts_with = "include_untracked")]
        staged: bool,
    },
    /// Apply a stash and keep it
    Apply { reference: String },
    /// Apply a stash and drop it
    Pop { reference: Option<String> },
    /// Drop a stash
    Drop {
        reference: String,
        /// Confirm; without it the command reports what it would drop
        #[arg(long)]
        yes: bool,
    },
    /// Drop every stash
    Clear {
        /// Confirm; without it the command reports what it would drop
        #[arg(long)]
        yes: bool,
    },
    /// Print a stash as a patch
    Show {
        reference: String,
        /// Print whole files instead of three lines of context
        #[arg(long)]
        expanded: bool,
    },
}

#[derive(Debug, Subcommand)]
enum PrVerb {
    /// Print a pull request's metadata and description
    View(PrArgs),
    /// List the files a pull request changes
    Files(PrArgs),
    /// Print a pull request's patch
    Diff(PrDiffArgs),
    /// Print a pull request's timeline and review comments
    Conversation(PrArgs),
    /// List a pull request's checks
    Checks(PrChecksArgs),
    /// Print one check run's steps and log
    Logs(PrLogsArgs),
    /// Open a pull request in a browser
    Open(PrArgs),
}

#[derive(Debug, Args)]
struct PrArgs {
    /// Pull-request number
    number: u64,
    /// Repository the number belongs to, as owner/name
    #[arg(long, value_name = "OWNER/NAME")]
    repo: Option<String>,
    /// Ask GitHub again instead of answering from the cache
    #[arg(long)]
    refresh: bool,
}

#[derive(Debug, Args)]
struct PrDiffArgs {
    #[command(flatten)]
    pull_request: PrArgs,
    /// Limit the patch to one path
    path: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct PrChecksArgs {
    #[command(flatten)]
    pull_request: PrArgs,
    /// Keep reading until every check has settled
    #[arg(long)]
    watch: bool,
    /// Seconds between reads while watching
    #[arg(long, value_name = "SECONDS", default_value_t = CHECK_WATCH_INTERVAL)]
    interval: u64,
    /// Exit 1 when a check has not passed
    #[arg(long)]
    exit_code: bool,
}

#[derive(Debug, Args)]
struct PrLogsArgs {
    #[command(flatten)]
    pull_request: PrArgs,
    /// Check run to read, by name
    check: String,
    /// Keep reading while the run is still going
    #[arg(long)]
    watch: bool,
    /// Seconds between reads while watching
    #[arg(long, value_name = "SECONDS", default_value_t = LOG_WATCH_INTERVAL)]
    interval: u64,
}

pub(crate) fn dispatch() -> Result<Launch> {
    let cli = Cli::parse();
    let json = cli.json;
    let Some(verb) = cli.command else {
        return Ok(Launch::Terminal(Box::new(TerminalOptions {
            path: cli.path,
            no_mouse: cli.no_mouse,
            webhook_listen: cli.webhook_listen,
        })));
    };
    if let Verb::Tui(args) = verb {
        return Ok(Launch::Terminal(Box::new(TerminalOptions {
            path: args.path,
            no_mouse: args.no_mouse,
            webhook_listen: args.webhook_listen,
        })));
    }
    let repository = Repository::discover(&cli.repository)?;
    let mut session = Session::new(repository);
    let out = Emitter { json };
    run(&mut session, &out, verb).map(Launch::Finished)
}

struct Emitter {
    json: bool,
}

impl Emitter {
    fn emit<T: Serialize>(&self, value: &T, text: impl FnOnce() -> String) -> Result<()> {
        let mut stdout = io::stdout().lock();
        if self.json {
            writeln!(stdout, "{}", serde_json::to_string_pretty(value)?)?;
        } else {
            write!(stdout, "{}", text())?;
        }
        stdout.flush()?;
        Ok(())
    }

    fn message(&self, message: &str) -> Result<()> {
        self.emit(&Message { message }, || format!("{message}\n"))
    }
}

#[derive(Serialize)]
struct Message<'a> {
    message: &'a str,
}

fn run(session: &mut Session, out: &Emitter, verb: Verb) -> Result<u8> {
    match verb {
        Verb::Tui(_) => Err(Failure::new(
            EXIT_FAILURE,
            "the terminal interface is launched before any verb runs",
        )
        .into()),
        Verb::Status(args) => status(session, out, &args),
        Verb::Diff(args) => working_diff(session, out, &args),
        Verb::Stage(args) => {
            let operation = if args.all {
                GitOperation::StageAll
            } else {
                GitOperation::Stage(require_paths(args.paths, "stage")?)
            };
            operate(session, out, operation)
        }
        Verb::Unstage(args) => {
            let operation = if args.all {
                GitOperation::UnstageAll
            } else {
                GitOperation::Unstage(require_paths(args.paths, "unstage")?)
            };
            operate(session, out, operation)
        }
        Verb::Discard(args) => discard(session, out, &args),
        Verb::Commit(args) => operate(
            session,
            out,
            GitOperation::Commit {
                message: args.message,
                amend: args.amend,
            },
        ),
        Verb::Fetch => operate(session, out, GitOperation::Fetch),
        Verb::Pull => operate(session, out, GitOperation::Pull),
        Verb::Push => operate(session, out, GitOperation::Push),
        Verb::Sync => operate(session, out, GitOperation::Sync),
        Verb::Log(args) => log(session, out, &args),
        Verb::Show(args) => show(session, out, &args),
        Verb::Branch { command } => branch(session, out, command),
        Verb::Stash { command } => stash(session, out, command),
        Verb::CherryPick(args) => {
            let revision = revision(session, &args.revision)?;
            operate(session, out, GitOperation::CherryPick(revision))
        }
        Verb::Revert(args) => {
            let revision = revision(session, &args.revision)?;
            operate(session, out, GitOperation::Revert(revision))
        }
        Verb::Resolve(args) => resolve(session, out, args),
        Verb::Repos(args) => repositories(session, out, &args),
        Verb::Pr { command } => pull_request(session, out, command),
    }
}

fn status(session: &mut Session, out: &Emitter, args: &WatchableArgs) -> Result<u8> {
    if args.watch {
        return watch::run(interval(args.interval, 1), out.json, || {
            let status = session.execute(Command::Status)?.status()?;
            Ok(watch::Frame {
                text: render::status(&status),
                value: status,
                finished: false,
                code: 0,
            })
        });
    }
    let status = session.execute(Command::Status)?.status()?;
    out.emit(&status, || render::status(&status))?;
    Ok(0)
}

fn working_diff(session: &mut Session, out: &Emitter, args: &DiffArgs) -> Result<u8> {
    let status = session.execute(Command::Status)?.status()?;
    let changes: Vec<Change> = status
        .changes
        .iter()
        .filter(|change| match (args.staged, args.unstaged) {
            (true, _) => change.area == ChangeArea::Staged,
            (_, true) => change.area == ChangeArea::Unstaged,
            _ => true,
        })
        .filter(|change| matches(&change.path, &args.paths))
        .cloned()
        .collect();
    if changes.is_empty() {
        out.message("No changes match")?;
        return Ok(0);
    }
    let document = whole_document(
        session,
        Command::PrepareLocalDiff {
            workspace: 0,
            request: Box::new(LocalDiffRequest::Changes {
                changes,
                version: 0,
                expanded: args.expanded,
            }),
        },
        |workspace, path| Command::LocalDiffFile { workspace, path },
    )?;
    out.emit(&document, || render::diff(&document))?;
    Ok(0)
}

fn log(session: &mut Session, out: &Emitter, args: &LogArgs) -> Result<u8> {
    let revision = revision(session, &args.revision)?;
    let commits = session
        .execute(Command::History {
            revision,
            skip: args.skip,
            limit: args.limit,
        })?
        .history()?;
    out.emit(&commits, || render::history(&commits))?;
    Ok(0)
}

fn show(session: &mut Session, out: &Emitter, args: &ShowArgs) -> Result<u8> {
    let revision = revision(session, &args.revision)?;
    let commits = session
        .execute(Command::History {
            revision: revision.clone(),
            skip: 0,
            limit: 1,
        })?
        .history()?;
    let Some(commit) = commits.into_iter().next() else {
        return Err(Failure::new(
            EXIT_NOT_FOUND,
            format!("`{revision}` does not name a commit in this repository"),
        )
        .into());
    };
    let document = whole_document(
        session,
        Command::PrepareLocalDiff {
            workspace: 0,
            request: Box::new(LocalDiffRequest::Commit {
                commit: Box::new(commit.clone()),
                expanded: args.expanded,
            }),
        },
        |workspace, path| Command::LocalDiffFile { workspace, path },
    )?;
    out.emit(
        &CommitPatch {
            commit: &commit,
            diff: &document,
        },
        || format!("{}{}", render::commit(&commit), render::diff(&document)),
    )?;
    Ok(0)
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CommitPatch<'a> {
    commit: &'a crate::git::history::Commit,
    diff: &'a DiffDocument,
}

fn branch(session: &mut Session, out: &Emitter, command: BranchVerb) -> Result<u8> {
    match command {
        BranchVerb::List(args) if args.all => {
            let branches = session
                .execute(Command::HistoryBranches)?
                .history_branches()?;
            out.emit(&branches, || render::history_branches(&branches))?;
            Ok(0)
        }
        BranchVerb::List(_) => {
            let branches = session.execute(Command::Branches)?.branches()?;
            out.emit(&branches, || render::branches(&branches))?;
            Ok(0)
        }
        BranchVerb::Switch { name } => operate(session, out, GitOperation::Checkout(name)),
        BranchVerb::Create { name, start } => {
            let start = match start {
                Some(start) => Some(revision(session, &start)?),
                None => None,
            };
            operate(session, out, GitOperation::CreateBranch { name, start })
        }
        BranchVerb::Rename { old, new } => {
            operate(session, out, GitOperation::RenameBranch { old, new })
        }
        BranchVerb::Delete { name, yes } => {
            if !yes {
                out.message(&format!("Would delete `{name}`. Pass --yes to delete it."))?;
                return Ok(0);
            }
            operate(session, out, GitOperation::DeleteBranch(name))
        }
        BranchVerb::Compare {
            reference,
            expanded,
        } => compare(session, out, &reference, expanded),
    }
}

fn compare(session: &mut Session, out: &Emitter, reference: &str, expanded: bool) -> Result<u8> {
    let branches = session
        .execute(Command::HistoryBranches)?
        .history_branches()?;
    let Some(branch) = branches
        .iter()
        .find(|branch| branch.name == reference || branch.reference == reference)
    else {
        return Err(Failure::new(
            EXIT_NOT_FOUND,
            format!("`{reference}` does not name a branch in this repository"),
        )
        .hint("run `quinjet branch list --all` for the branches that exist")
        .into());
    };
    let status = session.execute(Command::Status)?.status()?;
    let document = whole_document(
        session,
        Command::PrepareLocalDiff {
            workspace: 0,
            request: Box::new(LocalDiffRequest::Branch {
                branch: Box::new(branch.clone()),
                current: status.branch.head.clone(),
                current_oid: status.branch.oid,
                expanded,
            }),
        },
        |workspace, path| Command::LocalDiffFile { workspace, path },
    )?;
    out.emit(&document, || render::diff(&document))?;
    Ok(0)
}

fn stash(session: &mut Session, out: &Emitter, command: StashVerb) -> Result<u8> {
    match command {
        StashVerb::List => {
            let stashes = session.execute(Command::Stashes)?.stashes()?;
            out.emit(&stashes, || render::stashes(&stashes))?;
            Ok(0)
        }
        StashVerb::Push {
            message,
            include_untracked,
            staged,
        } => operate(
            session,
            out,
            GitOperation::StashPush {
                message,
                include_untracked,
                staged,
            },
        ),
        StashVerb::Apply { reference } => {
            operate(session, out, GitOperation::StashApply(reference))
        }
        StashVerb::Pop { reference } => operate(session, out, GitOperation::StashPop(reference)),
        StashVerb::Drop { reference, yes } => {
            if !yes {
                out.message(&format!("Would drop `{reference}`. Pass --yes to drop it."))?;
                return Ok(0);
            }
            operate(session, out, GitOperation::StashDrop(reference))
        }
        StashVerb::Clear { yes } => {
            if !yes {
                let stashes = session.execute(Command::Stashes)?.stashes()?;
                out.message(&format!(
                    "Would drop {} stashes. Pass --yes to drop them.",
                    stashes.len()
                ))?;
                return Ok(0);
            }
            operate(session, out, GitOperation::StashClear)
        }
        StashVerb::Show {
            reference,
            expanded,
        } => {
            let stashes = session.execute(Command::Stashes)?.stashes()?;
            let Some(stash) = stashes.iter().find(|stash| stash.reference == reference) else {
                return Err(Failure::new(
                    EXIT_NOT_FOUND,
                    format!("`{reference}` does not name a stash in this repository"),
                )
                .hint("run `quinjet stash list` for the stashes that exist")
                .into());
            };
            let document = whole_document(
                session,
                Command::PrepareLocalDiff {
                    workspace: 0,
                    request: Box::new(LocalDiffRequest::Stash {
                        stash: Box::new(stash.clone()),
                        expanded,
                    }),
                },
                |workspace, path| Command::LocalDiffFile { workspace, path },
            )?;
            out.emit(&document, || render::diff(&document))?;
            Ok(0)
        }
    }
}

fn discard(session: &mut Session, out: &Emitter, args: &DiscardArgs) -> Result<u8> {
    let status = session.execute(Command::Status)?.status()?;
    let changes: Vec<Change> = status
        .changes
        .iter()
        .filter(|change| change.area != ChangeArea::Conflict)
        .filter(|change| args.all || matches(&change.path, &args.paths))
        .cloned()
        .collect();
    if !args.all && args.paths.is_empty() {
        return Err(Failure::new(
            EXIT_FAILURE,
            "discard needs paths, or --all for every change",
        )
        .into());
    }
    if changes.is_empty() {
        out.message("No changes match")?;
        return Ok(0);
    }
    if !args.yes {
        let paths: Vec<String> = changes.iter().map(Change::display_path).collect();
        out.message(&format!(
            "Would discard {} change(s): {}. Pass --yes to discard them.",
            paths.len(),
            paths.join(", ")
        ))?;
        return Ok(0);
    }
    operate(session, out, GitOperation::Discard(changes))
}

fn resolve(session: &mut Session, out: &Emitter, args: ResolveArgs) -> Result<u8> {
    let operation = if args.stage {
        GitOperation::Stage(vec![args.path])
    } else if args.ours {
        GitOperation::ResolveConflict {
            path: args.path,
            choice: ConflictChoice::Ours,
        }
    } else if args.theirs {
        GitOperation::ResolveConflict {
            path: args.path,
            choice: ConflictChoice::Theirs,
        }
    } else {
        return Err(Failure::new(
            EXIT_FAILURE,
            "resolve needs one of --ours, --theirs or --stage",
        )
        .into());
    };
    operate(session, out, operation)
}

fn repositories(session: &mut Session, out: &Emitter, args: &ReposArgs) -> Result<u8> {
    let (repositories, warnings) = session
        .execute(Command::GitHubRepositories {
            refresh: args.refresh,
        })?
        .github_repositories()?;
    out.emit(
        &RepositoryListing {
            repositories: &repositories,
            warnings: &warnings,
        },
        || render::repositories(&repositories, &warnings),
    )?;
    Ok(0)
}

#[derive(Serialize)]
struct RepositoryListing<'a> {
    repositories: &'a [GitHubRepository],
    warnings: &'a [String],
}

fn pull_request(session: &mut Session, out: &Emitter, command: PrVerb) -> Result<u8> {
    match command {
        PrVerb::View(args) => {
            let request = lookup(session, &args)?;
            out.emit(&request, || render::pull_request(&request))?;
            Ok(0)
        }
        PrVerb::Files(args) => {
            let request = lookup(session, &args)?;
            let index = prepare(session, &request)?;
            out.emit(&index, || render::pull_request_files(&index))?;
            Ok(0)
        }
        PrVerb::Diff(args) => {
            let request = lookup(session, &args.pull_request)?;
            let document = pull_request_diff(session, &request, args.path.as_deref())?;
            out.emit(&document, || render::diff(&document))?;
            Ok(0)
        }
        PrVerb::Conversation(args) => {
            let request = lookup(session, &args)?;
            let conversation = session
                .execute(Command::PullRequestConversation {
                    pull_request: Box::new(request),
                })?
                .conversation()?;
            out.emit(&conversation, || render::conversation(&conversation))?;
            Ok(0)
        }
        PrVerb::Checks(args) => checks(session, out, &args),
        PrVerb::Logs(args) => logs(session, out, &args),
        PrVerb::Open(args) => {
            let request = lookup(session, &args)?;
            open_url(&request.url)?;
            out.message(&format!("Opened {}", request.url))?;
            Ok(0)
        }
    }
}

fn checks(session: &mut Session, out: &Emitter, args: &PrChecksArgs) -> Result<u8> {
    let request = lookup(session, &args.pull_request)?;
    if args.watch {
        return watch::run(interval(args.interval, CHECK_WATCH_FLOOR), out.json, || {
            let checks = session
                .execute(Command::PullRequestChecks {
                    pull_request: Box::new(request.clone()),
                    refresh: true,
                })?
                .checks()?;
            let settled = !checks.checks.iter().any(|check| check.status.is_running());
            Ok(watch::Frame {
                text: render::checks(&checks.checks),
                finished: settled && !checks.checks.is_empty(),
                code: exit_for(&checks.checks),
                value: checks,
            })
        });
    }
    let checks = session
        .execute(Command::PullRequestChecks {
            pull_request: Box::new(request),
            refresh: args.pull_request.refresh,
        })?
        .checks()?;
    out.emit(&checks, || render::checks(&checks.checks))?;
    Ok(if args.exit_code {
        exit_for(&checks.checks)
    } else {
        0
    })
}

fn logs(session: &mut Session, out: &Emitter, args: &PrLogsArgs) -> Result<u8> {
    let request = lookup(session, &args.pull_request)?;
    let listing = session
        .execute(Command::PullRequestChecks {
            pull_request: Box::new(request.clone()),
            refresh: args.pull_request.refresh,
        })?
        .checks()?;
    let check = select_check(&listing.checks, &args.check)?;
    if args.watch {
        let name = check.name;
        return watch::run(interval(args.interval, LOG_WATCH_FLOOR), out.json, || {
            let listing = session
                .execute(Command::PullRequestChecks {
                    pull_request: Box::new(request.clone()),
                    refresh: true,
                })?
                .checks()?;
            let check = select_check(&listing.checks, &name)?;
            let log = session
                .execute(Command::CheckRunLog {
                    pull_request: Box::new(request.clone()),
                    check: Box::new(check.clone()),
                })?
                .check_log()?;
            Ok(watch::Frame {
                text: render::check_log(&check, &log),
                finished: !check.status.is_running(),
                code: u8::from(check.status == PullRequestCheckStatus::Failed),
                value: log,
            })
        });
    }
    let log = session
        .execute(Command::CheckRunLog {
            pull_request: Box::new(request),
            check: Box::new(check.clone()),
        })?
        .check_log()?;
    if let Some(reason) = &log.unavailable {
        return Err(Failure::new(EXIT_UNAVAILABLE, reason.clone()).into());
    }
    out.emit(&log, || render::check_log(&check, &log))?;
    Ok(0)
}

fn select_check(checks: &[PullRequestCheck], wanted: &str) -> Result<PullRequestCheck> {
    let exact: Vec<&PullRequestCheck> =
        checks.iter().filter(|check| check.name == wanted).collect();
    if let Some(check) = exact.first() {
        return Ok((*check).clone());
    }
    let partial: Vec<&PullRequestCheck> = checks
        .iter()
        .filter(|check| check.name.to_lowercase().contains(&wanted.to_lowercase()))
        .collect();
    match partial.as_slice() {
        [only] => Ok((*only).clone()),
        [] => Err(Failure::new(
            EXIT_NOT_FOUND,
            format!("no check on this pull request is called `{wanted}`"),
        )
        .hint(format!(
            "the checks are: {}",
            checks
                .iter()
                .map(|check| check.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ))
        .into()),
        _ => Err(Failure::new(
            EXIT_NOT_FOUND,
            format!("`{wanted}` matches more than one check"),
        )
        .hint(format!(
            "name one of: {}",
            partial
                .iter()
                .map(|check| check.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ))
        .into()),
    }
}

fn exit_for(checks: &[PullRequestCheck]) -> u8 {
    let unhappy = checks.iter().any(|check| {
        matches!(
            check.status,
            PullRequestCheckStatus::Failed | PullRequestCheckStatus::Pending
        )
    });
    u8::from(unhappy)
}

fn lookup(session: &mut Session, args: &PrArgs) -> Result<PullRequest> {
    let repositories = match &args.repo {
        None => Vec::new(),
        Some(_) => {
            session
                .execute(Command::GitHubRepositories { refresh: false })?
                .github_repositories()?
                .0
        }
    };
    let selected = match &args.repo {
        None => None,
        Some(wanted) => {
            let found = repositories
                .iter()
                .find(|repository| {
                    repository.name_with_owner.eq_ignore_ascii_case(wanted)
                        || repository.url.ends_with(wanted.as_str())
                })
                .cloned();
            match found {
                Some(repository) => Some(Box::new(repository)),
                None => {
                    return Err(Failure::new(
                        EXIT_NOT_FOUND,
                        format!("no remote of this checkout points at `{wanted}`"),
                    )
                    .hint("run `quinjet repos` for the repositories it can see")
                    .into());
                }
            }
        }
    };
    let snapshot = session
        .execute(Command::PullRequestLookup {
            repositories,
            repository: selected,
            number: args.number,
            refresh: args.refresh,
        })?
        .pull_request()?;
    for warning in &snapshot.warnings {
        note(&format!("warning: {warning}"));
    }
    Ok(snapshot.pull_request)
}

fn prepare(session: &mut Session, request: &PullRequest) -> Result<PullRequestDiffIndex> {
    session
        .execute(Command::PreparePullRequest {
            workspace: 0,
            pull_request: Box::new(request.clone()),
        })?
        .pull_request_index()
}

fn pull_request_diff(
    session: &mut Session,
    request: &PullRequest,
    path: Option<&Path>,
) -> Result<DiffDocument> {
    let index = prepare(session, request)?;
    let paths: Vec<PathBuf> = match path {
        Some(wanted) => {
            if !index.files.iter().any(|file| file.path == wanted) {
                return Err(Failure::new(
                    EXIT_NOT_FOUND,
                    format!("`{}` is not part of this pull request", wanted.display()),
                )
                .hint("run `quinjet pr files <number>` for the files it changes")
                .into());
            }
            vec![wanted.to_path_buf()]
        }
        None => index.files.iter().map(|file| file.path.clone()).collect(),
    };
    let mut loaded = HashMap::new();
    for chunk in paths.chunks(16) {
        for (path, document) in session
            .execute(Command::PullRequestFileBatch {
                workspace: 0,
                paths: chunk.to_vec(),
            })?
            .pull_request_diff_batch()?
        {
            drop(loaded.insert(path, document));
        }
    }
    let index = DiffIndex {
        title: format!("PR #{}", request.number),
        files: index
            .files
            .iter()
            .filter(|file| loaded.contains_key(&file.path))
            .map(|file| crate::git::diff::DiffFileIndexEntry {
                path: file.path.clone(),
                old_path: file.old_path.clone(),
                status: render::pull_request_file_label(file.status).to_owned(),
                counts: file.counts,
            })
            .collect(),
        truncated: index.truncated,
        commit_details: None,
    };
    Ok(index.document_with_visibility(&loaded, |_| true))
}

fn whole_document(
    session: &mut Session,
    prepare: Command,
    file: impl Fn(u64, PathBuf) -> Command,
) -> Result<DiffDocument> {
    let index = session.execute(prepare)?.local_diff_index()?;
    let mut loaded = HashMap::new();
    for entry in &index.files {
        let (path, document) = session
            .execute(file(0, entry.path.clone()))?
            .local_diff_file()?;
        drop(loaded.insert(path, document));
    }
    Ok(index.document_with_visibility(&loaded, |_| true))
}

fn operate(session: &mut Session, out: &Emitter, operation: GitOperation) -> Result<u8> {
    let (_, _, message) = session.execute(Command::Operate(operation))?.operation()?;
    out.message(&message)?;
    Ok(0)
}

fn revision(session: &Session, value: &str) -> Result<String> {
    session.repository_revision(value).map_err(|error| {
        Failure::new(EXIT_NOT_FOUND, format!("{error:#}"))
            .hint("run `quinjet log` or `quinjet branch list --all` for what this repository holds")
            .into()
    })
}

fn require_paths(paths: Vec<PathBuf>, verb: &str) -> Result<Vec<PathBuf>> {
    if paths.is_empty() {
        return Err(Failure::new(
            EXIT_FAILURE,
            format!("{verb} needs paths, or --all for every change"),
        )
        .into());
    }
    Ok(paths)
}

fn matches(path: &Path, filters: &[PathBuf]) -> bool {
    filters.is_empty() || filters.iter().any(|filter| path.starts_with(filter))
}

const fn interval(seconds: u64, floor: u64) -> Duration {
    Duration::from_secs(if seconds < floor { floor } else { seconds })
}

pub(crate) fn open_url(url: &str) -> Result<()> {
    let opener = if cfg!(target_os = "macos") {
        "open"
    } else if cfg!(target_os = "windows") {
        "explorer"
    } else {
        "xdg-open"
    };
    drop(
        std::process::Command::new(opener)
            .arg(url)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .with_context(|| format!("failed to hand {url} to {opener}"))?,
    );
    Ok(())
}

fn note(text: &str) {
    drop(writeln!(io::stderr().lock(), "{text}"));
}

pub(crate) fn report(error: &anyhow::Error) -> u8 {
    if let Some(broken) = error.downcast_ref::<io::Error>()
        && broken.kind() == io::ErrorKind::BrokenPipe
    {
        return 0;
    }
    let failure = error.downcast_ref::<Failure>();
    note(&format!("error: {error:#}"));
    if let Some(hint) = failure.and_then(|failure| failure.hint.as_deref()) {
        note(&format!("hint: {hint}"));
    }
    failure.map_or(EXIT_FAILURE, |failure| failure.code)
}

pub(crate) fn stdout_is_terminal() -> bool {
    io::stdout().is_terminal()
}

#[cfg(test)]
#[expect(
    unused_results,
    reason = "test helpers return values the assertions do not use"
)]
mod tests {
    use std::fs;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use clap::CommandFactory;

    use super::*;
    use crate::git::github::PullRequestCheck;

    static TEST_REPOSITORY_ID: AtomicUsize = AtomicUsize::new(0);

    struct TestRepository {
        path: PathBuf,
    }

    impl TestRepository {
        fn new() -> Self {
            let id = TEST_REPOSITORY_ID.fetch_add(1, Ordering::Relaxed);
            let name = format!("quinjet-cli-test-{}-{id}", std::process::id());
            // nosemgrep: rust.lang.security.temp-dir.temp-dir
            let path = std::env::temp_dir().join(name);
            drop(fs::remove_dir_all(&path));
            fs::create_dir_all(&path).unwrap();
            let repository = Self { path };
            repository.git(&["init", "--initial-branch=main"]);
            repository.git(&["config", "user.name", "Quinjet Test"]);
            repository.git(&["config", "user.email", "quinjet@example.com"]);
            fs::write(repository.path.join("README.md"), "one\n").unwrap();
            repository.git(&["add", "README.md"]);
            repository.git(&["commit", "--message=base"]);
            repository
        }

        fn git(&self, args: &[&str]) -> String {
            let output = std::process::Command::new("git")
                .arg("-C")
                .arg(&self.path)
                .args(args)
                .env("LC_ALL", "C")
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "git {args:?} failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            String::from_utf8_lossy(&output.stdout).trim().to_owned()
        }

        fn session(&self) -> Session {
            Session::new(Repository::discover(&self.path).unwrap())
        }
    }

    impl Drop for TestRepository {
        fn drop(&mut self) {
            drop(fs::remove_dir_all(&self.path));
        }
    }

    fn check(name: &str, status: PullRequestCheckStatus) -> PullRequestCheck {
        PullRequestCheck {
            name: name.to_owned(),
            workflow: "CI".to_owned(),
            state: String::new(),
            status,
            description: String::new(),
            link: String::new(),
            started_at: String::new(),
            completed_at: String::new(),
        }
    }

    #[test]
    fn the_command_tree_is_unambiguous() {
        Cli::command().debug_assert();
    }

    #[test]
    fn a_repository_path_with_no_verb_opens_the_terminal_interface() {
        let cli = Cli::try_parse_from(["quinjet", "/tmp/somewhere"]).unwrap();
        assert!(cli.command.is_none());
        assert_eq!(cli.path, PathBuf::from("/tmp/somewhere"));
    }

    #[test]
    fn a_verb_is_never_mistaken_for_a_repository_path() {
        let cli = Cli::try_parse_from(["quinjet", "status"]).unwrap();
        assert!(
            matches!(cli.command, Some(Verb::Status(_))),
            "`quinjet status` must reach the status verb rather than open a directory called status"
        );
    }

    #[test]
    fn every_subcommand_answers_to_the_repository_and_json_switches() {
        for argv in [
            vec!["quinjet", "-C", "/tmp/elsewhere", "--json", "status"],
            vec!["quinjet", "status", "-C", "/tmp/elsewhere", "--json"],
            vec![
                "quinjet",
                "pr",
                "checks",
                "1",
                "--json",
                "-C",
                "/tmp/elsewhere",
            ],
        ] {
            let cli = Cli::try_parse_from(&argv).unwrap();
            assert!(cli.json, "{argv:?} must be readable as JSON");
            assert_eq!(cli.repository, PathBuf::from("/tmp/elsewhere"), "{argv:?}");
        }
    }

    #[test]
    fn a_session_answers_a_status_command_with_the_working_tree() {
        let repository = TestRepository::new();
        fs::write(repository.path.join("added.txt"), "new\n").unwrap();
        let mut session = repository.session();

        let status = session.execute(Command::Status).unwrap().status().unwrap();

        assert_eq!(status.branch.head, "main");
        assert!(
            status
                .changes
                .iter()
                .any(|change| change.path == Path::new("added.txt")),
            "the untracked file belongs in the answer: {status:?}"
        );
    }

    #[test]
    fn a_prepared_workspace_answers_only_the_generation_that_asked_for_it() {
        let repository = TestRepository::new();
        fs::write(repository.path.join("README.md"), "two\n").unwrap();
        let mut session = repository.session();
        let status = session.execute(Command::Status).unwrap().status().unwrap();
        session
            .execute(Command::PrepareLocalDiff {
                workspace: 7,
                request: Box::new(LocalDiffRequest::Changes {
                    changes: status.changes,
                    version: 0,
                    expanded: false,
                }),
            })
            .unwrap();

        let mine = session.execute(Command::LocalDiffFile {
            workspace: 7,
            path: PathBuf::from("README.md"),
        });
        let stale = session.execute(Command::LocalDiffFile {
            workspace: 8,
            path: PathBuf::from("README.md"),
        });

        assert!(
            mine.is_ok(),
            "the generation that prepared it must be answered"
        );
        assert!(
            stale.is_err(),
            "a workspace must never answer a generation it was not prepared for"
        );
    }

    #[test]
    fn an_operation_command_reports_what_it_did() {
        let repository = TestRepository::new();
        fs::write(repository.path.join("added.txt"), "new\n").unwrap();
        let mut session = repository.session();

        let (label, changes_history, message) = session
            .execute(Command::Operate(GitOperation::StageAll))
            .unwrap()
            .operation()
            .unwrap();

        assert_eq!(label, "Staging all changes");
        assert!(!changes_history);
        assert_eq!(message, "All changes staged");
        assert!(
            repository
                .git(&["diff", "--cached", "--name-only"])
                .contains("added.txt"),
            "staging through the command layer must reach the index"
        );
    }

    #[test]
    fn a_revision_resolves_from_what_a_person_would_type() {
        let repository = TestRepository::new();
        let head = repository.git(&["rev-parse", "HEAD"]);
        repository.git(&["tag", "v1"]);
        let session = repository.session();

        assert_eq!(session.repository_revision("HEAD").unwrap(), "HEAD");
        assert_eq!(
            session.repository_revision("main").unwrap(),
            "refs/heads/main"
        );
        assert_eq!(session.repository_revision("v1").unwrap(), "refs/tags/v1");
        let short: String = head.chars().take(8).collect();
        assert_eq!(session.repository_revision(&short).unwrap(), head);
    }

    #[test]
    fn a_revision_that_names_nothing_is_a_name_that_was_not_found() {
        let repository = TestRepository::new();
        let session = repository.session();

        let error = revision(&session, "deadbeefdead").unwrap_err();
        let failure = error.downcast_ref::<Failure>().unwrap();

        assert_eq!(
            failure.code, EXIT_NOT_FOUND,
            "a revision that resolves to nothing is a missing name, not a failed command"
        );
        assert!(
            failure.hint.is_some(),
            "exit 3 always says what could be named instead"
        );
    }

    #[test]
    fn a_revision_that_could_be_read_as_an_option_is_refused_before_git_sees_it() {
        let repository = TestRepository::new();
        let session = repository.session();

        for revision in ["--output=/tmp/owned", "-n", ""] {
            assert!(
                session.repository_revision(revision).is_err(),
                "`{revision}` must never reach Git as a revision"
            );
        }
    }

    #[test]
    fn watching_checks_stops_only_once_nothing_is_still_running() {
        let running = [
            check("one", PullRequestCheckStatus::Passed),
            check("two", PullRequestCheckStatus::Pending),
        ];
        let settled = [
            check("one", PullRequestCheckStatus::Passed),
            check("two", PullRequestCheckStatus::Failed),
        ];

        assert!(running.iter().any(|check| check.status.is_running()));
        assert!(!settled.iter().any(|check| check.status.is_running()));
        assert_eq!(exit_for(&running), 1, "a pending check is not a green run");
        assert_eq!(exit_for(&settled), 1, "a failed check is not a green run");
        assert_eq!(exit_for(&[check("one", PullRequestCheckStatus::Passed)]), 0);
    }

    #[test]
    fn naming_a_check_that_matches_nothing_says_which_ones_exist() {
        let checks = [
            check(
                "Format, lint, and test (ubuntu-latest)",
                PullRequestCheckStatus::Passed,
            ),
            check(
                "Format, lint, and test (macos-latest)",
                PullRequestCheckStatus::Passed,
            ),
            check("Package validation", PullRequestCheckStatus::Passed),
        ];

        assert_eq!(
            select_check(&checks, "Package validation").unwrap().name,
            "Package validation"
        );
        assert_eq!(
            select_check(&checks, "package").unwrap().name,
            "Package validation",
            "one partial match is enough to name a check"
        );

        let ambiguous = select_check(&checks, "Format").unwrap_err();
        let ambiguous = ambiguous.downcast_ref::<Failure>().unwrap();
        assert_eq!(ambiguous.code, EXIT_NOT_FOUND);
        assert!(ambiguous.hint.as_ref().unwrap().contains("ubuntu-latest"));

        let missing = select_check(&checks, "nothing").unwrap_err();
        assert_eq!(
            missing.downcast_ref::<Failure>().unwrap().code,
            EXIT_NOT_FOUND
        );
    }

    #[test]
    fn a_destructive_verb_changes_nothing_until_it_is_confirmed() {
        let repository = TestRepository::new();
        fs::write(repository.path.join("README.md"), "changed\n").unwrap();
        let mut session = repository.session();
        let out = Emitter { json: true };

        discard(
            &mut session,
            &out,
            &DiscardArgs {
                paths: vec![PathBuf::from("README.md")],
                all: false,
                yes: false,
            },
        )
        .unwrap();

        assert_eq!(
            fs::read_to_string(repository.path.join("README.md")).unwrap(),
            "changed\n",
            "a discard without --yes must leave the working tree alone"
        );
    }
}