1mod build;
11mod clean;
12mod deps;
13mod doctor;
14mod fmt;
15mod lint;
16mod new;
17mod self_cmd;
18mod toolchain;
19
20use std::ffi::OsString;
21use std::io::{BufRead, Write};
22use std::num::NonZeroU32;
23use std::path::{Path, PathBuf};
24
25use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
26use cuno_core::{ColorChoice, CunoError, Env, ExitClass, Shell, Verbosity};
27use cuno_manifest::{CliSettings, ConfigError, Inputs, Settings};
28
29pub use cuno_toolchain::HostOs;
33
34pub struct Process {
38 pub args: Vec<OsString>,
40 pub env: Env,
42 pub cwd: Result<PathBuf, String>,
45 pub host: HostOs,
47 pub temp: PathBuf,
49 pub exe: Result<PathBuf, String>,
52 pub cores: NonZeroU32,
54 pub stdout: Box<dyn Write>,
57 pub stdout_is_terminal: bool,
59 pub stderr: Box<dyn Write>,
61 pub stderr_is_terminal: bool,
63 pub stdin: Box<dyn BufRead>,
65 pub stdin_is_terminal: bool,
67}
68
69#[derive(Parser)]
72#[command(
73 name = "cuno",
77 bin_name = "cuno",
78 version,
79 about
81)]
82struct Cli {
83 #[arg(long, value_name = "WHEN", value_enum, global = true)]
89 color: Option<Color>,
90
91 #[arg(short, long, global = true, conflicts_with = "quiet")]
93 verbose: bool,
94
95 #[arg(short, long, global = true)]
97 quiet: bool,
98
99 #[command(subcommand)]
100 command: Option<Command>,
101}
102
103#[derive(Subcommand)]
105enum Command {
106 New {
108 #[arg(value_name = "PATH")]
110 path: PathBuf,
111 #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
113 lang: Option<String>,
114 #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
116 edition: Option<String>,
117 #[arg(long, value_name = "NAME")]
119 name: Option<String>,
120 #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
122 vcs: String,
123 #[arg(long)]
125 lib: bool,
126 },
127 Init {
129 #[arg(value_name = "PATH")]
131 path: Option<PathBuf>,
132 #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
134 lang: Option<String>,
135 #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
137 edition: Option<String>,
138 #[arg(long, value_name = "NAME")]
140 name: Option<String>,
141 #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
143 vcs: String,
144 #[arg(long)]
146 lib: bool,
147 },
148 Build(BuildOpts),
150 Check {
152 #[arg(long)]
154 tests: bool,
155 #[arg(long)]
157 all_targets: bool,
158 #[command(flatten)]
159 opts: BuildOpts,
160 },
161 Run {
163 #[arg(long, value_name = "NAME")]
165 bin: Option<String>,
166 #[command(flatten)]
167 opts: BuildOpts,
168 #[arg(last = true, value_name = "ARGS")]
170 args: Vec<OsString>,
171 },
172 Test {
174 #[arg(value_name = "FILTER")]
176 filter: Option<String>,
177 #[arg(long)]
179 nocapture: bool,
180 #[command(flatten)]
181 opts: BuildOpts,
182 },
183 Fmt {
185 #[arg(long)]
187 check: bool,
188 },
189 Lint {
195 #[arg(long)]
197 fix: bool,
198 #[arg(long, value_name = "NAME")]
200 compiler: Option<String>,
201 #[arg(long, value_name = "TRIPLE")]
203 target: Option<String>,
204 #[arg(long, value_name = "PATH")]
206 target_dir: Option<PathBuf>,
207 #[arg(short, long, value_name = "N")]
209 jobs: Option<NonZeroU32>,
210 #[command(flatten)]
211 fetch: FetchOpts,
212 },
213 Clean {
215 #[arg(long, conflicts_with = "profile")]
217 release: bool,
218 #[arg(long, value_name = "NAME")]
220 profile: Option<String>,
221 #[arg(long, value_name = "PATH")]
223 target_dir: Option<PathBuf>,
224 },
225 Doctor {
227 #[arg(long, value_name = "NAME")]
229 compiler: Option<String>,
230 },
231 #[command(group(clap::ArgGroup::new("source").args(["git", "url", "path"]).multiple(false)))]
233 #[command(group(clap::ArgGroup::new("reference").args(["tag", "rev", "branch"]).multiple(false).requires("git")))]
234 Add {
235 #[arg(value_name = "NAME", conflicts_with = "source")]
237 name: Option<String>,
238 #[arg(long, value_name = "URL")]
240 git: Option<String>,
241 #[arg(long, value_name = "TAG")]
243 tag: Option<String>,
244 #[arg(long, value_name = "COMMIT")]
246 rev: Option<String>,
247 #[arg(long, value_name = "BRANCH")]
249 branch: Option<String>,
250 #[arg(long, value_name = "URL")]
252 url: Option<String>,
253 #[arg(long, value_name = "PATH")]
255 path: Option<PathBuf>,
256 #[arg(long, value_name = "CONDITION")]
258 version: Option<String>,
259 #[arg(long)]
261 offline: bool,
262 },
263 Remove {
265 #[arg(value_name = "NAME", required = true)]
267 names: Vec<String>,
268 #[arg(long)]
270 offline: bool,
271 },
272 Update {
274 #[arg(value_name = "NAME")]
276 name: Option<String>,
277 },
278 Tree {
280 #[command(flatten)]
281 fetch: FetchOpts,
282 },
283 Fetch {
285 #[command(flatten)]
286 fetch: FetchOpts,
287 },
288 Toolchain {
290 #[command(subcommand)]
291 command: ToolchainCommand,
292 },
293 #[command(name = "self")]
295 SelfCmd {
296 #[command(subcommand)]
297 command: SelfCommand,
298 },
299}
300
301#[derive(Subcommand)]
303enum SelfCommand {
304 Update,
306 Uninstall {
308 #[arg(short = 'y', long)]
310 yes: bool,
311 },
312}
313
314#[derive(Subcommand)]
316enum ToolchainCommand {
317 List,
319 Default {
321 #[arg(value_name = "COMPILER")]
323 compiler: String,
324 },
325}
326
327#[derive(Args)]
330struct BuildOpts {
331 #[arg(long, conflicts_with = "profile")]
333 release: bool,
334 #[arg(long, value_name = "NAME")]
336 profile: Option<String>,
337 #[arg(long, value_name = "NAME")]
339 compiler: Option<String>,
340 #[arg(long, value_name = "TRIPLE")]
342 target: Option<String>,
343 #[arg(long, value_name = "PATH")]
345 target_dir: Option<PathBuf>,
346 #[arg(short, long, value_name = "N")]
348 jobs: Option<NonZeroU32>,
349 #[command(flatten)]
350 fetch: FetchOpts,
351}
352
353#[derive(Args, Clone, Copy)]
357struct FetchOpts {
358 #[arg(long)]
360 locked: bool,
361 #[arg(long)]
363 offline: bool,
364}
365
366impl From<FetchOpts> for Fetching {
367 fn from(o: FetchOpts) -> Fetching {
368 Fetching {
369 network: if o.offline {
370 cuno_deps::Network::Offline
371 } else {
372 cuno_deps::Network::Online
373 },
374 lock: if o.locked {
375 cuno_deps::LockMode::Locked
376 } else {
377 cuno_deps::LockMode::Write
378 },
379 }
380 }
381}
382
383impl From<BuildOpts> for build::BuildArgs {
384 fn from(o: BuildOpts) -> build::BuildArgs {
385 build::BuildArgs {
386 release: o.release,
387 profile: o.profile,
388 target: o.target,
389 fetching: o.fetch.into(),
390 }
391 }
392}
393
394fn color_before_parsing(args: &[OsString]) -> Option<ColorChoice> {
401 let mut found = None;
402 let mut args = args.iter().skip(1);
403 while let Some(arg) = args.next() {
404 let value = match arg.to_str() {
407 Some("--") => break,
408 Some("--color") => Some(args.next().and_then(|v| v.to_str())),
409 Some(arg) => arg.strip_prefix("--color=").map(Some),
410 None => arg
411 .as_encoded_bytes()
412 .starts_with(b"--color=")
413 .then_some(None),
414 };
415 if let Some(value) = value {
416 found = Some(
417 value
418 .and_then(|v| Color::from_str(v, false).ok())
419 .map(ColorChoice::from),
420 );
421 }
422 }
423 found.flatten()
424}
425
426fn parser_color(given: Option<ColorChoice>, no_color: bool, terminal: bool) -> clap::ColorChoice {
431 if cuno_core::colors(given, None, no_color, terminal) {
432 clap::ColorChoice::Always
433 } else {
434 clap::ColorChoice::Never
435 }
436}
437
438#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
441enum Color {
442 Auto,
443 Always,
444 Never,
445}
446
447impl From<Color> for ColorChoice {
448 fn from(color: Color) -> ColorChoice {
449 match color {
450 Color::Auto => ColorChoice::Auto,
451 Color::Always => ColorChoice::Always,
452 Color::Never => ColorChoice::Never,
453 }
454 }
455}
456
457pub fn run(process: Process) -> i32 {
460 let Process {
461 args,
462 env,
463 cwd,
464 host,
465 temp,
466 exe,
467 cores,
468 mut stdout,
469 stdout_is_terminal,
470 mut stderr,
471 stderr_is_terminal,
472 mut stdin,
473 stdin_is_terminal,
474 } = process;
475 let given = color_before_parsing(&args);
479 let no_color = env.get("NO_COLOR").is_some();
480 let stdout_color = parser_color(given, no_color, stdout_is_terminal);
481 let stderr_color = parser_color(given, no_color, stderr_is_terminal);
482 let cli = match Cli::command().try_get_matches_from(&args) {
488 Ok(matches) => match Cli::from_arg_matches(&matches) {
491 Ok(cli) => cli,
492 Err(e) => {
493 let e = e.format(&mut Cli::command());
494 return print_clap(&e, stdout_color, stderr_color, &mut stdout, &mut stderr);
495 }
496 },
497 Err(error) => {
498 return print_clap(&error, stdout_color, stderr_color, &mut stdout, &mut stderr);
499 }
500 };
501 let mut shell = Shell::new(
502 stderr,
503 cli.color.map(ColorChoice::from),
504 &env,
505 stderr_is_terminal,
506 );
507 let given = Values {
508 env: &env,
509 cwd: &cwd,
510 exe: &exe,
511 host,
512 temp: &temp,
513 cores,
514 };
515 let input = Input {
516 stdin: stdin.as_mut(),
517 is_terminal: stdin_is_terminal,
518 };
519 match dispatch(cli, given, &mut shell, stdout_color, &mut stdout, input) {
520 Ok(code) => code,
521 Err(error) => report(&mut shell, &*error),
522 }
523}
524
525fn print_clap(
529 error: &clap::Error,
530 stdout_color: clap::ColorChoice,
531 stderr_color: clap::ColorChoice,
532 stdout: &mut Box<dyn Write>,
533 stderr: &mut Box<dyn Write>,
534) -> i32 {
535 let (out, color) = if error.use_stderr() {
536 (stderr, stderr_color)
537 } else {
538 (stdout, stdout_color)
539 };
540 let _ = write_styled(out.as_mut(), &error.render(), color);
543 error.exit_code()
544}
545
546fn write_styled(
550 out: &mut dyn Write,
551 text: &clap::builder::StyledStr,
552 color: clap::ColorChoice,
553) -> std::io::Result<()> {
554 match color {
555 clap::ColorChoice::Always => write!(out, "{}", text.ansi())?,
556 _ => write!(out, "{text}")?,
557 }
558 out.flush()
559}
560
561#[derive(Clone, Copy)]
564struct Values<'a> {
565 env: &'a Env,
566 cwd: &'a Result<PathBuf, String>,
567 host: HostOs,
568 temp: &'a Path,
569 exe: &'a Result<PathBuf, String>,
570 cores: NonZeroU32,
571}
572
573impl Values<'_> {
574 fn cwd(&self) -> Result<PathBuf, Box<dyn CunoError>> {
576 self.cwd
577 .clone()
578 .map_err(|e| Box::new(CwdError(e)) as Box<dyn CunoError>)
579 }
580}
581
582fn resolve_settings(inputs: Inputs<'_>, shell: &mut Shell) -> Result<Settings, ConfigError> {
588 let loaded = cuno_manifest::resolve(inputs)?;
589 shell.configure(loaded.value.color, loaded.value.verbose);
590 for warning in &loaded.warnings {
591 shell.warning(warning);
592 }
593 Ok(loaded.value)
594}
595
596#[derive(Clone, Copy, Debug)]
599pub(crate) struct Fetching {
600 pub(crate) network: cuno_deps::Network,
601 pub(crate) lock: cuno_deps::LockMode,
602}
603
604impl Default for Fetching {
607 fn default() -> Fetching {
609 Fetching {
610 network: cuno_deps::Network::Online,
611 lock: cuno_deps::LockMode::Write,
612 }
613 }
614}
615
616pub(crate) fn argument_path(path: &Path, cwd: &Path) -> Result<PathBuf, DriveRelativePath> {
621 cuno_manifest::resolve_path(path, cwd).map_err(|_| DriveRelativePath(path.to_owned()))
622}
623
624#[derive(Debug)]
627pub(crate) struct DriveRelativePath(pub(crate) PathBuf);
628
629impl std::fmt::Display for DriveRelativePath {
630 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
631 write!(
632 f,
633 "the path is `{}`, which depends on the current drive",
634 self.0.display()
635 )
636 }
637}
638
639impl std::error::Error for DriveRelativePath {}
640
641impl CunoError for DriveRelativePath {
642 fn exit_class(&self) -> ExitClass {
643 ExitClass::Setup
644 }
645
646 fn help(&self) -> Option<String> {
647 Some("write an absolute path, or a path relative to the current directory".to_owned())
648 }
649}
650
651pub(crate) fn with_dependencies(
660 mut settings: Settings,
661 fetching: Fetching,
662 env: &cuno_core::Env,
663 host: cuno_toolchain::HostOs,
664 cwd: &Path,
665 shell: &mut Shell,
666) -> Result<Settings, ConfigError> {
667 if let Some(package) = settings.project.take() {
668 let resolved = deps::with_resolve_options(
669 &settings,
670 fetching,
671 cuno_deps::Forget::Nothing,
672 &[],
673 env,
674 host,
675 cwd,
676 |options| cuno_deps::resolve(package, options, shell),
677 )?;
678 for (verb, text) in &resolved.changes {
679 shell.status(verb, text);
680 }
681 for warning in &resolved.warnings {
682 shell.warning(warning);
683 }
684 settings.project = Some(resolved.root);
685 }
686 Ok(settings)
687}
688
689fn resolve_user_settings(env: &Env, cwd: &Path, shell: &mut Shell) -> Result<(), ConfigError> {
693 let loaded = cuno_manifest::resolve_user(env, cwd)?;
694 shell.configure(loaded.value.color, loaded.value.verbose);
695 for warning in &loaded.warnings {
696 shell.warning(warning);
697 }
698 Ok(())
699}
700
701fn dispatch(
706 cli: Cli,
707 given: Values<'_>,
708 shell: &mut Shell,
709 help_color: clap::ColorChoice,
710 stdout: &mut Box<dyn Write>,
711 input: Input<'_>,
712) -> Result<i32, Box<dyn CunoError>> {
713 let env = given.env;
714 let Cli {
717 color: _,
718 verbose,
719 quiet,
720 command,
721 } = cli;
722
723 shell.set_verbosity(if quiet {
725 Verbosity::Quiet
726 } else if verbose {
727 Verbosity::Verbose
728 } else {
729 Verbosity::Normal
730 });
731
732 #[cfg(debug_assertions)]
733 test_trigger::fire(env)?;
734
735 let (goal, opts) = match command {
736 Some(Command::Build(opts)) => (build::Goal::Build, opts),
737 Some(Command::Check {
738 tests,
739 all_targets,
740 opts,
741 }) => (
742 build::Goal::Check {
745 programs: !tests || all_targets,
746 tests: tests || all_targets,
747 },
748 opts,
749 ),
750 Some(Command::Run { bin, opts, args }) => (build::Goal::Run { bin, args }, opts),
751 Some(Command::Test {
752 filter,
753 nocapture,
754 opts,
755 }) => (build::Goal::Test { filter, nocapture }, opts),
756 Some(Command::Clean {
757 release,
758 profile,
759 target_dir,
760 }) => {
761 let cwd = given.cwd()?;
762 let cli = CliSettings {
763 target_dir,
764 ..CliSettings::default()
765 };
766 let resolved = resolve_settings(
767 Inputs {
768 cwd: &cwd,
769 env,
770 cores: given.cores,
771 cli: &cli,
772 },
773 shell,
774 );
775 clean::clean(
776 clean::CleanArgs { release, profile },
777 resolved,
778 &cwd,
779 given.host,
780 shell,
781 )?;
782 return Ok(0);
783 }
784 Some(Command::New {
785 path,
786 lang,
787 edition,
788 name,
789 vcs,
790 lib,
791 }) => {
792 let cwd = given.cwd()?;
793 resolve_user_settings(env, &cwd, shell).map_err(build::boxed)?;
794 let args = new::NewArgs {
796 path,
797 lang: lang
798 .map(|l| cuno_toolchain::flags::Lang::parse(&l).expect("a lang clap admits")),
799 edition: edition.map(|e| {
800 cuno_toolchain::flags::Edition::parse(&e).expect("an edition clap admits")
801 }),
802 name,
803 vcs: if vcs == "none" {
804 new::Vcs::None
805 } else {
806 new::Vcs::Git
807 },
808 lib,
809 };
810 new::new(args, &cwd, shell).map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
811 return Ok(0);
812 }
813 Some(Command::Init {
814 path,
815 lang,
816 edition,
817 name,
818 vcs,
819 lib,
820 }) => {
821 let cwd = given.cwd()?;
822 resolve_user_settings(env, &cwd, shell).map_err(build::boxed)?;
823 let args = new::InitArgs {
825 path: path.unwrap_or_else(|| PathBuf::from(".")),
826 lang: lang
827 .map(|l| cuno_toolchain::flags::Lang::parse(&l).expect("a lang clap admits")),
828 edition: edition.map(|e| {
829 cuno_toolchain::flags::Edition::parse(&e).expect("an edition clap admits")
830 }),
831 name,
832 vcs: if vcs == "none" {
833 new::Vcs::None
834 } else {
835 new::Vcs::Git
836 },
837 lib,
838 };
839 new::init(args, &cwd, given.host, shell)?;
840 return Ok(0);
841 }
842 Some(Command::Fmt { check }) => {
843 let cwd = given.cwd()?;
844 let resolved = resolve_settings(
845 Inputs {
846 cwd: &cwd,
847 env,
848 cores: given.cores,
849 cli: &CliSettings::default(),
850 },
851 shell,
852 );
853 return fmt::fmt(check, resolved, env, &cwd, given.host, given.temp, shell);
854 }
855 Some(Command::Lint {
860 fix,
861 compiler,
862 target,
863 target_dir,
864 jobs,
865 fetch,
866 }) => {
867 let cwd = given.cwd()?;
868 let cli = CliSettings {
869 compiler,
870 target_dir,
871 jobs,
872 };
873 let resolved = resolve_settings(
874 Inputs {
875 cwd: &cwd,
876 env,
877 cores: given.cores,
878 cli: &cli,
879 },
880 shell,
881 );
882 build::refuse_target(target.as_deref())?;
883 let resolved = resolved
884 .and_then(|s| with_dependencies(s, fetch.into(), env, given.host, &cwd, shell));
885 return lint::lint(fix, resolved, env, &cwd, given.host, given.temp, shell);
886 }
887 Some(Command::Doctor { compiler }) => {
888 let cwd = given.cwd()?;
889 let cli = CliSettings {
890 compiler: compiler.clone(),
891 ..CliSettings::default()
892 };
893 let resolved = resolve_settings(
894 Inputs {
895 cwd: &cwd,
896 env,
897 cores: given.cores,
898 cli: &cli,
899 },
900 shell,
901 );
902 let doctor_fetching = Fetching {
906 network: cuno_deps::Network::Offline,
907 lock: cuno_deps::LockMode::ReadOnly,
908 };
909 let resolved = resolved
910 .and_then(|s| with_dependencies(s, doctor_fetching, env, given.host, &cwd, shell));
911 let problems =
912 doctor::doctor(compiler, resolved, env, &cwd, given.host, given.temp, shell);
913 return Ok(if problems == 0 { 0 } else { 1 });
914 }
915 Some(
916 command @ (Command::Add { .. }
917 | Command::Remove { .. }
918 | Command::Update { .. }
919 | Command::Tree { .. }
920 | Command::Fetch { .. }),
921 ) => {
922 let cwd = given.cwd()?;
923 let resolved = resolve_settings(
924 Inputs {
925 cwd: &cwd,
926 env,
927 cores: given.cores,
928 cli: &CliSettings::default(),
929 },
930 shell,
931 );
932 let host = given.host;
933 return match command {
934 Command::Add {
935 name,
936 git,
937 tag,
938 rev,
939 branch,
940 url,
941 path,
942 version,
943 offline,
944 } => {
945 let reference = match (tag, rev, branch) {
946 (Some(tag), _, _) => cuno_manifest::GitReference::Tag(tag),
947 (_, Some(rev), _) => cuno_manifest::GitReference::Rev(rev),
948 (_, _, Some(branch)) => cuno_manifest::GitReference::Branch(branch),
949 (None, None, None) => cuno_manifest::GitReference::DefaultBranch,
950 };
951 let added = deps::NewDependency {
952 git,
953 reference,
954 url,
955 path,
956 version,
957 };
958 deps::add(name, added, offline, resolved, env, host, &cwd, shell)
959 }
960 Command::Remove { names, offline } => {
961 deps::remove(&names, offline, resolved, env, host, &cwd, shell)
962 }
963 Command::Update { name } => deps::update(name, resolved, env, host, &cwd, shell),
964 Command::Tree { fetch } => deps::tree(
965 fetch.into(),
966 resolved,
967 env,
968 host,
969 &cwd,
970 stdout.as_mut(),
971 shell,
972 ),
973 Command::Fetch { fetch } => {
974 deps::fetch(fetch.into(), resolved, env, host, &cwd, shell)
975 }
976 _ => unreachable!("only the dependency commands come here"),
977 };
978 }
979 Some(Command::Toolchain { command }) => {
980 let cwd = given.cwd()?;
981 let settings = resolve_settings(
982 Inputs {
983 cwd: &cwd,
984 env,
985 cores: given.cores,
986 cli: &CliSettings::default(),
987 },
988 shell,
989 )
990 .map_err(build::boxed)?;
991 return match command {
992 ToolchainCommand::List => {
993 toolchain::list(&settings, env, given.host, stdout.as_mut(), shell)
994 }
995 ToolchainCommand::Default { compiler } => {
996 toolchain::default(&compiler, &settings, env, given.host, shell)
997 }
998 };
999 }
1000 Some(Command::SelfCmd { command }) => {
1001 let cwd = given.cwd()?;
1005 resolve_settings(
1006 Inputs {
1007 cwd: &cwd,
1008 env,
1009 cores: given.cores,
1010 cli: &CliSettings::default(),
1011 },
1012 shell,
1013 )
1014 .map_err(build::boxed)?;
1015 return match command {
1016 SelfCommand::Update => self_cmd::update(given.exe, env, given.temp, shell),
1017 SelfCommand::Uninstall { yes } => {
1018 self_cmd::uninstall(given.exe, env, yes, input, shell)
1019 }
1020 };
1021 }
1022 None => {
1023 let usage = Cli::command().render_help();
1029 let _ = write_styled(stdout.as_mut(), &usage, help_color);
1030 return Ok(0);
1031 }
1032 };
1033 let cwd = given.cwd()?;
1034 let cli = CliSettings {
1035 compiler: opts.compiler.clone(),
1036 target_dir: opts.target_dir.clone(),
1037 jobs: opts.jobs,
1038 };
1039 let resolved = resolve_settings(
1040 Inputs {
1041 cwd: &cwd,
1042 env,
1043 cores: given.cores,
1044 cli: &cli,
1045 },
1046 shell,
1047 );
1048 build::build(
1049 goal,
1050 opts.into(),
1051 resolved,
1052 env,
1053 &cwd,
1054 given.host,
1055 given.temp,
1056 shell,
1057 )
1058}
1059
1060pub(crate) struct Input<'a> {
1062 pub(crate) stdin: &'a mut dyn BufRead,
1063 pub(crate) is_terminal: bool,
1064}
1065
1066#[derive(Debug)]
1068struct CwdError(String);
1069
1070impl std::fmt::Display for CwdError {
1071 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1072 write!(f, "cannot read the current directory: {}", self.0)
1073 }
1074}
1075
1076impl std::error::Error for CwdError {}
1077
1078impl CunoError for CwdError {
1079 fn exit_class(&self) -> cuno_core::ExitClass {
1080 cuno_core::ExitClass::Setup
1081 }
1082}
1083
1084fn report(shell: &mut Shell, error: &dyn CunoError) -> i32 {
1087 shell.error(error);
1088 if let Some(help) = error.help() {
1089 shell.help(help);
1090 }
1091 error.exit_class().code()
1092}
1093
1094#[cfg(debug_assertions)]
1099mod test_trigger {
1100 use cuno_core::{CunoError, Env, ExitClass};
1101
1102 pub fn fire(env: &Env) -> Result<(), Box<dyn CunoError>> {
1105 match env.get("CUNO_TEST_TRIGGER").and_then(|v| v.to_str()) {
1106 Some("setup-error") => Err(Box::new(Triggered)),
1107 Some("panic") => panic!("triggered by CUNO_TEST_TRIGGER"),
1108 _ => Ok(()),
1109 }
1110 }
1111
1112 #[derive(Debug)]
1113 struct Triggered;
1114 impl std::fmt::Display for Triggered {
1115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1116 f.write_str("triggered by CUNO_TEST_TRIGGER")
1117 }
1118 }
1119 impl std::error::Error for Triggered {}
1120 impl CunoError for Triggered {
1121 fn exit_class(&self) -> ExitClass {
1122 ExitClass::Setup
1123 }
1124 fn help(&self) -> Option<String> {
1125 Some("unset CUNO_TEST_TRIGGER".into())
1126 }
1127 }
1128}
1129
1130#[cfg(test)]
1131mod tests {
1132 use super::*;
1133 use cuno_core::NameCase;
1134 use std::cell::RefCell;
1135 use std::rc::Rc;
1136
1137 #[test]
1144 fn the_profile_help_names_every_profile() {
1145 let mut cli = Cli::command();
1146 for command in ["build", "check", "run", "test", "clean"] {
1147 let sub = cli.find_subcommand_mut(command).expect(command);
1148 let help = sub
1149 .get_arguments()
1150 .find(|a| a.get_id() == "profile")
1151 .and_then(|a| a.get_help())
1152 .map(|h| h.to_string())
1153 .expect(command);
1154 for (_, name) in cuno_manifest::Profile::ALL {
1155 assert!(help.contains(name), "{command}: {help}");
1156 }
1157 }
1158 }
1159
1160 #[derive(Clone, Default)]
1164 struct Captured {
1165 text: Rc<RefCell<Vec<u8>>>,
1166 pending: Rc<RefCell<Vec<u8>>>,
1167 buffered: bool,
1168 }
1169
1170 impl Write for Captured {
1171 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1172 let to = if self.buffered {
1173 &self.pending
1174 } else {
1175 &self.text
1176 };
1177 to.borrow_mut().extend_from_slice(buf);
1178 Ok(buf.len())
1179 }
1180 fn flush(&mut self) -> std::io::Result<()> {
1181 let pending = std::mem::take(&mut *self.pending.borrow_mut());
1182 self.text.borrow_mut().extend(pending);
1183 Ok(())
1184 }
1185 }
1186
1187 impl Captured {
1188 fn text(&self) -> String {
1189 String::from_utf8(self.text.borrow().clone()).unwrap()
1190 }
1191 }
1192
1193 struct Setup {
1196 stdout_is_terminal: bool,
1197 stderr_is_terminal: bool,
1198 cwd: Result<PathBuf, String>,
1199 buffered: bool,
1200 }
1201
1202 fn run_with(args: &[&str], setup: Setup) -> (i32, String, String) {
1205 let dir = tempfile::tempdir().unwrap();
1206 let env = Env::from_pairs(
1207 [("CUNO_HOME".into(), dir.path().join("home").into_os_string())],
1208 NameCase::Insensitive,
1209 );
1210 let stdout = Captured {
1211 buffered: setup.buffered,
1212 ..Captured::default()
1213 };
1214 let stderr = Captured::default();
1215 let code = run(Process {
1216 args: std::iter::once("cuno")
1217 .chain(args.iter().copied())
1218 .map(OsString::from)
1219 .collect(),
1220 env,
1221 cwd: setup.cwd.map(|_| dir.path().to_owned()),
1222 host: HostOs::Windows,
1223 temp: dir.path().to_owned(),
1224 exe: Err("not needed".to_owned()),
1225 cores: NonZeroU32::new(2).unwrap(),
1226 stdout: Box::new(stdout.clone()),
1227 stdout_is_terminal: setup.stdout_is_terminal,
1228 stderr: Box::new(stderr.clone()),
1229 stderr_is_terminal: setup.stderr_is_terminal,
1230 stdin: Box::new(std::io::empty()),
1231 stdin_is_terminal: false,
1232 });
1233 (code, stdout.text(), stderr.text())
1234 }
1235
1236 fn terminals(stdout_is_terminal: bool, stderr_is_terminal: bool) -> Setup {
1237 Setup {
1238 stdout_is_terminal,
1239 stderr_is_terminal,
1240 cwd: Ok(PathBuf::new()),
1241 buffered: false,
1242 }
1243 }
1244
1245 const ESC: char = '\u{1b}';
1246
1247 #[test]
1256 fn each_stream_is_colored_by_its_own_terminal() {
1257 for (stdout_tty, stderr_tty) in [(true, false), (false, true)] {
1258 let at = format!("stdout terminal {stdout_tty}, stderr terminal {stderr_tty}");
1259 let (code, out, _) = run_with(&["--help"], terminals(stdout_tty, stderr_tty));
1260 assert_eq!((code, out.contains(ESC)), (0, stdout_tty), "{at}: {out}");
1261 let (code, out, _) = run_with(&[], terminals(stdout_tty, stderr_tty));
1262 assert_eq!((code, out.contains(ESC)), (0, stdout_tty), "{at}: {out}");
1263 let (code, out, err) = run_with(&["bogus"], terminals(stdout_tty, stderr_tty));
1264 assert_eq!((code, out.as_str()), (2, ""), "{at}");
1265 assert_eq!(err.contains(ESC), stderr_tty, "{at}: {err}");
1266 let (code, _, err) = run_with(&["clean"], terminals(stdout_tty, stderr_tty));
1267 assert_eq!(code, 3, "{at}: {err}");
1268 assert_eq!(err.contains(ESC), stderr_tty, "{at}: {err}");
1269 }
1270 }
1271
1272 #[test]
1279 fn an_unreadable_current_directory_is_reported_by_each_command() {
1280 let unreadable = || Setup {
1281 cwd: Err("gone".to_owned()),
1282 ..terminals(false, false)
1283 };
1284 for args in [
1285 &["build"][..],
1286 &["check"],
1287 &["run"],
1288 &["test"],
1289 &["clean"],
1290 &["doctor"],
1291 &["new", "app"],
1292 ] {
1293 let (code, _, err) = run_with(args, unreadable());
1294 assert_eq!(code, 3, "{args:?}: {err}");
1295 assert_eq!(
1296 err, "error: cannot read the current directory: gone\n",
1297 "{args:?}"
1298 );
1299 }
1300 let (code, out, _) = run_with(&["--help"], unreadable());
1301 assert_eq!(code, 0);
1302 assert!(out.starts_with("Everything C/C++"), "{out}");
1303 }
1304
1305 #[test]
1310 fn help_is_flushed() {
1311 let (code, out, _) = run_with(
1312 &["--help"],
1313 Setup {
1314 buffered: true,
1315 ..terminals(false, false)
1316 },
1317 );
1318 assert_eq!(code, 0);
1319 assert!(out.starts_with("Everything C/C++"), "{out:?}");
1320 }
1321
1322 #[test]
1325 fn color_values_map_to_the_same_choice() {
1326 assert_eq!(ColorChoice::from(Color::Auto), ColorChoice::Auto);
1327 assert_eq!(ColorChoice::from(Color::Always), ColorChoice::Always);
1328 assert_eq!(ColorChoice::from(Color::Never), ColorChoice::Never);
1329 }
1330
1331 fn given(args: &[&str]) -> Option<ColorChoice> {
1332 let args: Vec<OsString> = std::iter::once("cuno")
1333 .chain(args.iter().copied())
1334 .map(OsString::from)
1335 .collect();
1336 color_before_parsing(&args)
1337 }
1338
1339 #[test]
1344 fn the_color_is_read_before_parsing() {
1345 assert_eq!(
1346 given(&["--color", "never", "build"]),
1347 Some(ColorChoice::Never)
1348 );
1349 assert_eq!(
1350 given(&["build", "--color=always"]),
1351 Some(ColorChoice::Always)
1352 );
1353 assert_eq!(
1354 given(&["--color", "never", "build", "--color", "always"]),
1355 Some(ColorChoice::Always)
1356 );
1357 assert_eq!(given(&["run", "--", "--color", "never"]), None);
1358 assert_eq!(given(&["--color", "bogus"]), None);
1359 assert_eq!(given(&["--color=never", "--color=bogus"]), None);
1360 assert_eq!(given(&["build"]), None);
1361 assert_eq!(given(&["--color=always", "--color"]), None);
1362 #[cfg(windows)]
1363 {
1364 use std::os::windows::ffi::OsStringExt;
1365 let lone = OsString::from_wide(&[0xD800]);
1366 let mut equals = OsString::from("--color=");
1367 equals.push(&lone);
1368 for bad in [vec![OsString::from("--color"), lone], vec![equals]] {
1369 let args: Vec<OsString> = ["cuno", "--color", "always"]
1370 .into_iter()
1371 .map(OsString::from)
1372 .chain(bad)
1373 .collect();
1374 assert_eq!(color_before_parsing(&args), None, "{args:?}");
1375 }
1376 }
1377 }
1378
1379 #[test]
1382 fn what_clap_prints_follows_cunos_order() {
1383 use clap::ColorChoice as Clap;
1384 assert_eq!(
1385 parser_color(Some(ColorChoice::Always), true, false),
1386 Clap::Always
1387 );
1388 assert_eq!(
1389 parser_color(Some(ColorChoice::Never), false, true),
1390 Clap::Never
1391 );
1392 assert_eq!(
1393 parser_color(Some(ColorChoice::Auto), true, true),
1394 Clap::Always
1395 );
1396 assert_eq!(
1397 parser_color(Some(ColorChoice::Auto), false, false),
1398 Clap::Never
1399 );
1400 assert_eq!(parser_color(None, true, true), Clap::Never);
1401 assert_eq!(parser_color(None, false, true), Clap::Always);
1402 assert_eq!(parser_color(None, false, false), Clap::Never);
1403 }
1404
1405 #[test]
1413 fn self_uninstall_takes_yes_and_the_terminal_from_the_command_line() {
1414 for (args, code, gone) in [
1415 (vec!["self", "uninstall"], 2, false),
1416 (vec!["self", "uninstall", "-y"], 0, true),
1417 (vec!["self", "uninstall", "--yes"], 0, true),
1418 ] {
1419 let dir = tempfile::tempdir().unwrap();
1420 let home = dir.path().join("home");
1421 std::fs::create_dir_all(&home).unwrap();
1422 std::fs::write(home.join("config.toml"), "").unwrap();
1423 let env = Env::from_pairs(
1424 [
1425 ("CUNO_HOME".into(), home.clone().into_os_string()),
1426 (
1427 "USERPROFILE".into(),
1428 dir.path().join("user").into_os_string(),
1429 ),
1430 ],
1431 NameCase::Insensitive,
1432 );
1433 let stderr = Captured::default();
1434 let got = run(Process {
1435 args: std::iter::once("cuno")
1436 .chain(args.iter().copied())
1437 .map(OsString::from)
1438 .collect(),
1439 env,
1440 cwd: Ok(dir.path().to_owned()),
1441 host: HostOs::Windows,
1442 temp: dir.path().to_owned(),
1443 exe: Ok(dir.path().join("tools").join("cuno.exe")),
1444 cores: NonZeroU32::new(2).unwrap(),
1445 stdout: Box::new(Captured::default()),
1446 stdout_is_terminal: false,
1447 stderr: Box::new(stderr.clone()),
1448 stderr_is_terminal: false,
1449 stdin: Box::new(std::io::empty()),
1450 stdin_is_terminal: false,
1451 });
1452 assert_eq!(got, code, "{args:?}: {}", stderr.text());
1453 assert_eq!(!home.exists(), gone, "{args:?}");
1454 }
1455 }
1456}