cuno-cli 0.3.0

Everything C/C++ development needs, in one tool.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
//! The `cuno` command line: parses it, resolves the settings, dispatches to
//! a command and reports what went wrong, from values the binary collected
//! from the process. Each command is a module that combines the other crates
//! and shows the result.
//!
//! See `docs/en/specs/commands.md` for the commands, options, output and exit
//! codes, and `docs/en/specs/architecture.md`, "What goes in `src/` and
//! `cuno-cli`", for what belongs here.

mod build;
mod clean;
mod deps;
mod doctor;
mod fmt;
mod lint;
mod new;
mod self_cmd;
mod toolchain;

use std::ffi::OsString;
use std::io::{BufRead, Write};
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};

use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use cuno_core::{ColorChoice, CunoError, Env, ExitClass, Shell, Verbosity};
use cuno_manifest::{CliSettings, ConfigError, Inputs, Settings};

// So the binary, which may depend only on this crate and `cuno-core`, can
// name the host it collects (`architecture.md`, "Dependencies between
// crates").
pub use cuno_toolchain::HostOs;

/// What only the process has, collected by the binary and handed in as
/// values: no library reads the process itself (`docs/en/specs/
/// architecture.md`, "Dependencies between crates").
pub struct Process {
    /// The command line, the program's name first.
    pub args: Vec<OsString>,
    /// The environment variables.
    pub env: Env,
    /// The current directory, or why it cannot be read. Only a command that
    /// needs it reports the reason, so `--help` works without one.
    pub cwd: Result<PathBuf, String>,
    /// The operating system cuno runs on.
    pub host: HostOs,
    /// The temporary directory.
    pub temp: PathBuf,
    /// Where the running executable is, or why that cannot be found. Only
    /// `cuno self` needs it.
    pub exe: Result<PathBuf, String>,
    /// How many processors this machine has: the default number of jobs.
    pub cores: NonZeroU32,
    /// Standard output: help, the version and the usage. Any writer, so a
    /// test can read what was written.
    pub stdout: Box<dyn Write>,
    /// Whether standard output is a terminal.
    pub stdout_is_terminal: bool,
    /// Standard error: everything else cuno prints.
    pub stderr: Box<dyn Write>,
    /// Whether standard error is a terminal.
    pub stderr_is_terminal: bool,
    /// Standard input: the answer to a question cuno asks.
    pub stdin: Box<dyn BufRead>,
    /// Whether standard input is a terminal; cuno only asks one that is.
    pub stdin_is_terminal: bool,
}

/// The top-level command line. Subcommands are added with the milestones that
/// implement them (docs/en/roadmap.md).
#[derive(Parser)]
#[command(
    // `name` is what `--version` prints ("cuno <version>"); `bin_name` is what
    // the usage line prints. Without `bin_name`, clap takes the executable's
    // file name, which is `cuno.exe` on Windows.
    name = "cuno",
    bin_name = "cuno",
    version,
    // Taken from `description` in Cargo.toml, so the two cannot drift apart.
    about
)]
struct Cli {
    // The line below is the help text `cuno --help` prints for this option,
    // pinned by tests/cli.rs. `None` when not given: `[term] color`, then
    // NO_COLOR, apply only then (docs/en/specs/commands.md, "Available for
    // all commands").
    /// Coloring
    #[arg(long, value_name = "WHEN", value_enum, global = true)]
    color: Option<Color>,

    /// Show more, such as each command a build runs
    #[arg(short, long, global = true, conflicts_with = "quiet")]
    verbose: bool,

    /// Show only errors, warnings and the compilers' output
    #[arg(short, long, global = true)]
    quiet: bool,

    #[command(subcommand)]
    command: Option<Command>,
}

