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