1mod 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
26pub use cuno_toolchain::HostOs;
30
31pub struct Process {
35 pub args: Vec<OsString>,
37 pub env: Env,
39 pub cwd: Result<PathBuf, String>,
42 pub host: HostOs,
44 pub temp: PathBuf,
46 pub stdout: Box<dyn Write>,
49 pub stdout_is_terminal: bool,
51 pub stderr: Box<dyn Write>,
53 pub stderr_is_terminal: bool,
55}
56
57#[derive(Parser)]
60#[command(
61 name = "cuno",
65 bin_name = "cuno",
66 version,
67 about
69)]
70struct Cli {
71 #[arg(long, value_name = "WHEN", value_enum, global = true)]
77 color: Option<Color>,
78
79 #[arg(short, long, global = true, conflicts_with = "quiet")]
81 verbose: bool,
82
83 #[arg(short, long, global = true)]
85 quiet: bool,
86
87 #[command(subcommand)]
88 command: Option<Command>,
89}
90
91#[derive(Subcommand)]
93enum Command {
94 New {
96 #[arg(value_name = "PATH")]
98 path: PathBuf,
99 #[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
101 lang: Option<String>,
102 #[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
104 edition: Option<String>,
105 #[arg(long, value_name = "NAME")]
107 name: Option<String>,
108 #[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
110 vcs: String,
111 },
112 Build(BuildOpts),
114 Check {
116 #[arg(long)]
118 tests: bool,
119 #[arg(long)]
121 all_targets: bool,
122 #[command(flatten)]
123 opts: BuildOpts,
124 },
125 Run {
127 #[arg(long, value_name = "NAME")]
129 bin: Option<String>,
130 #[command(flatten)]
131 opts: BuildOpts,
132 #[arg(last = true, value_name = "ARGS")]
134 args: Vec<OsString>,
135 },
136 Test {
138 #[arg(value_name = "FILTER")]
140 filter: Option<String>,
141 #[arg(long)]
143 nocapture: bool,
144 #[command(flatten)]
145 opts: BuildOpts,
146 },
147 Fmt {
149 #[arg(long)]
151 check: bool,
152 },
153 Lint {
155 #[arg(long)]
157 fix: bool,
158 #[arg(long, value_name = "NAME")]
160 compiler: Option<String>,
161 },
162 Clean {
164 #[arg(long, conflicts_with = "profile")]
166 release: bool,
167 #[arg(long, value_name = "NAME")]
169 profile: Option<String>,
170 #[arg(long, value_name = "PATH")]
172 target_dir: Option<PathBuf>,
173 },
174 Doctor {
176 #[arg(long, value_name = "NAME")]
178 compiler: Option<String>,
179 },
180}
181
182#[derive(Args)]
185struct BuildOpts {
186 #[arg(long, conflicts_with = "profile")]
188 release: bool,
189 #[arg(long, value_name = "NAME")]
191 profile: Option<String>,
192 #[arg(long, value_name = "NAME")]
194 compiler: Option<String>,
195 #[arg(long, value_name = "TRIPLE")]
197 target: Option<String>,
198 #[arg(long, value_name = "PATH")]
200 target_dir: Option<PathBuf>,
201 #[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
216fn 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 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
248fn 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#[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
279pub 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 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 let cli = match Cli::command().try_get_matches_from(&args) {
306 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
337fn 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 let _ = write_styled(out.as_mut(), &error.render(), color);
355 error.exit_code()
356}
357
358fn 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#[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 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
392fn 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
406fn 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
418fn 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 let Cli {
433 color: _,
434 verbose,
435 quiet,
436 command,
437 } = cli;
438
439 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 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 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 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#[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
627fn 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#[cfg(debug_assertions)]
642mod test_trigger {
643 use cuno_core::{CunoError, Env, ExitClass};
644
645 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 #[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 #[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 struct Setup {
739 stdout_is_terminal: bool,
740 stderr_is_terminal: bool,
741 cwd: Result<PathBuf, String>,
742 buffered: bool,
743 }
744
745 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 #[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 #[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 #[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 #[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 #[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 #[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}