/// The commands (docs/en/specs/commands.md).
#[derive(Subcommand)]
enum Command {
    /// Create a new package
    New {
        /// Where to create it
        #[arg(value_name = "PATH")]
        path: PathBuf,
        /// The language (c / c++; default c++)
        #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
        lang: Option<String>,
        /// The language standard (c++17 / c++20 / c++23 / c11 / c17 / c23)
        #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
        edition: Option<String>,
        /// The package's name (default: the directory's)
        #[arg(long, value_name = "NAME")]
        name: Option<String>,
        /// Version control (git / none)
        #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
        vcs: String,
        /// Make a library package
        #[arg(long)]
        lib: bool,
    },
    /// Make an existing directory into a package
    Init {
        /// The directory (default: the current one)
        #[arg(value_name = "PATH")]
        path: Option<PathBuf>,
        /// The language (c / c++; default: the sources', else c++)
        #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
        lang: Option<String>,
        /// The language standard (c++17 / c++20 / c++23 / c11 / c17 / c23)
        #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
        edition: Option<String>,
        /// The package's name (default: the directory's)
        #[arg(long, value_name = "NAME")]
        name: Option<String>,
        /// Version control (git / none)
        #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
        vcs: String,
        /// Make a library package
        #[arg(long)]
        lib: bool,
    },
    /// Compile the package
    Build(BuildOpts),
    /// Check the package for errors without building it
    Check {
        /// Check the tests instead of the program
        #[arg(long)]
        tests: bool,
        /// Check both the program and the tests
        #[arg(long)]
        all_targets: bool,
        #[command(flatten)]
        opts: BuildOpts,
    },
    /// Build the package and run one of its executables
    Run {
        /// The executable to run, when there are several
        #[arg(long, value_name = "NAME")]
        bin: Option<String>,
        #[command(flatten)]
        opts: BuildOpts,
        /// Arguments for the program
        #[arg(last = true, value_name = "ARGS")]
        args: Vec<OsString>,
    },
    /// Build the package's tests and run them
    Test {
        /// Run only the tests whose names contain this
        #[arg(value_name = "FILTER")]
        filter: Option<String>,
        /// Show every test's output, not only a failed one's
        #[arg(long)]
        nocapture: bool,
        #[command(flatten)]
        opts: BuildOpts,
    },
    /// Format the package's code with clang-format
    Fmt {
        /// Do not format; fail if any file is not formatted (for CI)
        #[arg(long)]
        check: bool,
    },
    /// Analyse the package's code with clang-tidy
    // The build commands' --target, --target-dir and -j are declared again
    // here rather than through `BuildOpts`, which would bring --release and
    // --profile, which lint refuses (docs/en/specs/dev-tools.md, "Target
    // files"); the help text says what each does for lint.
    Lint {
        /// Fix what clang-tidy can, in the sources themselves
        #[arg(long)]
        fix: bool,
        /// The compiler whose commands are analysed (msvc / clang / clang-cl / gcc / safec)
        #[arg(long, value_name = "NAME")]
        compiler: Option<String>,
        /// The target to analyse for (reserved: an error for now)
        #[arg(long, value_name = "TRIPLE")]
        target: Option<String>,
        /// The build's output directory, which the analysed commands name
        #[arg(long, value_name = "PATH")]
        target_dir: Option<PathBuf>,
        /// How many sources to analyse at once (default: the number of cores)
        #[arg(short, long, value_name = "N")]
        jobs: Option<NonZeroU32>,
        #[command(flatten)]
        fetch: FetchOpts,
    },
    /// Remove the build's output
    Clean {
        /// Remove only the release profile's output
        #[arg(long, conflicts_with = "profile")]
        release: bool,
        /// Remove only the given profile's output (dev / release)
        #[arg(long, value_name = "NAME")]
        profile: Option<String>,
        /// The output directory to remove from
        #[arg(long, value_name = "PATH")]
        target_dir: Option<PathBuf>,
    },
    /// Diagnose the environment and show a fix for each problem
    Doctor {
        /// The compiler to diagnose (msvc / clang / clang-cl / gcc / safec)
        #[arg(long, value_name = "NAME")]
        compiler: Option<String>,
    },
    /// Add a dependency to Cuno.toml, fetch it and record it in Cuno.lock
    #[command(group(clap::ArgGroup::new("source").args(["git", "url", "path"]).multiple(false)))]
    #[command(group(clap::ArgGroup::new("reference").args(["tag", "rev", "branch"]).multiple(false).requires("git")))]
    Add {
        /// A dependency by its name alone (not available yet)
        #[arg(value_name = "NAME", conflicts_with = "source")]
        name: Option<String>,
        /// From a Git repository
        #[arg(long, value_name = "URL")]
        git: Option<String>,
        /// The tag to check out, with --git
        #[arg(long, value_name = "TAG")]
        tag: Option<String>,
        /// The commit to check out, with --git
        #[arg(long, value_name = "COMMIT")]
        rev: Option<String>,
        /// The branch to check out, with --git
        #[arg(long, value_name = "BRANCH")]
        branch: Option<String>,
        /// From an archive (.zip / .tar.gz)
        #[arg(long, value_name = "URL")]
        url: Option<String>,
        /// From a package on this machine
        #[arg(long, value_name = "PATH")]
        path: Option<PathBuf>,
        /// A condition the package's version must satisfy
        #[arg(long, value_name = "CONDITION")]
        version: Option<String>,
        /// Do not use the network; fail if the source is not in the cache
        #[arg(long)]
        offline: bool,
    },
    /// Remove dependencies from Cuno.toml
    Remove {
        /// The dependencies to remove
        #[arg(value_name = "NAME", required = true)]
        names: Vec<String>,
        /// Do not use the network; fail if a dependency is not in the cache
        #[arg(long)]
        offline: bool,
    },
    /// Fetch the dependencies again and record what they are now
    Update {
        /// Only this dependency, and what it depends on
        #[arg(value_name = "NAME")]
        name: Option<String>,
    },
    /// Show the dependency graph
    Tree {
        #[command(flatten)]
        fetch: FetchOpts,
    },
    /// Fetch the dependencies and write Cuno.lock, without building
    Fetch {
        #[command(flatten)]
        fetch: FetchOpts,
    },
    /// List the compilers cuno finds, or choose the default one
    Toolchain {
        #[command(subcommand)]
        command: ToolchainCommand,
    },
    /// Update cuno itself
    #[command(name = "self")]
    SelfCmd {
        #[command(subcommand)]
        command: SelfCommand,
    },
}

/// `cuno self`'s commands (docs/en/specs/commands.md).
#[derive(Subcommand)]
enum SelfCommand {
    /// Update cuno to the latest release
    Update,
    /// Remove cuno's home and, if its installer placed it, cuno itself
    Uninstall {
        /// Remove without asking
        #[arg(short = 'y', long)]
        yes: bool,
    },
}

/// `cuno toolchain`'s commands (docs/en/specs/commands.md).
#[derive(Subcommand)]
enum ToolchainCommand {
    /// List the compilers and tools cuno finds, and which one builds use
    List,
    /// Make a compiler this user's default
    Default {
        /// The compiler (msvc / clang / clang-cl / gcc)
        #[arg(value_name = "COMPILER")]
        compiler: String,
    },
}

/// The options of the build commands (docs/en/specs/commands.md, "Available for
/// build commands (`build` / `run` / `check` / `test`)").
#[derive(Args)]
struct BuildOpts {
    /// Build with the release profile
    #[arg(long, conflicts_with = "profile")]
    release: bool,
    /// Build with the given profile (dev / release)
    #[arg(long, value_name = "NAME")]
    profile: Option<String>,
    /// The compiler to use (msvc / clang / clang-cl / gcc / safec)
    #[arg(long, value_name = "NAME")]
    compiler: Option<String>,
    /// Cross-compile for a target (reserved)
    #[arg(long, value_name = "TRIPLE")]
    target: Option<String>,
    /// Where to put the build's output
    #[arg(long, value_name = "PATH")]
    target_dir: Option<PathBuf>,
    /// How many steps to run at once (default: the number of cores)
    #[arg(short, long, value_name = "N")]
    jobs: Option<NonZeroU32>,
    #[command(flatten)]
    fetch: FetchOpts,
}

