Skip to main content

cuno_cli/
lib.rs

1//! The `cuno` command line: parses it, resolves the settings, dispatches to
2//! a command and reports what went wrong, from values the binary collected
3//! from the process. Each command is a module that combines the other crates
4//! and shows the result.
5//!
6//! See `docs/en/specs/commands.md` for the commands, options, output and exit
7//! codes, and `docs/en/specs/architecture.md`, "What goes in `src/` and
8//! `cuno-cli`", for what belongs here.
9
10mod build;
11mod clean;
12mod deps;
13mod doctor;
14mod fmt;
15mod lint;
16mod new;
17mod self_cmd;
18mod toolchain;
19
20use std::ffi::OsString;
21use std::io::{BufRead, Write};
22use std::num::NonZeroU32;
23use std::path::{Path, PathBuf};
24
25use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
26use cuno_core::{ColorChoice, CunoError, Env, ExitClass, Shell, Verbosity};
27use cuno_manifest::{CliSettings, ConfigError, Inputs, Settings};
28
29// So the binary, which may depend only on this crate and `cuno-core`, can
30// name the host it collects (`architecture.md`, "Dependencies between
31// crates").
32pub use cuno_toolchain::HostOs;
33
34/// What only the process has, collected by the binary and handed in as
35/// values: no library reads the process itself (`docs/en/specs/
36/// architecture.md`, "Dependencies between crates").
37pub struct Process {
38    /// The command line, the program's name first.
39    pub args: Vec<OsString>,
40    /// The environment variables.
41    pub env: Env,
42    /// The current directory, or why it cannot be read. Only a command that
43    /// needs it reports the reason, so `--help` works without one.
44    pub cwd: Result<PathBuf, String>,
45    /// The operating system cuno runs on.
46    pub host: HostOs,
47    /// The temporary directory.
48    pub temp: PathBuf,
49    /// Where the running executable is, or why that cannot be found. Only
50    /// `cuno self` needs it.
51    pub exe: Result<PathBuf, String>,
52    /// How many processors this machine has: the default number of jobs.
53    pub cores: NonZeroU32,
54    /// Standard output: help, the version and the usage. Any writer, so a
55    /// test can read what was written.
56    pub stdout: Box<dyn Write>,
57    /// Whether standard output is a terminal.
58    pub stdout_is_terminal: bool,
59    /// Standard error: everything else cuno prints.
60    pub stderr: Box<dyn Write>,
61    /// Whether standard error is a terminal.
62    pub stderr_is_terminal: bool,
63    /// Standard input: the answer to a question cuno asks.
64    pub stdin: Box<dyn BufRead>,
65    /// Whether standard input is a terminal; cuno only asks one that is.
66    pub stdin_is_terminal: bool,
67}
68
69/// The top-level command line. Subcommands are added with the milestones that
70/// implement them (docs/en/roadmap.md).
71#[derive(Parser)]
72#[command(
73    // `name` is what `--version` prints ("cuno <version>"); `bin_name` is what
74    // the usage line prints. Without `bin_name`, clap takes the executable's
75    // file name, which is `cuno.exe` on Windows.
76    name = "cuno",
77    bin_name = "cuno",
78    version,
79    // Taken from `description` in Cargo.toml, so the two cannot drift apart.
80    about
81)]
82struct Cli {
83    // The line below is the help text `cuno --help` prints for this option,
84    // pinned by tests/cli.rs. `None` when not given: `[term] color`, then
85    // NO_COLOR, apply only then (docs/en/specs/commands.md, "Available for
86    // all commands").
87    /// Coloring
88    #[arg(long, value_name = "WHEN", value_enum, global = true)]
89    color: Option<Color>,
90
91    /// Show more, such as each command a build runs
92    #[arg(short, long, global = true, conflicts_with = "quiet")]
93    verbose: bool,
94
95    /// Show only errors, warnings and the compilers' output
96    #[arg(short, long, global = true)]
97    quiet: bool,
98
99    #[command(subcommand)]
100    command: Option<Command>,
101}
102
103/// The commands (docs/en/specs/commands.md).
104#[derive(Subcommand)]
105enum Command {
106    /// Create a new package
107    New {
108        /// Where to create it
109        #[arg(value_name = "PATH")]
110        path: PathBuf,
111        /// The language (c / c++; default c++)
112        #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
113        lang: Option<String>,
114        /// The language standard (c++17 / c++20 / c++23 / c11 / c17 / c23)
115        #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
116        edition: Option<String>,
117        /// The package's name (default: the directory's)
118        #[arg(long, value_name = "NAME")]
119        name: Option<String>,
120        /// Version control (git / none)
121        #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
122        vcs: String,
123        /// Make a library package
124        #[arg(long)]
125        lib: bool,
126    },
127    /// Make an existing directory into a package
128    Init {
129        /// The directory (default: the current one)
130        #[arg(value_name = "PATH")]
131        path: Option<PathBuf>,
132        /// The language (c / c++; default: the sources', else c++)
133        #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
134        lang: Option<String>,
135        /// The language standard (c++17 / c++20 / c++23 / c11 / c17 / c23)
136        #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
137        edition: Option<String>,
138        /// The package's name (default: the directory's)
139        #[arg(long, value_name = "NAME")]
140        name: Option<String>,
141        /// Version control (git / none)
142        #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
143        vcs: String,
144        /// Make a library package
145        #[arg(long)]
146        lib: bool,
147    },
148    /// Compile the package
149    Build(BuildOpts),
150    /// Check the package for errors without building it
151    Check {
152        /// Check the tests instead of the program
153        #[arg(long)]
154        tests: bool,
155        /// Check both the program and the tests
156        #[arg(long)]
157        all_targets: bool,
158        #[command(flatten)]
159        opts: BuildOpts,
160    },
161    /// Build the package and run one of its executables
162    Run {
163        /// The executable to run, when there are several
164        #[arg(long, value_name = "NAME")]
165        bin: Option<String>,
166        #[command(flatten)]
167        opts: BuildOpts,
168        /// Arguments for the program
169        #[arg(last = true, value_name = "ARGS")]
170        args: Vec<OsString>,
171    },
172    /// Build the package's tests and run them
173    Test {
174        /// Run only the tests whose names contain this
175        #[arg(value_name = "FILTER")]
176        filter: Option<String>,
177        /// Show every test's output, not only a failed one's
178        #[arg(long)]
179        nocapture: bool,
180        #[command(flatten)]
181        opts: BuildOpts,
182    },
183    /// Format the package's code with clang-format
184    Fmt {
185        /// Do not format; fail if any file is not formatted (for CI)
186        #[arg(long)]
187        check: bool,
188    },
189    /// Analyse the package's code with clang-tidy
190    // The build commands' --target, --target-dir and -j are declared again
191    // here rather than through `BuildOpts`, which would bring --release and
192    // --profile, which lint refuses (docs/en/specs/dev-tools.md, "Target
193    // files"); the help text says what each does for lint.
194    Lint {
195        /// Fix what clang-tidy can, in the sources themselves
196        #[arg(long)]
197        fix: bool,
198        /// The compiler whose commands are analysed (msvc / clang / clang-cl / gcc / safec)
199        #[arg(long, value_name = "NAME")]
200        compiler: Option<String>,
201        /// The target to analyse for (reserved: an error for now)
202        #[arg(long, value_name = "TRIPLE")]
203        target: Option<String>,
204        /// The build's output directory, which the analysed commands name
205        #[arg(long, value_name = "PATH")]
206        target_dir: Option<PathBuf>,
207        /// How many sources to analyse at once (default: the number of cores)
208        #[arg(short, long, value_name = "N")]
209        jobs: Option<NonZeroU32>,
210        #[command(flatten)]
211        fetch: FetchOpts,
212    },
213    /// Remove the build's output
214    Clean {
215        /// Remove only the release profile's output
216        #[arg(long, conflicts_with = "profile")]
217        release: bool,
218        /// Remove only the given profile's output (dev / release)
219        #[arg(long, value_name = "NAME")]
220        profile: Option<String>,
221        /// The output directory to remove from
222        #[arg(long, value_name = "PATH")]
223        target_dir: Option<PathBuf>,
224    },
225    /// Diagnose the environment and show a fix for each problem
226    Doctor {
227        /// The compiler to diagnose (msvc / clang / clang-cl / gcc / safec)
228        #[arg(long, value_name = "NAME")]
229        compiler: Option<String>,
230    },
231    /// Add a dependency to Cuno.toml, fetch it and record it in Cuno.lock
232    #[command(group(clap::ArgGroup::new("source").args(["git", "url", "path"]).multiple(false)))]
233    #[command(group(clap::ArgGroup::new("reference").args(["tag", "rev", "branch"]).multiple(false).requires("git")))]
234    Add {
235        /// A dependency by its name alone (not available yet)
236        #[arg(value_name = "NAME", conflicts_with = "source")]
237        name: Option<String>,
238        /// From a Git repository
239        #[arg(long, value_name = "URL")]
240        git: Option<String>,
241        /// The tag to check out, with --git
242        #[arg(long, value_name = "TAG")]
243        tag: Option<String>,
244        /// The commit to check out, with --git
245        #[arg(long, value_name = "COMMIT")]
246        rev: Option<String>,
247        /// The branch to check out, with --git
248        #[arg(long, value_name = "BRANCH")]
249        branch: Option<String>,
250        /// From an archive (.zip / .tar.gz)
251        #[arg(long, value_name = "URL")]
252        url: Option<String>,
253        /// From a package on this machine
254        #[arg(long, value_name = "PATH")]
255        path: Option<PathBuf>,
256        /// A condition the package's version must satisfy
257        #[arg(long, value_name = "CONDITION")]
258        version: Option<String>,
259        /// Do not use the network; fail if the source is not in the cache
260        #[arg(long)]
261        offline: bool,
262    },
263    /// Remove dependencies from Cuno.toml
264    Remove {
265        /// The dependencies to remove
266        #[arg(value_name = "NAME", required = true)]
267        names: Vec<String>,
268        /// Do not use the network; fail if a dependency is not in the cache
269        #[arg(long)]
270        offline: bool,
271    },
272    /// Fetch the dependencies again and record what they are now
273    Update {
274        /// Only this dependency, and what it depends on
275        #[arg(value_name = "NAME")]
276        name: Option<String>,
277    },
278    /// Show the dependency graph
279    Tree {
280        #[command(flatten)]
281        fetch: FetchOpts,
282    },
283    /// Fetch the dependencies and write Cuno.lock, without building
284    Fetch {
285        #[command(flatten)]
286        fetch: FetchOpts,
287    },
288    /// List the compilers cuno finds, or choose the default one
289    Toolchain {
290        #[command(subcommand)]
291        command: ToolchainCommand,
292    },
293    /// Update cuno itself
294    #[command(name = "self")]
295    SelfCmd {
296        #[command(subcommand)]
297        command: SelfCommand,
298    },
299}
300
301/// `cuno self`'s commands (docs/en/specs/commands.md).
302#[derive(Subcommand)]
303enum SelfCommand {
304    /// Update cuno to the latest release
305    Update,
306    /// Remove cuno's home and, if its installer placed it, cuno itself
307    Uninstall {
308        /// Remove without asking
309        #[arg(short = 'y', long)]
310        yes: bool,
311    },
312}
313
314/// `cuno toolchain`'s commands (docs/en/specs/commands.md).
315#[derive(Subcommand)]
316enum ToolchainCommand {
317    /// List the compilers and tools cuno finds, and which one builds use
318    List,
319    /// Make a compiler this user's default
320    Default {
321        /// The compiler (msvc / clang / clang-cl / gcc)
322        #[arg(value_name = "COMPILER")]
323        compiler: String,
324    },
325}
326
327/// The options of the build commands (docs/en/specs/commands.md, "Available for
328/// build commands (`build` / `run` / `check` / `test`)").
329#[derive(Args)]
330struct BuildOpts {
331    /// Build with the release profile
332    #[arg(long, conflicts_with = "profile")]
333    release: bool,
334    /// Build with the given profile (dev / release)
335    #[arg(long, value_name = "NAME")]
336    profile: Option<String>,
337    /// The compiler to use (msvc / clang / clang-cl / gcc / safec)
338    #[arg(long, value_name = "NAME")]
339    compiler: Option<String>,
340    /// Cross-compile for a target (reserved)
341    #[arg(long, value_name = "TRIPLE")]
342    target: Option<String>,
343    /// Where to put the build's output
344    #[arg(long, value_name = "PATH")]
345    target_dir: Option<PathBuf>,
346    /// How many steps to run at once (default: the number of cores)
347    #[arg(short, long, value_name = "N")]
348    jobs: Option<NonZeroU32>,
349    #[command(flatten)]
350    fetch: FetchOpts,
351}
352
353/// `--locked` and `--offline` (docs/en/specs/commands.md, "Available for
354/// build commands and `lint` (`build` / `run` / `check` / `test` /
355/// `lint`)").
356#[derive(Args, Clone, Copy)]
357struct FetchOpts {
358    /// Fail if Cuno.lock would need rewriting (for CI)
359    #[arg(long)]
360    locked: bool,
361    /// Do not use the network; fail if a dependency is not in the cache
362    #[arg(long)]
363    offline: bool,
364}
365
366impl From<FetchOpts> for Fetching {
367    fn from(o: FetchOpts) -> Fetching {
368        Fetching {
369            network: if o.offline {
370                cuno_deps::Network::Offline
371            } else {
372                cuno_deps::Network::Online
373            },
374            lock: if o.locked {
375                cuno_deps::LockMode::Locked
376            } else {
377                cuno_deps::LockMode::Write
378            },
379        }
380    }
381}
382
383impl From<BuildOpts> for build::BuildArgs {
384    fn from(o: BuildOpts) -> build::BuildArgs {
385        build::BuildArgs {
386            release: o.release,
387            profile: o.profile,
388            target: o.target,
389            fetching: o.fetch.into(),
390        }
391    }
392}
393
394/// The `--color` the command line gives, read before clap parses it so
395/// that what clap prints follows it too: the last one before a bare `--`
396/// (what follows belongs to the program `cuno run` runs), as
397/// `--color <when>` or `--color=<when>`. A value that is not one of
398/// `--color`'s counts as none, so the usage error it causes is colored as if
399/// `--color` were not given.
400fn color_before_parsing(args: &[OsString]) -> Option<ColorChoice> {
401    let mut found = None;
402    let mut args = args.iter().skip(1);
403    while let Some(arg) = args.next() {
404        // `Some(None)` is a `--color` whose value is missing or not
405        // Unicode, which counts as none like any other invalid value.
406        let value = match arg.to_str() {
407            Some("--") => break,
408            Some("--color") => Some(args.next().and_then(|v| v.to_str())),
409            Some(arg) => arg.strip_prefix("--color=").map(Some),
410            None => arg
411                .as_encoded_bytes()
412                .starts_with(b"--color=")
413                .then_some(None),
414        };
415        if let Some(value) = value {
416            found = Some(
417                value
418                    .and_then(|v| Color::from_str(v, false).ok())
419                    .map(ColorChoice::from),
420            );
421        }
422    }
423    found.flatten()
424}
425
426/// Whether what clap makes is written with its colors on a stream, by
427/// [`cuno_core::colors`] with no configured choice: clap prints before the
428/// files are read. Never clap's own `Auto`, which reads `CLICOLOR_FORCE`, a
429/// variable cuno does not read.
430fn parser_color(given: Option<ColorChoice>, no_color: bool, terminal: bool) -> clap::ColorChoice {
431    if cuno_core::colors(given, None, no_color, terminal) {
432        clap::ColorChoice::Always
433    } else {
434        clap::ColorChoice::Never
435    }
436}
437
438/// The values of `--color`. A separate type because `cuno-core` does not
439/// depend on clap.
440#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
441enum Color {
442    Auto,
443    Always,
444    Never,
445}
446
447impl From<Color> for ColorChoice {
448    fn from(color: Color) -> ColorChoice {
449        match color {
450            Color::Auto => ColorChoice::Auto,
451            Color::Always => ColorChoice::Always,
452            Color::Never => ColorChoice::Never,
453        }
454    }
455}
456
457/// Carries out the command line `process` holds and returns the exit code
458/// for the binary to end with.
459pub fn run(process: Process) -> i32 {
460    let Process {
461        args,
462        env,
463        cwd,
464        host,
465        temp,
466        exe,
467        cores,
468        mut stdout,
469        stdout_is_terminal,
470        mut stderr,
471        stderr_is_terminal,
472        mut stdin,
473        stdin_is_terminal,
474    } = process;
475    // What clap prints itself is colored by cuno's rule, not clap's
476    // (docs/en/specs/commands.md, "Available for all commands"): `--color`
477    // as written, then NO_COLOR, then whether the output is a terminal.
478    let given = color_before_parsing(&args);
479    let no_color = env.get("NO_COLOR").is_some();
480    let stdout_color = parser_color(given, no_color, stdout_is_terminal);
481    let stderr_color = parser_color(given, no_color, stderr_is_terminal);
482    // On `--version`, `--help` and usage errors, what clap made is printed
483    // and its code returned: 0 for the first two and 2 for a usage error, as
484    // the spec's exit codes require. What clap makes carries its styles
485    // whatever color the command is given; whether they are written is
486    // decided per stream, in `write_styled`.
487    let cli = match Cli::command().try_get_matches_from(&args) {
488        // Formatted against the command, as `Cli::parse` does, so such an
489        // error would carry the usage line too.
490        Ok(matches) => match Cli::from_arg_matches(&matches) {
491            Ok(cli) => cli,
492            Err(e) => {
493                let e = e.format(&mut Cli::command());
494                return print_clap(&e, stdout_color, stderr_color, &mut stdout, &mut stderr);
495            }
496        },
497        Err(error) => {
498            return print_clap(&error, stdout_color, stderr_color, &mut stdout, &mut stderr);
499        }
500    };
501    let mut shell = Shell::new(
502        stderr,
503        cli.color.map(ColorChoice::from),
504        &env,
505        stderr_is_terminal,
506    );
507    let given = Values {
508        env: &env,
509        cwd: &cwd,
510        exe: &exe,
511        host,
512        temp: &temp,
513        cores,
514    };
515    let input = Input {
516        stdin: stdin.as_mut(),
517        is_terminal: stdin_is_terminal,
518    };
519    match dispatch(cli, given, &mut shell, stdout_color, &mut stdout, input) {
520        Ok(code) => code,
521        Err(error) => report(&mut shell, &*error),
522    }
523}
524
525/// What clap made for `--help`, `--version` or a usage error, written where
526/// clap writes it (stdout for the first two, stderr for an error) in that
527/// stream's color, and its exit code.
528fn print_clap(
529    error: &clap::Error,
530    stdout_color: clap::ColorChoice,
531    stderr_color: clap::ColorChoice,
532    stdout: &mut Box<dyn Write>,
533    stderr: &mut Box<dyn Write>,
534) -> i32 {
535    let (out, color) = if error.use_stderr() {
536        (stderr, stderr_color)
537    } else {
538        (stdout, stdout_color)
539    };
540    // A failed write (a closed stream) is ignored, as clap ignores it: the
541    // exit code stays clap's.
542    let _ = write_styled(out.as_mut(), &error.render(), color);
543    error.exit_code()
544}
545
546/// `text` written plain, or with its colors when `color` says so. clap's
547/// own printing writes to the process's streams and exits, which a library
548/// may not, so what clap makes is written here to the streams given.
549fn write_styled(
550    out: &mut dyn Write,
551    text: &clap::builder::StyledStr,
552    color: clap::ColorChoice,
553) -> std::io::Result<()> {
554    match color {
555        clap::ColorChoice::Always => write!(out, "{}", text.ansi())?,
556        _ => write!(out, "{text}")?,
557    }
558    out.flush()
559}
560
561/// The values the commands take from [`Process`], borrowed once the
562/// standard streams have gone to the shell and to the usage.
563#[derive(Clone, Copy)]
564struct Values<'a> {
565    env: &'a Env,
566    cwd: &'a Result<PathBuf, String>,
567    host: HostOs,
568    temp: &'a Path,
569    exe: &'a Result<PathBuf, String>,
570    cores: NonZeroU32,
571}
572
573impl Values<'_> {
574    /// The current directory, or the error a command reports without it.
575    fn cwd(&self) -> Result<PathBuf, Box<dyn CunoError>> {
576        self.cwd
577            .clone()
578            .map_err(|e| Box::new(CwdError(e)) as Box<dyn CunoError>)
579    }
580}
581
582/// The settings, with `[term] color` applied to `shell` before the warnings
583/// they raised are printed, so every command colors as configured
584/// (`docs/en/specs/commands.md`, "Available for all commands"). An error
585/// comes back before any configuration file is applied, so it is shown as
586/// `--color` and `NO_COLOR` alone decide.
587fn resolve_settings(inputs: Inputs<'_>, shell: &mut Shell) -> Result<Settings, ConfigError> {
588    let loaded = cuno_manifest::resolve(inputs)?;
589    shell.configure(loaded.value.color, loaded.value.verbose);
590    for warning in &loaded.warnings {
591        shell.warning(warning);
592    }
593    Ok(loaded.value)
594}
595
596/// What resolving dependencies may do: use the network, and write
597/// `Cuno.lock`.
598#[derive(Clone, Copy, Debug)]
599pub(crate) struct Fetching {
600    pub(crate) network: cuno_deps::Network,
601    pub(crate) lock: cuno_deps::LockMode,
602}
603
604/// What `BuildArgs`, which derives `Default`, holds when no option is
605/// given.
606impl Default for Fetching {
607    /// Fetch what is missing, and write `Cuno.lock`.
608    fn default() -> Fetching {
609        Fetching {
610            network: cuno_deps::Network::Online,
611            lock: cuno_deps::LockMode::Write,
612        }
613    }
614}
615
616/// `path` as a command's argument gave it (`cuno new`, `cuno init`, `cuno
617/// add --path`), resolved against `cwd` the way every path the user writes
618/// is (`cuno_manifest`'s `resolve_path`): a path that depends on the
619/// current drive is refused, with the same error wherever it was given.
620pub(crate) fn argument_path(path: &Path, cwd: &Path) -> Result<PathBuf, DriveRelativePath> {
621    cuno_manifest::resolve_path(path, cwd).map_err(|_| DriveRelativePath(path.to_owned()))
622}
623
624/// A path argument that depends on the current drive on Windows (`/x`,
625/// `C:x`): exit code 3 (`docs/en/specs/commands.md`, "`cuno new <path>`").
626#[derive(Debug)]
627pub(crate) struct DriveRelativePath(pub(crate) PathBuf);
628
629impl std::fmt::Display for DriveRelativePath {
630    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
631        write!(
632            f,
633            "the path is `{}`, which depends on the current drive",
634            self.0.display()
635        )
636    }
637}
638
639impl std::error::Error for DriveRelativePath {}
640
641impl CunoError for DriveRelativePath {
642    fn exit_class(&self) -> ExitClass {
643        ExitClass::Setup
644    }
645
646    fn help(&self) -> Option<String> {
647        Some("write an absolute path, or a path relative to the current directory".to_owned())
648    }
649}
650
651/// `settings` with the project's dependencies resolved, fetched as
652/// `fetching` allows (`docs/en/specs/dependencies.md`, "Resolution" and
653/// "When sources are fetched and what is used"), and their warnings
654/// printed: for the commands that build or analyse the package, which see
655/// the same dependencies. `cuno fmt` reads none, as it formats the
656/// package's own files alone. A command calls it once its own arguments are
657/// checked, so that an error in them is reported before anything is
658/// fetched.
659pub(crate) fn with_dependencies(
660    mut settings: Settings,
661    fetching: Fetching,
662    env: &cuno_core::Env,
663    host: cuno_toolchain::HostOs,
664    cwd: &Path,
665    shell: &mut Shell,
666) -> Result<Settings, ConfigError> {
667    if let Some(package) = settings.project.take() {
668        let resolved = deps::with_resolve_options(
669            &settings,
670            fetching,
671            cuno_deps::Forget::Nothing,
672            &[],
673            env,
674            host,
675            cwd,
676            |options| cuno_deps::resolve(package, options, shell),
677        )?;
678        for (verb, text) in &resolved.changes {
679            shell.status(verb, text);
680        }
681        for warning in &resolved.warnings {
682            shell.warning(warning);
683        }
684        settings.project = Some(resolved.root);
685    }
686    Ok(settings)
687}
688
689/// `cuno new`'s settings: the user's `[term]` alone, applied to `shell`,
690/// since the project around the new package is not its own
691/// (`docs/en/specs/commands.md`, "Available for all commands").
692fn resolve_user_settings(env: &Env, cwd: &Path, shell: &mut Shell) -> Result<(), ConfigError> {
693    let loaded = cuno_manifest::resolve_user(env, cwd)?;
694    shell.configure(loaded.value.color, loaded.value.verbose);
695    for warning in &loaded.warnings {
696        shell.warning(warning);
697    }
698    Ok(())
699}
700
701/// Carries out the parsed command line and returns the exit code. Every
702/// error a command can meet comes back here rather than being printed where
703/// it happens; `doctor` prints its problems itself and only says how many.
704/// `help_color` is how the usage printed with no command is colored.
705fn dispatch(
706    cli: Cli,
707    given: Values<'_>,
708    shell: &mut Shell,
709    help_color: clap::ColorChoice,
710    stdout: &mut Box<dyn Write>,
711    input: Input<'_>,
712) -> Result<i32, Box<dyn CunoError>> {
713    let env = given.env;
714    // Destructured rather than ignored, so that adding a field to `Cli`
715    // fails to compile here until it is handled.
716    let Cli {
717        color: _,
718        verbose,
719        quiet,
720        command,
721    } = cli;
722
723    // Before anything is written, so no status line escapes `-q`.
724    shell.set_verbosity(if quiet {
725        Verbosity::Quiet
726    } else if verbose {
727        Verbosity::Verbose
728    } else {
729        Verbosity::Normal
730    });
731
732    #[cfg(debug_assertions)]
733    test_trigger::fire(env)?;
734
735    let (goal, opts) = match command {
736        Some(Command::Build(opts)) => (build::Goal::Build, opts),
737        Some(Command::Check {
738            tests,
739            all_targets,
740            opts,
741        }) => (
742            // `--all-targets` wins over `--tests` (commands.md, "`cuno
743            // build` / `cuno check`").
744            build::Goal::Check {
745                programs: !tests || all_targets,
746                tests: tests || all_targets,
747            },
748            opts,
749        ),
750        Some(Command::Run { bin, opts, args }) => (build::Goal::Run { bin, args }, opts),
751        Some(Command::Test {
752            filter,
753            nocapture,
754            opts,
755        }) => (build::Goal::Test { filter, nocapture }, opts),
756        Some(Command::Clean {
757            release,
758            profile,
759            target_dir,
760        }) => {
761            let cwd = given.cwd()?;
762            let cli = CliSettings {
763                target_dir,
764                ..CliSettings::default()
765            };
766            let resolved = resolve_settings(
767                Inputs {
768                    cwd: &cwd,
769                    env,
770                    cores: given.cores,
771                    cli: &cli,
772                },
773                shell,
774            );
775            clean::clean(
776                clean::CleanArgs { release, profile },
777                resolved,
778                &cwd,
779                given.host,
780                shell,
781            )?;
782            return Ok(0);
783        }
784        Some(Command::New {
785            path,
786            lang,
787            edition,
788            name,
789            vcs,
790            lib,
791        }) => {
792            let cwd = given.cwd()?;
793            resolve_user_settings(env, &cwd, shell).map_err(build::boxed)?;
794            // clap admits only these values.
795            let args = new::NewArgs {
796                path,
797                lang: lang
798                    .map(|l| cuno_toolchain::flags::Lang::parse(&l).expect("a lang clap admits")),
799                edition: edition.map(|e| {
800                    cuno_toolchain::flags::Edition::parse(&e).expect("an edition clap admits")
801                }),
802                name,
803                vcs: if vcs == "none" {
804                    new::Vcs::None
805                } else {
806                    new::Vcs::Git
807                },
808                lib,
809            };
810            new::new(args, &cwd, shell).map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
811            return Ok(0);
812        }
813        Some(Command::Init {
814            path,
815            lang,
816            edition,
817            name,
818            vcs,
819            lib,
820        }) => {
821            let cwd = given.cwd()?;
822            resolve_user_settings(env, &cwd, shell).map_err(build::boxed)?;
823            // clap admits only these values.
824            let args = new::InitArgs {
825                path: path.unwrap_or_else(|| PathBuf::from(".")),
826                lang: lang
827                    .map(|l| cuno_toolchain::flags::Lang::parse(&l).expect("a lang clap admits")),
828                edition: edition.map(|e| {
829                    cuno_toolchain::flags::Edition::parse(&e).expect("an edition clap admits")
830                }),
831                name,
832                vcs: if vcs == "none" {
833                    new::Vcs::None
834                } else {
835                    new::Vcs::Git
836                },
837                lib,
838            };
839            new::init(args, &cwd, given.host, shell)?;
840            return Ok(0);
841        }
842        Some(Command::Fmt { check }) => {
843            let cwd = given.cwd()?;
844            let resolved = resolve_settings(
845                Inputs {
846                    cwd: &cwd,
847                    env,
848                    cores: given.cores,
849                    cli: &CliSettings::default(),
850                },
851                shell,
852            );
853            return fmt::fmt(check, resolved, env, &cwd, given.host, given.temp, shell);
854        }
855        // --target-dir and -j reach lint through the settings, layered as the
856        // build commands' are; --target is refused as theirs is, after the
857        // settings are resolved and before anything is written
858        // (docs/en/specs/dev-tools.md, "Target files").
859        Some(Command::Lint {
860            fix,
861            compiler,
862            target,
863            target_dir,
864            jobs,
865            fetch,
866        }) => {
867            let cwd = given.cwd()?;
868            let cli = CliSettings {
869                compiler,
870                target_dir,
871                jobs,
872            };
873            let resolved = resolve_settings(
874                Inputs {
875                    cwd: &cwd,
876                    env,
877                    cores: given.cores,
878                    cli: &cli,
879                },
880                shell,
881            );
882            build::refuse_target(target.as_deref())?;
883            let resolved = resolved
884                .and_then(|s| with_dependencies(s, fetch.into(), env, given.host, &cwd, shell));
885            return lint::lint(fix, resolved, env, &cwd, given.host, given.temp, shell);
886        }
887        Some(Command::Doctor { compiler }) => {
888            let cwd = given.cwd()?;
889            let cli = CliSettings {
890                compiler: compiler.clone(),
891                ..CliSettings::default()
892            };
893            let resolved = resolve_settings(
894                Inputs {
895                    cwd: &cwd,
896                    env,
897                    cores: given.cores,
898                    cli: &cli,
899                },
900                shell,
901            );
902            // The doctor fetches nothing and writes no Cuno.lock
903            // (docs/en/specs/dependencies.md, "When sources are fetched and
904            // what is used").
905            let doctor_fetching = Fetching {
906                network: cuno_deps::Network::Offline,
907                lock: cuno_deps::LockMode::ReadOnly,
908            };
909            let resolved = resolved
910                .and_then(|s| with_dependencies(s, doctor_fetching, env, given.host, &cwd, shell));
911            let problems =
912                doctor::doctor(compiler, resolved, env, &cwd, given.host, given.temp, shell);
913            return Ok(if problems == 0 { 0 } else { 1 });
914        }
915        Some(
916            command @ (Command::Add { .. }
917            | Command::Remove { .. }
918            | Command::Update { .. }
919            | Command::Tree { .. }
920            | Command::Fetch { .. }),
921        ) => {
922            let cwd = given.cwd()?;
923            let resolved = resolve_settings(
924                Inputs {
925                    cwd: &cwd,
926                    env,
927                    cores: given.cores,
928                    cli: &CliSettings::default(),
929                },
930                shell,
931            );
932            let host = given.host;
933            return match command {
934                Command::Add {
935                    name,
936                    git,
937                    tag,
938                    rev,
939                    branch,
940                    url,
941                    path,
942                    version,
943                    offline,
944                } => {
945                    let reference = match (tag, rev, branch) {
946                        (Some(tag), _, _) => cuno_manifest::GitReference::Tag(tag),
947                        (_, Some(rev), _) => cuno_manifest::GitReference::Rev(rev),
948                        (_, _, Some(branch)) => cuno_manifest::GitReference::Branch(branch),
949                        (None, None, None) => cuno_manifest::GitReference::DefaultBranch,
950                    };
951                    let added = deps::NewDependency {
952                        git,
953                        reference,
954                        url,
955                        path,
956                        version,
957                    };
958                    deps::add(name, added, offline, resolved, env, host, &cwd, shell)
959                }
960                Command::Remove { names, offline } => {
961                    deps::remove(&names, offline, resolved, env, host, &cwd, shell)
962                }
963                Command::Update { name } => deps::update(name, resolved, env, host, &cwd, shell),
964                Command::Tree { fetch } => deps::tree(
965                    fetch.into(),
966                    resolved,
967                    env,
968                    host,
969                    &cwd,
970                    stdout.as_mut(),
971                    shell,
972                ),
973                Command::Fetch { fetch } => {
974                    deps::fetch(fetch.into(), resolved, env, host, &cwd, shell)
975                }
976                _ => unreachable!("only the dependency commands come here"),
977            };
978        }
979        Some(Command::Toolchain { command }) => {
980            let cwd = given.cwd()?;
981            let settings = resolve_settings(
982                Inputs {
983                    cwd: &cwd,
984                    env,
985                    cores: given.cores,
986                    cli: &CliSettings::default(),
987                },
988                shell,
989            )
990            .map_err(build::boxed)?;
991            return match command {
992                ToolchainCommand::List => {
993                    toolchain::list(&settings, env, given.host, stdout.as_mut(), shell)
994                }
995                ToolchainCommand::Default { compiler } => {
996                    toolchain::default(&compiler, &settings, env, given.host, shell)
997                }
998            };
999        }
1000        Some(Command::SelfCmd { command }) => {
1001            // Every layer, as for any command but `cuno new`
1002            // (docs/en/specs/commands.md, "Available for all commands"):
1003            // a broken configuration file stops it like any other.
1004            let cwd = given.cwd()?;
1005            resolve_settings(
1006                Inputs {
1007                    cwd: &cwd,
1008                    env,
1009                    cores: given.cores,
1010                    cli: &CliSettings::default(),
1011                },
1012                shell,
1013            )
1014            .map_err(build::boxed)?;
1015            return match command {
1016                SelfCommand::Update => self_cmd::update(given.exe, env, given.temp, shell),
1017                SelfCommand::Uninstall { yes } => {
1018                    self_cmd::uninstall(given.exe, env, yes, input, shell)
1019                }
1020            };
1021        }
1022        None => {
1023            // No command was given. Like Cargo, print the usage to stdout and
1024            // succeed; see docs/en/specs/commands.md, "Without a command
1025            // (`--version` / `--help` / no arguments)". A failed write (a
1026            // closed stdout) is ignored, matching what clap does for `--help`
1027            // and what Cargo does in both cases: the exit code stays 0.
1028            let usage = Cli::command().render_help();
1029            let _ = write_styled(stdout.as_mut(), &usage, help_color);
1030            return Ok(0);
1031        }
1032    };
1033    let cwd = given.cwd()?;
1034    let cli = CliSettings {
1035        compiler: opts.compiler.clone(),
1036        target_dir: opts.target_dir.clone(),
1037        jobs: opts.jobs,
1038    };
1039    let resolved = resolve_settings(
1040        Inputs {
1041            cwd: &cwd,
1042            env,
1043            cores: given.cores,
1044            cli: &cli,
1045        },
1046        shell,
1047    );
1048    build::build(
1049        goal,
1050        opts.into(),
1051        resolved,
1052        env,
1053        &cwd,
1054        given.host,
1055        given.temp,
1056        shell,
1057    )
1058}
1059
1060/// Standard input, for the one command that asks.
1061pub(crate) struct Input<'a> {
1062    pub(crate) stdin: &'a mut dyn BufRead,
1063    pub(crate) is_terminal: bool,
1064}
1065
1066/// The current directory cannot be read (deleted, or no permission).
1067#[derive(Debug)]
1068struct CwdError(String);
1069
1070impl std::fmt::Display for CwdError {
1071    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1072        write!(f, "cannot read the current directory: {}", self.0)
1073    }
1074}
1075
1076impl std::error::Error for CwdError {}
1077
1078impl CunoError for CwdError {
1079    fn exit_class(&self) -> cuno_core::ExitClass {
1080        cuno_core::ExitClass::Setup
1081    }
1082}
1083
1084/// The one place an error is shown and turned into an exit code
1085/// (docs/en/specs/architecture.md, "What goes in `cuno-core`").
1086fn report(shell: &mut Shell, error: &dyn CunoError) -> i32 {
1087    shell.error(error);
1088    if let Some(help) = error.help() {
1089        shell.help(help);
1090    }
1091    error.exit_class().code()
1092}
1093
1094/// A way for tests/cli.rs to make the binary fail before any command can, so
1095/// that the error path, colors and exit codes are tested through the real
1096/// process. Compiled into debug builds only (which is what `cargo test`
1097/// runs); release builds have no trace of it.
1098#[cfg(debug_assertions)]
1099mod test_trigger {
1100    use cuno_core::{CunoError, Env, ExitClass};
1101
1102    /// `CUNO_TEST_TRIGGER=setup-error` fails with an exit-class-3 error that
1103    /// has a help line; `CUNO_TEST_TRIGGER=panic` panics.
1104    pub fn fire(env: &Env) -> Result<(), Box<dyn CunoError>> {
1105        match env.get("CUNO_TEST_TRIGGER").and_then(|v| v.to_str()) {
1106            Some("setup-error") => Err(Box::new(Triggered)),
1107            Some("panic") => panic!("triggered by CUNO_TEST_TRIGGER"),
1108            _ => Ok(()),
1109        }
1110    }
1111
1112    #[derive(Debug)]
1113    struct Triggered;
1114    impl std::fmt::Display for Triggered {
1115        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1116            f.write_str("triggered by CUNO_TEST_TRIGGER")
1117        }
1118    }
1119    impl std::error::Error for Triggered {}
1120    impl CunoError for Triggered {
1121        fn exit_class(&self) -> ExitClass {
1122            ExitClass::Setup
1123        }
1124        fn help(&self) -> Option<String> {
1125            Some("unset CUNO_TEST_TRIGGER".into())
1126        }
1127    }
1128}
1129
1130#[cfg(test)]
1131mod tests {
1132    use super::*;
1133    use cuno_core::NameCase;
1134    use std::cell::RefCell;
1135    use std::rc::Rc;
1136
1137    /// `--profile`'s help, which clap takes from a doc comment and cannot
1138    /// ask `Profile` for, names every profile `Profile` has, for every
1139    /// command that takes it.
1140    ///
1141    /// Mutation: add a profile to `Profile` without naming it in the help,
1142    /// or drop `release` from one command's help; this test fails.
1143    #[test]
1144    fn the_profile_help_names_every_profile() {
1145        let mut cli = Cli::command();
1146        for command in ["build", "check", "run", "test", "clean"] {
1147            let sub = cli.find_subcommand_mut(command).expect(command);
1148            let help = sub
1149                .get_arguments()
1150                .find(|a| a.get_id() == "profile")
1151                .and_then(|a| a.get_help())
1152                .map(|h| h.to_string())
1153                .expect(command);
1154            for (_, name) in cuno_manifest::Profile::ALL {
1155                assert!(help.contains(name), "{command}: {help}");
1156            }
1157        }
1158    }
1159
1160    /// A stream the test reads back after `run` has written to it. With
1161    /// `buffered`, what is written reaches it only when flushed, as through
1162    /// a buffered writer.
1163    #[derive(Clone, Default)]
1164    struct Captured {
1165        text: Rc<RefCell<Vec<u8>>>,
1166        pending: Rc<RefCell<Vec<u8>>>,
1167        buffered: bool,
1168    }
1169
1170    impl Write for Captured {
1171        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1172            let to = if self.buffered {
1173                &self.pending
1174            } else {
1175                &self.text
1176            };
1177            to.borrow_mut().extend_from_slice(buf);
1178            Ok(buf.len())
1179        }
1180        fn flush(&mut self) -> std::io::Result<()> {
1181            let pending = std::mem::take(&mut *self.pending.borrow_mut());
1182            self.text.borrow_mut().extend(pending);
1183            Ok(())
1184        }
1185    }
1186
1187    impl Captured {
1188        fn text(&self) -> String {
1189            String::from_utf8(self.text.borrow().clone()).unwrap()
1190        }
1191    }
1192
1193    /// How a run is set up: whether each stream is a terminal, the current
1194    /// directory, and whether stdout buffers.
1195    struct Setup {
1196        stdout_is_terminal: bool,
1197        stderr_is_terminal: bool,
1198        cwd: Result<PathBuf, String>,
1199        buffered: bool,
1200    }
1201
1202    /// `cuno <args>` run with `setup`, in a directory holding no project and
1203    /// a cuno home of its own: the exit code, stdout and stderr.
1204    fn run_with(args: &[&str], setup: Setup) -> (i32, String, String) {
1205        let dir = tempfile::tempdir().unwrap();
1206        let env = Env::from_pairs(
1207            [("CUNO_HOME".into(), dir.path().join("home").into_os_string())],
1208            NameCase::Insensitive,
1209        );
1210        let stdout = Captured {
1211            buffered: setup.buffered,
1212            ..Captured::default()
1213        };
1214        let stderr = Captured::default();
1215        let code = run(Process {
1216            args: std::iter::once("cuno")
1217                .chain(args.iter().copied())
1218                .map(OsString::from)
1219                .collect(),
1220            env,
1221            cwd: setup.cwd.map(|_| dir.path().to_owned()),
1222            host: HostOs::Windows,
1223            temp: dir.path().to_owned(),
1224            exe: Err("not needed".to_owned()),
1225            cores: NonZeroU32::new(2).unwrap(),
1226            stdout: Box::new(stdout.clone()),
1227            stdout_is_terminal: setup.stdout_is_terminal,
1228            stderr: Box::new(stderr.clone()),
1229            stderr_is_terminal: setup.stderr_is_terminal,
1230            stdin: Box::new(std::io::empty()),
1231            stdin_is_terminal: false,
1232        });
1233        (code, stdout.text(), stderr.text())
1234    }
1235
1236    fn terminals(stdout_is_terminal: bool, stderr_is_terminal: bool) -> Setup {
1237        Setup {
1238            stdout_is_terminal,
1239            stderr_is_terminal,
1240            cwd: Ok(PathBuf::new()),
1241            buffered: false,
1242        }
1243    }
1244
1245    const ESC: char = '\u{1b}';
1246
1247    /// Each stream is colored by whether it is the terminal, not the other:
1248    /// help and the usage on stdout, a usage error and cuno's own `error:`
1249    /// on stderr (`docs/en/specs/commands.md`, "Available for all
1250    /// commands").
1251    ///
1252    /// Mutation: decide a stream's color from the other stream's terminal,
1253    /// give the shell stdout's, write clap's message in the other stream's
1254    /// color, or color the usage with stderr's; this test fails.
1255    #[test]
1256    fn each_stream_is_colored_by_its_own_terminal() {
1257        for (stdout_tty, stderr_tty) in [(true, false), (false, true)] {
1258            let at = format!("stdout terminal {stdout_tty}, stderr terminal {stderr_tty}");
1259            let (code, out, _) = run_with(&["--help"], terminals(stdout_tty, stderr_tty));
1260            assert_eq!((code, out.contains(ESC)), (0, stdout_tty), "{at}: {out}");
1261            let (code, out, _) = run_with(&[], terminals(stdout_tty, stderr_tty));
1262            assert_eq!((code, out.contains(ESC)), (0, stdout_tty), "{at}: {out}");
1263            let (code, out, err) = run_with(&["bogus"], terminals(stdout_tty, stderr_tty));
1264            assert_eq!((code, out.as_str()), (2, ""), "{at}");
1265            assert_eq!(err.contains(ESC), stderr_tty, "{at}: {err}");
1266            let (code, _, err) = run_with(&["clean"], terminals(stdout_tty, stderr_tty));
1267            assert_eq!(code, 3, "{at}: {err}");
1268            assert_eq!(err.contains(ESC), stderr_tty, "{at}: {err}");
1269        }
1270    }
1271
1272    /// A current directory that cannot be read is reported, exit code 3, by
1273    /// every command that needs one, and help still works without one.
1274    ///
1275    /// Mutation: run a command somewhere else instead, change the message
1276    /// or its exit class, or read the directory before `--help`; this test
1277    /// fails.
1278    #[test]
1279    fn an_unreadable_current_directory_is_reported_by_each_command() {
1280        let unreadable = || Setup {
1281            cwd: Err("gone".to_owned()),
1282            ..terminals(false, false)
1283        };
1284        for args in [
1285            &["build"][..],
1286            &["check"],
1287            &["run"],
1288            &["test"],
1289            &["clean"],
1290            &["doctor"],
1291            &["new", "app"],
1292        ] {
1293            let (code, _, err) = run_with(args, unreadable());
1294            assert_eq!(code, 3, "{args:?}: {err}");
1295            assert_eq!(
1296                err, "error: cannot read the current directory: gone\n",
1297                "{args:?}"
1298            );
1299        }
1300        let (code, out, _) = run_with(&["--help"], unreadable());
1301        assert_eq!(code, 0);
1302        assert!(out.starts_with("Everything C/C++"), "{out}");
1303    }
1304
1305    /// What clap makes is flushed, so it is not lost in a buffered stream
1306    /// when the process ends.
1307    ///
1308    /// Mutation: leave out the flush in `write_styled`; this test fails.
1309    #[test]
1310    fn help_is_flushed() {
1311        let (code, out, _) = run_with(
1312            &["--help"],
1313            Setup {
1314                buffered: true,
1315                ..terminals(false, false)
1316            },
1317        );
1318        assert_eq!(code, 0);
1319        assert!(out.starts_with("Everything C/C++"), "{out:?}");
1320    }
1321
1322    /// Mutation: swap any two arms of `From<Color> for ColorChoice`; this
1323    /// test fails.
1324    #[test]
1325    fn color_values_map_to_the_same_choice() {
1326        assert_eq!(ColorChoice::from(Color::Auto), ColorChoice::Auto);
1327        assert_eq!(ColorChoice::from(Color::Always), ColorChoice::Always);
1328        assert_eq!(ColorChoice::from(Color::Never), ColorChoice::Never);
1329    }
1330
1331    fn given(args: &[&str]) -> Option<ColorChoice> {
1332        let args: Vec<OsString> = std::iter::once("cuno")
1333            .chain(args.iter().copied())
1334            .map(OsString::from)
1335            .collect();
1336        color_before_parsing(&args)
1337    }
1338
1339    /// Mutation: read only one of the two spellings, take the first
1340    /// `--color` instead of the last, read past `--`, or keep an earlier
1341    /// value past an invalid one, a missing one or one that is not Unicode;
1342    /// this test fails.
1343    #[test]
1344    fn the_color_is_read_before_parsing() {
1345        assert_eq!(
1346            given(&["--color", "never", "build"]),
1347            Some(ColorChoice::Never)
1348        );
1349        assert_eq!(
1350            given(&["build", "--color=always"]),
1351            Some(ColorChoice::Always)
1352        );
1353        assert_eq!(
1354            given(&["--color", "never", "build", "--color", "always"]),
1355            Some(ColorChoice::Always)
1356        );
1357        assert_eq!(given(&["run", "--", "--color", "never"]), None);
1358        assert_eq!(given(&["--color", "bogus"]), None);
1359        assert_eq!(given(&["--color=never", "--color=bogus"]), None);
1360        assert_eq!(given(&["build"]), None);
1361        assert_eq!(given(&["--color=always", "--color"]), None);
1362        #[cfg(windows)]
1363        {
1364            use std::os::windows::ffi::OsStringExt;
1365            let lone = OsString::from_wide(&[0xD800]);
1366            let mut equals = OsString::from("--color=");
1367            equals.push(&lone);
1368            for bad in [vec![OsString::from("--color"), lone], vec![equals]] {
1369                let args: Vec<OsString> = ["cuno", "--color", "always"]
1370                    .into_iter()
1371                    .map(OsString::from)
1372                    .chain(bad)
1373                    .collect();
1374                assert_eq!(color_before_parsing(&args), None, "{args:?}");
1375            }
1376        }
1377    }
1378
1379    /// Mutation: hand clap its own `Auto`, let NO_COLOR beat a choice given,
1380    /// or ignore it with none; this test fails.
1381    #[test]
1382    fn what_clap_prints_follows_cunos_order() {
1383        use clap::ColorChoice as Clap;
1384        assert_eq!(
1385            parser_color(Some(ColorChoice::Always), true, false),
1386            Clap::Always
1387        );
1388        assert_eq!(
1389            parser_color(Some(ColorChoice::Never), false, true),
1390            Clap::Never
1391        );
1392        assert_eq!(
1393            parser_color(Some(ColorChoice::Auto), true, true),
1394            Clap::Always
1395        );
1396        assert_eq!(
1397            parser_color(Some(ColorChoice::Auto), false, false),
1398            Clap::Never
1399        );
1400        assert_eq!(parser_color(None, true, true), Clap::Never);
1401        assert_eq!(parser_color(None, false, true), Clap::Always);
1402        assert_eq!(parser_color(None, false, false), Clap::Never);
1403    }
1404
1405    /// `cuno self uninstall` through the whole command line: without `-y`
1406    /// and with no terminal it refuses, with `-y` (or `--yes`) it removes.
1407    /// The cuno it runs as is placed outside its home, so no `PATH` is
1408    /// edited and nothing is left running.
1409    ///
1410    /// Mutation: pass `!yes`, drop `-y`'s short name, or pass the terminal
1411    /// flag as true; this test fails.
1412    #[test]
1413    fn self_uninstall_takes_yes_and_the_terminal_from_the_command_line() {
1414        for (args, code, gone) in [
1415            (vec!["self", "uninstall"], 2, false),
1416            (vec!["self", "uninstall", "-y"], 0, true),
1417            (vec!["self", "uninstall", "--yes"], 0, true),
1418        ] {
1419            let dir = tempfile::tempdir().unwrap();
1420            let home = dir.path().join("home");
1421            std::fs::create_dir_all(&home).unwrap();
1422            std::fs::write(home.join("config.toml"), "").unwrap();
1423            let env = Env::from_pairs(
1424                [
1425                    ("CUNO_HOME".into(), home.clone().into_os_string()),
1426                    (
1427                        "USERPROFILE".into(),
1428                        dir.path().join("user").into_os_string(),
1429                    ),
1430                ],
1431                NameCase::Insensitive,
1432            );
1433            let stderr = Captured::default();
1434            let got = run(Process {
1435                args: std::iter::once("cuno")
1436                    .chain(args.iter().copied())
1437                    .map(OsString::from)
1438                    .collect(),
1439                env,
1440                cwd: Ok(dir.path().to_owned()),
1441                host: HostOs::Windows,
1442                temp: dir.path().to_owned(),
1443                exe: Ok(dir.path().join("tools").join("cuno.exe")),
1444                cores: NonZeroU32::new(2).unwrap(),
1445                stdout: Box::new(Captured::default()),
1446                stdout_is_terminal: false,
1447                stderr: Box::new(stderr.clone()),
1448                stderr_is_terminal: false,
1449                stdin: Box::new(std::io::empty()),
1450                stdin_is_terminal: false,
1451            });
1452            assert_eq!(got, code, "{args:?}: {}", stderr.text());
1453            assert_eq!(!home.exists(), gone, "{args:?}");
1454        }
1455    }
1456}