1mod 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
28pub use cuno_toolchain::HostOs;
32
33pub struct Process {
37 pub args: Vec<OsString>,
39 pub env: Env,
41 pub cwd: Result<PathBuf, String>,
44 pub host: HostOs,
46 pub temp: PathBuf,
48 pub exe: Result<PathBuf, String>,
51 pub cores: NonZeroU32,
53 pub stdout: Box<dyn Write>,
56 pub stdout_is_terminal: bool,
58 pub stderr: Box<dyn Write>,
60 pub stderr_is_terminal: bool,
62 pub stdin: Box<dyn BufRead>,
64 pub stdin_is_terminal: bool,
66}
67
68#[derive(Parser)]
71#[command(
72 name = "cuno",
76 bin_name = "cuno",
77 version,
78 about
80)]
81struct Cli {
82 #[arg(long, value_name = "WHEN", value_enum, global = true)]
88 color: Option<Color>,
89
90 #[arg(short, long, global = true, conflicts_with = "quiet")]
92 verbose: bool,
93
94 #[arg(short, long, global = true)]
96 quiet: bool,
97
98 #[command(subcommand)]
99 command: Option<Command>,
100}
101
102#[derive(Subcommand)]
104enum Command {
105 New {
107 #[arg(value_name = "PATH")]
109 path: PathBuf,
110 #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
112 lang: Option<String>,
113 #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
115 edition: Option<String>,
116 #[arg(long, value_name = "NAME")]
118 name: Option<String>,
119 #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
121 vcs: String,
122 },
123 Init {
125 #[arg(value_name = "PATH")]
127 path: Option<PathBuf>,
128 #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
130 lang: Option<String>,
131 #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
133 edition: Option<String>,
134 #[arg(long, value_name = "NAME")]
136 name: Option<String>,
137 #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
139 vcs: String,
140 },
141 Build(BuildOpts),
143 Check {
145 #[arg(long)]
147 tests: bool,
148 #[arg(long)]
150 all_targets: bool,
151 #[command(flatten)]
152 opts: BuildOpts,
153 },
154 Run {
156 #[arg(long, value_name = "NAME")]
158 bin: Option<String>,
159 #[command(flatten)]
160 opts: BuildOpts,
161 #[arg(last = true, value_name = "ARGS")]
163 args: Vec<OsString>,
164 },
165 Test {
167 #[arg(value_name = "FILTER")]
169 filter: Option<String>,
170 #[arg(long)]
172 nocapture: bool,
173 #[command(flatten)]
174 opts: BuildOpts,
175 },
176 Fmt {
178 #[arg(long)]
180 check: bool,
181 },
182 Lint {
188 #[arg(long)]
190 fix: bool,
191 #[arg(long, value_name = "NAME")]
193 compiler: Option<String>,
194 #[arg(long, value_name = "TRIPLE")]
196 target: Option<String>,
197 #[arg(long, value_name = "PATH")]
199 target_dir: Option<PathBuf>,
200 #[arg(short, long, value_name = "N")]
202 jobs: Option<NonZeroU32>,
203 },
204 Clean {
206 #[arg(long, conflicts_with = "profile")]
208 release: bool,
209 #[arg(long, value_name = "NAME")]
211 profile: Option<String>,
212 #[arg(long, value_name = "PATH")]
214 target_dir: Option<PathBuf>,
215 },
216 Doctor {
218 #[arg(long, value_name = "NAME")]
220 compiler: Option<String>,
221 },
222 Toolchain {
224 #[command(subcommand)]
225 command: ToolchainCommand,
226 },
227 #[command(name = "self")]
229 SelfCmd {
230 #[command(subcommand)]
231 command: SelfCommand,
232 },
233}
234
235#[derive(Subcommand)]
237enum SelfCommand {
238 Update,
240 Uninstall {
242 #[arg(short = 'y', long)]
244 yes: bool,
245 },
246}
247
248#[derive(Subcommand)]
250enum ToolchainCommand {
251 List,
253 Default {
255 #[arg(value_name = "COMPILER")]
257 compiler: String,
258 },
259}
260
261#[derive(Args)]
264struct BuildOpts {
265 #[arg(long, conflicts_with = "profile")]
267 release: bool,
268 #[arg(long, value_name = "NAME")]
270 profile: Option<String>,
271 #[arg(long, value_name = "NAME")]
273 compiler: Option<String>,
274 #[arg(long, value_name = "TRIPLE")]
276 target: Option<String>,
277 #[arg(long, value_name = "PATH")]
279 target_dir: Option<PathBuf>,
280 #[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
295fn 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 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
327fn 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#[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
358pub 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 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 let cli = match Cli::command().try_get_matches_from(&args) {
389 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
426fn 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 let _ = write_styled(out.as_mut(), &error.render(), color);
444 error.exit_code()
445}
446
447fn 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#[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 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
483fn 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
497fn 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
509fn 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 let Cli {
525 color: _,
526 verbose,
527 quiet,
528 command,
529 } = cli;
530
531 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 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 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 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 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 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 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
790pub(crate) struct Input<'a> {
792 pub(crate) stdin: &'a mut dyn BufRead,
793 pub(crate) is_terminal: bool,
794}
795
796#[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
814fn 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#[cfg(debug_assertions)]
829mod test_trigger {
830 use cuno_core::{CunoError, Env, ExitClass};
831
832 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 #[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 #[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 struct Setup {
926 stdout_is_terminal: bool,
927 stderr_is_terminal: bool,
928 cwd: Result<PathBuf, String>,
929 buffered: bool,
930 }
931
932 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}