/// `--locked` and `--offline` (docs/en/specs/commands.md, "Available for
/// build commands and `lint` (`build` / `run` / `check` / `test` /
/// `lint`)").
#[derive(Args, Clone, Copy)]
struct FetchOpts {
    /// Fail if Cuno.lock would need rewriting (for CI)
    #[arg(long)]
    locked: bool,
    /// Do not use the network; fail if a dependency is not in the cache
    #[arg(long)]
    offline: bool,
}

impl From<FetchOpts> for Fetching {
    fn from(o: FetchOpts) -> Fetching {
        Fetching {
            network: if o.offline {
                cuno_deps::Network::Offline
            } else {
                cuno_deps::Network::Online
            },
            lock: if o.locked {
                cuno_deps::LockMode::Locked
            } else {
                cuno_deps::LockMode::Write
            },
        }
    }
}

impl From<BuildOpts> for build::BuildArgs {
    fn from(o: BuildOpts) -> build::BuildArgs {
        build::BuildArgs {
            release: o.release,
            profile: o.profile,
            target: o.target,
            fetching: o.fetch.into(),
        }
    }
}

/// The `--color` the command line gives, read before clap parses it so
/// that what clap prints follows it too: the last one before a bare `--`
/// (what follows belongs to the program `cuno run` runs), as
/// `--color <when>` or `--color=<when>`. A value that is not one of
/// `--color`'s counts as none, so the usage error it causes is colored as if
/// `--color` were not given.
fn color_before_parsing(args: &[OsString]) -> Option<ColorChoice> {
    let mut found = None;
    let mut args = args.iter().skip(1);
    while let Some(arg) = args.next() {
        // `Some(None)` is a `--color` whose value is missing or not
        // Unicode, which counts as none like any other invalid value.
        let value = match arg.to_str() {
            Some("--") => break,
            Some("--color") => Some(args.next().and_then(|v| v.to_str())),
            Some(arg) => arg.strip_prefix("--color=").map(Some),
            None => arg
                .as_encoded_bytes()
                .starts_with(b"--color=")
                .then_some(None),
        };
        if let Some(value) = value {
            found = Some(
                value
                    .and_then(|v| Color::from_str(v, false).ok())
                    .map(ColorChoice::from),
            );
        }
    }
    found.flatten()
}

/// Whether what clap makes is written with its colors on a stream, by
/// [`cuno_core::colors`] with no configured choice: clap prints before the
/// files are read. Never clap's own `Auto`, which reads `CLICOLOR_FORCE`, a
/// variable cuno does not read.
fn parser_color(given: Option<ColorChoice>, no_color: bool, terminal: bool) -> clap::ColorChoice {
    if cuno_core::colors(given, None, no_color, terminal) {
        clap::ColorChoice::Always
    } else {
        clap::ColorChoice::Never
    }
}

/// The values of `--color`. A separate type because `cuno-core` does not
/// depend on clap.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum Color {
    Auto,
    Always,
    Never,
}

impl From<Color> for ColorChoice {
    fn from(color: Color) -> ColorChoice {
        match color {
            Color::Auto => ColorChoice::Auto,
            Color::Always => ColorChoice::Always,
            Color::Never => ColorChoice::Never,
        }
    }
}

/// Carries out the command line `process` holds and returns the exit code
/// for the binary to end with.
pub fn run(process: Process) -> i32 {
    let Process {
        args,
        env,
        cwd,
        host,
        temp,
        exe,
        cores,
        mut stdout,
        stdout_is_terminal,
        mut stderr,
        stderr_is_terminal,
        mut stdin,
        stdin_is_terminal,
    } = process;
    // What clap prints itself is colored by cuno's rule, not clap's
    // (docs/en/specs/commands.md, "Available for all commands"): `--color`
    // as written, then NO_COLOR, then whether the output is a terminal.
    let given = color_before_parsing(&args);
    let no_color = env.get("NO_COLOR").is_some();
    let stdout_color = parser_color(given, no_color, stdout_is_terminal);
    let stderr_color = parser_color(given, no_color, stderr_is_terminal);
    // On `--version`, `--help` and usage errors, what clap made is printed
    // and its code returned: 0 for the first two and 2 for a usage error, as
    // the spec's exit codes require. What clap makes carries its styles
    // whatever color the command is given; whether they are written is
    // decided per stream, in `write_styled`.
    let cli = match Cli::command().try_get_matches_from(&args) {
        // Formatted against the command, as `Cli::parse` does, so such an
        // error would carry the usage line too.
        Ok(matches) => match Cli::from_arg_matches(&matches) {
            Ok(cli) => cli,
            Err(e) => {
                let e = e.format(&mut Cli::command());
                return print_clap(&e, stdout_color, stderr_color, &mut stdout, &mut stderr);
            }
        },
        Err(error) => {
            return print_clap(&error, stdout_color, stderr_color, &mut stdout, &mut stderr);
        }
    };
    let mut shell = Shell::new(
        stderr,
        cli.color.map(ColorChoice::from),
        &env,
        stderr_is_terminal,
    );
    let given = Values {
        env: &env,
        cwd: &cwd,
        exe: &exe,
        host,
        temp: &temp,
        cores,
    };
    let input = Input {
        stdin: stdin.as_mut(),
        is_terminal: stdin_is_terminal,
    };
    match dispatch(cli, given, &mut shell, stdout_color, &mut stdout, input) {
        Ok(code) => code,
        Err(error) => report(&mut shell, &*error),
    }
}

/// What clap made for `--help`, `--version` or a usage error, written where
/// clap writes it (stdout for the first two, stderr for an error) in that
/// stream's color, and its exit code.
fn print_clap(
    error: &clap::Error,
    stdout_color: clap::ColorChoice,
    stderr_color: clap::ColorChoice,
    stdout: &mut Box<dyn Write>,
    stderr: &mut Box<dyn Write>,
) -> i32 {
    let (out, color) = if error.use_stderr() {
        (stderr, stderr_color)
    } else {
        (stdout, stdout_color)
    };
    // A failed write (a closed stream) is ignored, as clap ignores it: the
    // exit code stays clap's.
    let _ = write_styled(out.as_mut(), &error.render(), color);
    error.exit_code()
}

