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