/// `text` written plain, or with its colors when `color` says so. clap's
/// own printing writes to the process's streams and exits, which a library
/// may not, so what clap makes is written here to the streams given.
fn write_styled(
    out: &mut dyn Write,
    text: &clap::builder::StyledStr,
    color: clap::ColorChoice,
) -> std::io::Result<()> {
    match color {
        clap::ColorChoice::Always => write!(out, "{}", text.ansi())?,
        _ => write!(out, "{text}")?,
    }
    out.flush()
}

/// The values the commands take from [`Process`], borrowed once the
/// standard streams have gone to the shell and to the usage.
#[derive(Clone, Copy)]
struct Values<'a> {
    env: &'a Env,
    cwd: &'a Result<PathBuf, String>,
    host: HostOs,
    temp: &'a Path,
    exe: &'a Result<PathBuf, String>,
    cores: NonZeroU32,
}

impl Values<'_> {
    /// The current directory, or the error a command reports without it.
    fn cwd(&self) -> Result<PathBuf, Box<dyn CunoError>> {
        self.cwd
            .clone()
            .map_err(|e| Box::new(CwdError(e)) as Box<dyn CunoError>)
    }
}

/// The settings, with `[term] color` applied to `shell` before the warnings
/// they raised are printed, so every command colors as configured
/// (`docs/en/specs/commands.md`, "Available for all commands"). An error
/// comes back before any configuration file is applied, so it is shown as
/// `--color` and `NO_COLOR` alone decide.
fn resolve_settings(inputs: Inputs<'_>, shell: &mut Shell) -> Result<Settings, ConfigError> {
    let loaded = cuno_manifest::resolve(inputs)?;
    shell.configure(loaded.value.color, loaded.value.verbose);
    for warning in &loaded.warnings {
        shell.warning(warning);
    }
    Ok(loaded.value)
}

/// What resolving dependencies may do: use the network, and write
/// `Cuno.lock`.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Fetching {
    pub(crate) network: cuno_deps::Network,
    pub(crate) lock: cuno_deps::LockMode,
}

/// What `BuildArgs`, which derives `Default`, holds when no option is
/// given.
impl Default for Fetching {
    /// Fetch what is missing, and write `Cuno.lock`.
    fn default() -> Fetching {
        Fetching {
            network: cuno_deps::Network::Online,
            lock: cuno_deps::LockMode::Write,
        }
    }
}

/// `path` as a command's argument gave it (`cuno new`, `cuno init`, `cuno
/// add --path`), resolved against `cwd` the way every path the user writes
/// is (`cuno_manifest`'s `resolve_path`): a path that depends on the
/// current drive is refused, with the same error wherever it was given.
pub(crate) fn argument_path(path: &Path, cwd: &Path) -> Result<PathBuf, DriveRelativePath> {
    cuno_manifest::resolve_path(path, cwd).map_err(|_| DriveRelativePath(path.to_owned()))
}

/// A path argument that depends on the current drive on Windows (`/x`,
/// `C:x`): exit code 3 (`docs/en/specs/commands.md`, "`cuno new <path>`").
#[derive(Debug)]
pub(crate) struct DriveRelativePath(pub(crate) PathBuf);

impl std::fmt::Display for DriveRelativePath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "the path is `{}`, which depends on the current drive",
            self.0.display()
        )
    }
}

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

impl CunoError for DriveRelativePath {
    fn exit_class(&self) -> ExitClass {
        ExitClass::Setup
    }

    fn help(&self) -> Option<String> {
        Some("write an absolute path, or a path relative to the current directory".to_owned())
    }
}

/// `settings` with the project's dependencies resolved, fetched as
/// `fetching` allows (`docs/en/specs/dependencies.md`, "Resolution" and
/// "When sources are fetched and what is used"), and their warnings
/// printed: for the commands that build or analyse the package, which see
/// the same dependencies. `cuno fmt` reads none, as it formats the
/// package's own files alone. A command calls it once its own arguments are
/// checked, so that an error in them is reported before anything is
/// fetched.
pub(crate) fn with_dependencies(
    mut settings: Settings,
    fetching: Fetching,
    env: &cuno_core::Env,
    host: cuno_toolchain::HostOs,
    cwd: &Path,
    shell: &mut Shell,
) -> Result<Settings, ConfigError> {
    if let Some(package) = settings.project.take() {
        let resolved = deps::with_resolve_options(
            &settings,
            fetching,
            cuno_deps::Forget::Nothing,
            &[],
            env,
            host,
            cwd,
            |options| cuno_deps::resolve(package, options, shell),
        )?;
        for (verb, text) in &resolved.changes {
            shell.status(verb, text);
        }
        for warning in &resolved.warnings {
            shell.warning(warning);
        }
        settings.project = Some(resolved.root);
    }
    Ok(settings)
}

/// `cuno new`'s settings: the user's `[term]` alone, applied to `shell`,
/// since the project around the new package is not its own
/// (`docs/en/specs/commands.md`, "Available for all commands").
fn resolve_user_settings(env: &Env, cwd: &Path, shell: &mut Shell) -> Result<(), ConfigError> {
    let loaded = cuno_manifest::resolve_user(env, cwd)?;
    shell.configure(loaded.value.color, loaded.value.verbose);
    for warning in &loaded.warnings {
        shell.warning(warning);
    }
    Ok(())
}

/// Carries out the parsed command line and returns the exit code. Every
/// error a command can meet comes back here rather than being printed where
/// it happens; `doctor` prints its problems itself and only says how many.
/// `help_color` is how the usage printed with no command is colored.
fn dispatch(
    cli: Cli,
    given: Values<'_>,
    shell: &mut Shell,
    help_color: clap::ColorChoice,
    stdout: &mut Box<dyn Write>,
    input: Input<'_>,
) -> Result<i32, Box<dyn CunoError>> {
    let env = given.env;
    // Destructured rather than ignored, so that adding a field to `Cli`
    // fails to compile here until it is handled.
    let Cli {
        color: _,
        verbose,
        quiet,
        command,
    } = cli;

    // Before anything is written, so no status line escapes `-q`.
    shell.set_verbosity(if quiet {
        Verbosity::Quiet
    } else if verbose {
        Verbosity::Verbose
    } else {
        Verbosity::Normal
    });

    #[cfg(debug_assertions)]
    test_trigger::fire(env)?;

    let (goal, opts) = match command {
        Some(Command::Build(opts)) => (build::Goal::Build, opts),
        Some(Command::Check {
            tests,
            all_targets,
            opts,
        }) => (
            // `--all-targets` wins over `--tests` (commands.md, "`cuno
            // build` / `cuno check`").
            build::Goal::Check {
                programs: !tests || all_targets,
                tests: tests || all_targets,
            },
            opts,
        ),
        Some(Command::Run { bin, opts, args }) => (build::Goal::Run { bin, args }, opts),
        Some(Command::Test {
            filter,
            nocapture,
            opts,
        }) => (build::Goal::Test { filter, nocapture }, opts),
        Some(Command::Clean {
            release,
            profile,
            target_dir,
        }) => {
            let cwd = given.cwd()?;
            let cli = CliSettings {
                target_dir,
                ..CliSettings::default()
            };
            let resolved = resolve_settings(
                Inputs {
                    cwd: &cwd,
                    env,
                    cores: given.cores,
                    cli: &cli,
                },
                shell,
            );
            clean::clean(
                clean::CleanArgs { release, profile },
                resolved,
                &cwd,
                given.host,
                shell,
            )?;
            return Ok(0);
        }
        Some(Command::New {
            path,
            lang,
            edition,
            name,
            vcs,
            lib,
        }) => {
            let cwd = given.cwd()?;
            resolve_user_settings(env, &cwd, shell).map_err(build::boxed)?;
            // clap admits only these values.
            let args = new::NewArgs {
                path,
                lang: lang
                    .map(|l| cuno_toolchain::flags::Lang::parse(&l).expect("a lang clap admits")),
                edition: edition.map(|e| {
                    cuno_toolchain::flags::Edition::parse(&e).expect("an edition clap admits")
                }),
                name,
                vcs: if vcs == "none" {
                    new::Vcs::None
                } else {
                    new::Vcs::Git
                },
                lib,
            };
            new::new(args, &cwd, shell).map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
            return Ok(0);
        }
        Some(Command::Init {
            path,
            lang,
            edition,
            name,
            vcs,
            lib,
        }) => {
            let cwd = given.cwd()?;
            resolve_user_settings(env, &cwd, shell).map_err(build::boxed)?;
            // clap admits only these values.
            let args = new::InitArgs {
                path: path.unwrap_or_else(|| PathBuf::from(".")),
                lang: lang
                    .map(|l| cuno_toolchain::flags::Lang::parse(&l).expect("a lang clap admits")),
                edition: edition.map(|e| {
                    cuno_toolchain::flags::Edition::parse(&e).expect("an edition clap admits")
                }),
                name,
                vcs: if vcs == "none" {
                    new::Vcs::None
                } else {
                    new::Vcs::Git
                },
                lib,
            };
            new::init(args, &cwd, given.host, shell)?;
            return Ok(0);
        }
        Some(Command::Fmt { check }) => {
            let cwd = given.cwd()?;
            let resolved = resolve_settings(
                Inputs {
                    cwd: &cwd,
                    env,
                    cores: given.cores,
                    cli: &CliSettings::default(),
                },
                shell,
            );
            return fmt::fmt(check, resolved, env, &cwd, given.host, given.temp, shell);
        }
        // --target-dir and -j reach lint through the settings, layered as the
        // build commands' are; --target is refused as theirs is, after the
        // settings are resolved and before anything is written
        // (docs/en/specs/dev-tools.md, "Target files").
        Some(Command::Lint {
            fix,
            compiler,
            target,
            target_dir,
            jobs,
            fetch,
        }) => {
            let cwd = given.cwd()?;
            let cli = CliSettings {
                compiler,
                target_dir,
                jobs,
            };
            let resolved = resolve_settings(
                Inputs {
                    cwd: &cwd,
                    env,
                    cores: given.cores,
                    cli: &cli,
                },
                shell,
            );
            build::refuse_target(target.as_deref())?;
            let resolved = resolved
                .and_then(|s| with_dependencies(s, fetch.into(), env, given.host, &cwd, shell));
            return lint::lint(fix, resolved, env, &cwd, given.host, given.temp, shell);
        }
        Some(Command::Doctor { compiler }) => {
            let cwd = given.cwd()?;
            let cli = CliSettings {
                compiler: compiler.clone(),
                ..CliSettings::default()
            };
            let resolved = resolve_settings(
                Inputs {
                    cwd: &cwd,
                    env,
                    cores: given.cores,
                    cli: &cli,
                },
                shell,
            );
            // The doctor fetches nothing and writes no Cuno.lock
            // (docs/en/specs/dependencies.md, "When sources are fetched and
            // what is used").
            let doctor_fetching = Fetching {
                network: cuno_deps::Network::Offline,
                lock: cuno_deps::LockMode::ReadOnly,
            };
            let resolved = resolved
                .and_then(|s| with_dependencies(s, doctor_fetching, env, given.host, &cwd, shell));
            let problems =
                doctor::doctor(compiler, resolved, env, &cwd, given.host, given.temp, shell);
            return Ok(if problems == 0 { 0 } else { 1 });
        }
        Some(
            command @ (Command::Add { .. }
            | Command::Remove { .. }
            | Command::Update { .. }
            | Command::Tree { .. }
            | Command::Fetch { .. }),
        ) => {
            let cwd = given.cwd()?;
            let resolved = resolve_settings(
                Inputs {
                    cwd: &cwd,
                    env,
                    cores: given.cores,
                    cli: &CliSettings::default(),
                },
                shell,
            );
            let host = given.host;
            return match command {
                Command::Add {
                    name,
                    git,
                    tag,
                    rev,
                    branch,
                    url,
                    path,
                    version,
                    offline,
                } => {
                    let reference = match (tag, rev, branch) {
                        (Some(tag), _, _) => cuno_manifest::GitReference::Tag(tag),
                        (_, Some(rev), _) => cuno_manifest::GitReference::Rev(rev),
                        (_, _, Some(branch)) => cuno_manifest::GitReference::Branch(branch),
                        (None, None, None) => cuno_manifest::GitReference::DefaultBranch,
                    };
                    let added = deps::NewDependency {
                        git,
                        reference,
                        url,
                        path,
                        version,
                    };
                    deps::add(name, added, offline, resolved, env, host, &cwd, shell)
                }
                Command::Remove { names, offline } => {
                    deps::remove(&names, offline, resolved, env, host, &cwd, shell)
                }
                Command::Update { name } => deps::update(name, resolved, env, host, &cwd, shell),
                Command::Tree { fetch } => deps::tree(
                    fetch.into(),
                    resolved,
                    env,
                    host,
                    &cwd,
                    stdout.as_mut(),
                    shell,
                ),
                Command::Fetch { fetch } => {
                    deps::fetch(fetch.into(), resolved, env, host, &cwd, shell)
                }
                _ => unreachable!("only the dependency commands come here"),
            };
        }
        Some(Command::Toolchain { command }) => {
            let cwd = given.cwd()?;
            let settings = resolve_settings(
                Inputs {
                    cwd: &cwd,
                    env,
                    cores: given.cores,
                    cli: &CliSettings::default(),
                },
                shell,
            )
            .map_err(build::boxed)?;
            return match command {
                ToolchainCommand::List => {
                    toolchain::list(&settings, env, given.host, stdout.as_mut(), shell)
                }
                ToolchainCommand::Default { compiler } => {
                    toolchain::default(&compiler, &settings, env, given.host, shell)
                }
            };
        }
        Some(Command::SelfCmd { command }) => {
            // Every layer, as for any command but `cuno new`
            // (docs/en/specs/commands.md, "Available for all commands"):
            // a broken configuration file stops it like any other.
            let cwd = given.cwd()?;
            resolve_settings(
                Inputs {
                    cwd: &cwd,
                    env,
                    cores: given.cores,
                    cli: &CliSettings::default(),
                },
                shell,
            )
            .map_err(build::boxed)?;
            return match command {
                SelfCommand::Update => self_cmd::update(given.exe, env, given.temp, shell),
                SelfCommand::Uninstall { yes } => {
                    self_cmd::uninstall(given.exe, env, yes, input, shell)
                }
            };
        }
        None => {
            // No command was given. Like Cargo, print the usage to stdout and
            // succeed; see docs/en/specs/commands.md, "Without a command
            // (`--version` / `--help` / no arguments)". A failed write (a
            // closed stdout) is ignored, matching what clap does for `--help`
            // and what Cargo does in both cases: the exit code stays 0.
            let usage = Cli::command().render_help();
            let _ = write_styled(stdout.as_mut(), &usage, help_color);
            return Ok(0);
        }
    };
    let cwd = given.cwd()?;
    let cli = CliSettings {
        compiler: opts.compiler.clone(),
        target_dir: opts.target_dir.clone(),
        jobs: opts.jobs,
    };
    let resolved = resolve_settings(
        Inputs {
            cwd: &cwd,
            env,
            cores: given.cores,
            cli: &cli,
        },
        shell,
    );
    build::build(
        goal,
        opts.into(),
        resolved,
        env,
        &cwd,
        given.host,
        given.temp,
        shell,
    )
}

/// Standard input, for the one command that asks.
pub(crate) struct Input<'a> {
    pub(crate) stdin: &'a mut dyn BufRead,
    pub(crate) is_terminal: bool,
}

/// The current directory cannot be read (deleted, or no permission).
#[derive(Debug)]
struct CwdError(String);

impl std::fmt::Display for CwdError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "cannot read the current directory: {}", self.0)
    }
}

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

impl CunoError for CwdError {
    fn exit_class(&self) -> cuno_core::ExitClass {
        cuno_core::ExitClass::Setup
    }
}

/// The one place an error is shown and turned into an exit code
/// (docs/en/specs/architecture.md, "What goes in `cuno-core`").
fn report(shell: &mut Shell, error: &dyn CunoError) -> i32 {
    shell.error(error);
    if let Some(help) = error.help() {
        shell.help(help);
    }
    error.exit_class().code()
}

/// A way for tests/cli.rs to make the binary fail before any command can, so
/// that the error path, colors and exit codes are tested through the real
/// process. Compiled into debug builds only (which is what `cargo test`
/// runs); release builds have no trace of it.
#[cfg(debug_assertions)]
mod test_trigger {
    use cuno_core::{CunoError, Env, ExitClass};

    /// `CUNO_TEST_TRIGGER=setup-error` fails with an exit-class-3 error that
    /// has a help line; `CUNO_TEST_TRIGGER=panic` panics.
    pub fn fire(env: &Env) -> Result<(), Box<dyn CunoError>> {
        match env.get("CUNO_TEST_TRIGGER").and_then(|v| v.to_str()) {
            Some("setup-error") => Err(Box::new(Triggered)),
            Some("panic") => panic!("triggered by CUNO_TEST_TRIGGER"),
            _ => Ok(()),
        }
    }

    #[derive(Debug)]
    struct Triggered;
    impl std::fmt::Display for Triggered {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("triggered by CUNO_TEST_TRIGGER")
        }
    }
    impl std::error::Error for Triggered {}
    impl CunoError for Triggered {
        fn exit_class(&self) -> ExitClass {
            ExitClass::Setup
        }
        fn help(&self) -> Option<String> {
            Some("unset CUNO_TEST_TRIGGER".into())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cuno_core::NameCase;
    use std::cell::RefCell;
    use std::rc::Rc;

    /// `--profile`'s help, which clap takes from a doc comment and cannot
    /// ask `Profile` for, names every profile `Profile` has, for every
    /// command that takes it.
    ///
    /// Mutation: add a profile to `Profile` without naming it in the help,
    /// or drop `release` from one command's help; this test fails.
    #[test]
    fn the_profile_help_names_every_profile() {
        let mut cli = Cli::command();
        for command in ["build", "check", "run", "test", "clean"] {
            let sub = cli.find_subcommand_mut(command).expect(command);
            let help = sub
                .get_arguments()
                .find(|a| a.get_id() == "profile")
                .and_then(|a| a.get_help())
                .map(|h| h.to_string())
                .expect(command);
            for (_, name) in cuno_manifest::Profile::ALL {
                assert!(help.contains(name), "{command}: {help}");
            }
        }
    }

    /// A stream the test reads back after `run` has written to it. With
    /// `buffered`, what is written reaches it only when flushed, as through
    /// a buffered writer.
    #[derive(Clone, Default)]
    struct Captured {
        text: Rc<RefCell<Vec<u8>>>,
        pending: Rc<RefCell<Vec<u8>>>,
        buffered: bool,
    }

    impl Write for Captured {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            let to = if self.buffered {
                &self.pending
            } else {
                &self.text
            };
            to.borrow_mut().extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            let pending = std::mem::take(&mut *self.pending.borrow_mut());
            self.text.borrow_mut().extend(pending);
            Ok(())
        }
    }

    impl Captured {
        fn text(&self) -> String {
            String::from_utf8(self.text.borrow().clone()).unwrap()
        }
    }

    /// How a run is set up: whether each stream is a terminal, the current
    /// directory, and whether stdout buffers.
    struct Setup {
        stdout_is_terminal: bool,
        stderr_is_terminal: bool,
        cwd: Result<PathBuf, String>,
        buffered: bool,
    }

    /// `cuno <args>` run with `setup`, in a directory holding no project and
    /// a cuno home of its own: the exit code, stdout and stderr.
    fn run_with(args: &[&str], setup: Setup) -> (i32, String, String) {
        let dir = tempfile::tempdir().unwrap();
        let env = Env::from_pairs(
            [("CUNO_HOME".into(), dir.path().join("home").into_os_string())],
            NameCase::Insensitive,
        );
        let stdout = Captured {
            buffered: setup.buffered,
            ..Captured::default()
        };
        let stderr = Captured::default();
        let code = run(Process {
            args: std::iter::once("cuno")
                .chain(args.iter().copied())
                .map(OsString::from)
                .collect(),
            env,
            cwd: setup.cwd.map(|_| dir.path().to_owned()),
            host: HostOs::Windows,
            temp: dir.path().to_owned(),
            exe: Err("not needed".to_owned()),
            cores: NonZeroU32::new(2).unwrap(),
            stdout: Box::new(stdout.clone()),
            stdout_is_terminal: setup.stdout_is_terminal,
            stderr: Box::new(stderr.clone()),
            stderr_is_terminal: setup.stderr_is_terminal,
            stdin: Box::new(std::io::empty()),
            stdin_is_terminal: false,
        });
        (code, stdout.text(), stderr.text())
    }

    fn terminals(stdout_is_terminal: bool, stderr_is_terminal: bool) -> Setup {
        Setup {
            stdout_is_terminal,
            stderr_is_terminal,
            cwd: Ok(PathBuf::new()),
            buffered: false,
        }
    }

    const ESC: char = '\u{1b}';

    /// Each stream is colored by whether it is the terminal, not the other:
    /// help and the usage on stdout, a usage error and cuno's own `error:`
    /// on stderr (`docs/en/specs/commands.md`, "Available for all
    /// commands").
    ///
    /// Mutation: decide a stream's color from the other stream's terminal,
    /// give the shell stdout's, write clap's message in the other stream's
    /// color, or color the usage with stderr's; this test fails.
    #[test]
    fn each_stream_is_colored_by_its_own_terminal() {
        for (stdout_tty, stderr_tty) in [(true, false), (false, true)] {
            let at = format!("stdout terminal {stdout_tty}, stderr terminal {stderr_tty}");
            let (code, out, _) = run_with(&["--help"], terminals(stdout_tty, stderr_tty));
            assert_eq!((code, out.contains(ESC)), (0, stdout_tty), "{at}: {out}");
            let (code, out, _) = run_with(&[], terminals(stdout_tty, stderr_tty));
            assert_eq!((code, out.contains(ESC)), (0, stdout_tty), "{at}: {out}");
            let (code, out, err) = run_with(&["bogus"], terminals(stdout_tty, stderr_tty));
            assert_eq!((code, out.as_str()), (2, ""), "{at}");
            assert_eq!(err.contains(ESC), stderr_tty, "{at}: {err}");
            let (code, _, err) = run_with(&["clean"], terminals(stdout_tty, stderr_tty));
            assert_eq!(code, 3, "{at}: {err}");
            assert_eq!(err.contains(ESC), stderr_tty, "{at}: {err}");
        }
    }

    /// A current directory that cannot be read is reported, exit code 3, by
    /// every command that needs one, and help still works without one.
    ///
    /// Mutation: run a command somewhere else instead, change the message
    /// or its exit class, or read the directory before `--help`; this test
    /// fails.
    #[test]
    fn an_unreadable_current_directory_is_reported_by_each_command() {
        let unreadable = || Setup {
            cwd: Err("gone".to_owned()),
            ..terminals(false, false)
        };
        for args in [
            &["build"][..],
            &["check"],
            &["run"],
            &["test"],
            &["clean"],
            &["doctor"],
            &["new", "app"],
        ] {
            let (code, _, err) = run_with(args, unreadable());
            assert_eq!(code, 3, "{args:?}: {err}");
            assert_eq!(
                err, "error: cannot read the current directory: gone\n",
                "{args:?}"
            );
        }
        let (code, out, _) = run_with(&["--help"], unreadable());
        assert_eq!(code, 0);
        assert!(out.starts_with("Everything C/C++"), "{out}");
    }

    /// What clap makes is flushed, so it is not lost in a buffered stream
    /// when the process ends.
    ///
    /// Mutation: leave out the flush in `write_styled`; this test fails.
    #[test]
    fn help_is_flushed() {
        let (code, out, _) = run_with(
            &["--help"],
            Setup {
                buffered: true,
                ..terminals(false, false)
            },
        );
        assert_eq!(code, 0);
        assert!(out.starts_with("Everything C/C++"), "{out:?}");
    }

    /// Mutation: swap any two arms of `From<Color> for ColorChoice`; this
    /// test fails.
    #[test]
    fn color_values_map_to_the_same_choice() {
        assert_eq!(ColorChoice::from(Color::Auto), ColorChoice::Auto);
        assert_eq!(ColorChoice::from(Color::Always), ColorChoice::Always);
        assert_eq!(ColorChoice::from(Color::Never), ColorChoice::Never);
    }

    fn given(args: &[&str]) -> Option<ColorChoice> {
        let args: Vec<OsString> = std::iter::once("cuno")
            .chain(args.iter().copied())
            .map(OsString::from)
            .collect();
        color_before_parsing(&args)
    }

    /// Mutation: read only one of the two spellings, take the first
    /// `--color` instead of the last, read past `--`, or keep an earlier
    /// value past an invalid one, a missing one or one that is not Unicode;
    /// this test fails.
    #[test]
    fn the_color_is_read_before_parsing() {
        assert_eq!(
            given(&["--color", "never", "build"]),
            Some(ColorChoice::Never)
        );
        assert_eq!(
            given(&["build", "--color=always"]),
            Some(ColorChoice::Always)
        );
        assert_eq!(
            given(&["--color", "never", "build", "--color", "always"]),
            Some(ColorChoice::Always)
        );
        assert_eq!(given(&["run", "--", "--color", "never"]), None);
        assert_eq!(given(&["--color", "bogus"]), None);
        assert_eq!(given(&["--color=never", "--color=bogus"]), None);
        assert_eq!(given(&["build"]), None);
        assert_eq!(given(&["--color=always", "--color"]), None);
        #[cfg(windows)]
        {
            use std::os::windows::ffi::OsStringExt;
            let lone = OsString::from_wide(&[0xD800]);
            let mut equals = OsString::from("--color=");
            equals.push(&lone);
            for bad in [vec![OsString::from("--color"), lone], vec![equals]] {
                let args: Vec<OsString> = ["cuno", "--color", "always"]
                    .into_iter()
                    .map(OsString::from)
                    .chain(bad)
                    .collect();
                assert_eq!(color_before_parsing(&args), None, "{args:?}");
            }
        }
    }

    /// Mutation: hand clap its own `Auto`, let NO_COLOR beat a choice given,
    /// or ignore it with none; this test fails.
    #[test]
    fn what_clap_prints_follows_cunos_order() {
        use clap::ColorChoice as Clap;
        assert_eq!(
            parser_color(Some(ColorChoice::Always), true, false),
            Clap::Always
        );
        assert_eq!(
            parser_color(Some(ColorChoice::Never), false, true),
            Clap::Never
        );
        assert_eq!(
            parser_color(Some(ColorChoice::Auto), true, true),
            Clap::Always
        );
        assert_eq!(
            parser_color(Some(ColorChoice::Auto), false, false),
            Clap::Never
        );
        assert_eq!(parser_color(None, true, true), Clap::Never);
        assert_eq!(parser_color(None, false, true), Clap::Always);
        assert_eq!(parser_color(None, false, false), Clap::Never);
    }

    /// `cuno self uninstall` through the whole command line: without `-y`
    /// and with no terminal it refuses, with `-y` (or `--yes`) it removes.
    /// The cuno it runs as is placed outside its home, so no `PATH` is
    /// edited and nothing is left running.
    ///
    /// Mutation: pass `!yes`, drop `-y`'s short name, or pass the terminal
    /// flag as true; this test fails.
    #[test]
    fn self_uninstall_takes_yes_and_the_terminal_from_the_command_line() {
        for (args, code, gone) in [
            (vec!["self", "uninstall"], 2, false),
            (vec!["self", "uninstall", "-y"], 0, true),
            (vec!["self", "uninstall", "--yes"], 0, true),
        ] {
            let dir = tempfile::tempdir().unwrap();
            let home = dir.path().join("home");
            std::fs::create_dir_all(&home).unwrap();
            std::fs::write(home.join("config.toml"), "").unwrap();
            let env = Env::from_pairs(
                [
                    ("CUNO_HOME".into(), home.clone().into_os_string()),
                    (
                        "USERPROFILE".into(),
                        dir.path().join("user").into_os_string(),
                    ),
                ],
                NameCase::Insensitive,
            );
            let stderr = Captured::default();
            let got = run(Process {
                args: std::iter::once("cuno")
                    .chain(args.iter().copied())
                    .map(OsString::from)
                    .collect(),
                env,
                cwd: Ok(dir.path().to_owned()),
                host: HostOs::Windows,
                temp: dir.path().to_owned(),
                exe: Ok(dir.path().join("tools").join("cuno.exe")),
                cores: NonZeroU32::new(2).unwrap(),
                stdout: Box::new(Captured::default()),
                stdout_is_terminal: false,
                stderr: Box::new(stderr.clone()),
                stderr_is_terminal: false,
                stdin: Box::new(std::io::empty()),
                stdin_is_terminal: false,
            });
            assert_eq!(got, code, "{args:?}: {}", stderr.text());
            assert_eq!(!home.exists(), gone, "{args:?}");
        }
    }
}