mod build;
mod clean;
mod doctor;
mod fmt;
mod lint;
mod new;
use std::ffi::OsString;
use std::io::Write;
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use cuno_core::{ColorChoice, CunoError, Env, Shell, Verbosity};
use cuno_manifest::{CliSettings, ConfigError, Inputs, Settings};
pub use cuno_toolchain::HostOs;
pub struct Process {
pub args: Vec<OsString>,
pub env: Env,
pub cwd: Result<PathBuf, String>,
pub host: HostOs,
pub temp: PathBuf,
pub stdout: Box<dyn Write>,
pub stdout_is_terminal: bool,
pub stderr: Box<dyn Write>,
pub stderr_is_terminal: bool,
}
#[derive(Parser)]
#[command(
// `name` is what `--version` prints ("cuno <version>"); `bin_name` is what
// the usage line prints. Without `bin_name`, clap takes the executable's
// file name, which is `cuno.exe` on Windows.
name = "cuno",
bin_name = "cuno",
version,
// Taken from `description` in Cargo.toml, so the two cannot drift apart.
about
)]
struct Cli {
#[arg(long, value_name = "WHEN", value_enum, global = true)]
color: Option<Color>,
#[arg(short, long, global = true, conflicts_with = "quiet")]
verbose: bool,
#[arg(short, long, global = true)]
quiet: bool,
#[command(subcommand)]
command: Option<Command>,
}
#[derive(Subcommand)]
enum Command {
New {
#[arg(value_name = "PATH")]
path: PathBuf,
#[arg(long, value_name = "LANG", value_parser = ["c", "c++"])]
lang: Option<String>,
#[arg(long, value_name = "EDITION", value_parser = ["c++17", "c++20", "c++23", "c11", "c17", "c23"])]
edition: Option<String>,
#[arg(long, value_name = "NAME")]
name: Option<String>,
#[arg(long, value_name = "VCS", value_parser = ["git", "none"], default_value = "git")]
vcs: String,
},
Build(BuildOpts),
Check {
#[arg(long)]
tests: bool,
#[arg(long)]
all_targets: bool,
#[command(flatten)]
opts: BuildOpts,
},
Run {
#[arg(long, value_name = "NAME")]
bin: Option<String>,
#[command(flatten)]
opts: BuildOpts,
#[arg(last = true, value_name = "ARGS")]
args: Vec<OsString>,
},
Test {
#[arg(value_name = "FILTER")]
filter: Option<String>,
#[arg(long)]
nocapture: bool,
#[command(flatten)]
opts: BuildOpts,
},
Fmt {
#[arg(long)]
check: bool,
},
Lint {
#[arg(long)]
fix: bool,
#[arg(long, value_name = "NAME")]
compiler: Option<String>,
},
Clean {
#[arg(long, conflicts_with = "profile")]
release: bool,
#[arg(long, value_name = "NAME")]
profile: Option<String>,
#[arg(long, value_name = "PATH")]
target_dir: Option<PathBuf>,
},
Doctor {
#[arg(long, value_name = "NAME")]
compiler: Option<String>,
},
}
#[derive(Args)]
struct BuildOpts {
#[arg(long, conflicts_with = "profile")]
release: bool,
#[arg(long, value_name = "NAME")]
profile: Option<String>,
#[arg(long, value_name = "NAME")]
compiler: Option<String>,
#[arg(long, value_name = "TRIPLE")]
target: Option<String>,
#[arg(long, value_name = "PATH")]
target_dir: Option<PathBuf>,
#[arg(short, long, value_name = "N")]
jobs: Option<NonZeroU32>,
}
impl From<BuildOpts> for build::BuildArgs {
fn from(o: BuildOpts) -> build::BuildArgs {
build::BuildArgs {
release: o.release,
profile: o.profile,
target: o.target,
}
}
}
fn color_before_parsing(args: &[OsString]) -> Option<ColorChoice> {
let mut found = None;
let mut args = args.iter().skip(1);
while let Some(arg) = args.next() {
let value = match arg.to_str() {
Some("--") => break,
Some("--color") => Some(args.next().and_then(|v| v.to_str())),
Some(arg) => arg.strip_prefix("--color=").map(Some),
None => arg
.as_encoded_bytes()
.starts_with(b"--color=")
.then_some(None),
};
if let Some(value) = value {
found = Some(
value
.and_then(|v| Color::from_str(v, false).ok())
.map(ColorChoice::from),
);
}
}
found.flatten()
}
fn parser_color(given: Option<ColorChoice>, no_color: bool, terminal: bool) -> clap::ColorChoice {
if cuno_core::colors(given, None, no_color, terminal) {
clap::ColorChoice::Always
} else {
clap::ColorChoice::Never
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum Color {
Auto,
Always,
Never,
}
impl From<Color> for ColorChoice {
fn from(color: Color) -> ColorChoice {
match color {
Color::Auto => ColorChoice::Auto,
Color::Always => ColorChoice::Always,
Color::Never => ColorChoice::Never,
}
}
}
pub fn run(process: Process) -> i32 {
let Process {
args,
env,
cwd,
host,
temp,
mut stdout,
stdout_is_terminal,
mut stderr,
stderr_is_terminal,
} = process;
let given = color_before_parsing(&args);
let no_color = env.get("NO_COLOR").is_some();
let stdout_color = parser_color(given, no_color, stdout_is_terminal);
let stderr_color = parser_color(given, no_color, stderr_is_terminal);
let cli = match Cli::command().try_get_matches_from(&args) {
Ok(matches) => match Cli::from_arg_matches(&matches) {
Ok(cli) => cli,
Err(e) => {
let e = e.format(&mut Cli::command());
return print_clap(&e, stdout_color, stderr_color, &mut stdout, &mut stderr);
}
},
Err(error) => {
return print_clap(&error, stdout_color, stderr_color, &mut stdout, &mut stderr);
}
};
let mut shell = Shell::new(
stderr,
cli.color.map(ColorChoice::from),
&env,
stderr_is_terminal,
);
let given = Values {
env: &env,
cwd: &cwd,
host,
temp: &temp,
};
match dispatch(cli, given, &mut shell, stdout_color, &mut stdout) {
Ok(code) => code,
Err(error) => report(&mut shell, &*error),
}
}
fn print_clap(
error: &clap::Error,
stdout_color: clap::ColorChoice,
stderr_color: clap::ColorChoice,
stdout: &mut Box<dyn Write>,
stderr: &mut Box<dyn Write>,
) -> i32 {
let (out, color) = if error.use_stderr() {
(stderr, stderr_color)
} else {
(stdout, stdout_color)
};
let _ = write_styled(out.as_mut(), &error.render(), color);
error.exit_code()
}
fn write_styled(
out: &mut dyn Write,
text: &clap::builder::StyledStr,
color: clap::ColorChoice,
) -> std::io::Result<()> {
match color {
clap::ColorChoice::Always => write!(out, "{}", text.ansi())?,
_ => write!(out, "{text}")?,
}
out.flush()
}
#[derive(Clone, Copy)]
struct Values<'a> {
env: &'a Env,
cwd: &'a Result<PathBuf, String>,
host: HostOs,
temp: &'a Path,
}
impl Values<'_> {
fn cwd(&self) -> Result<PathBuf, Box<dyn CunoError>> {
self.cwd
.clone()
.map_err(|e| Box::new(CwdError(e)) as Box<dyn CunoError>)
}
}
fn resolve_settings(inputs: Inputs<'_>, shell: &mut Shell) -> Result<Settings, ConfigError> {
let loaded = cuno_manifest::resolve(inputs)?;
shell.configure(loaded.value.color, loaded.value.verbose);
for warning in &loaded.warnings {
shell.warning(warning);
}
Ok(loaded.value)
}
fn resolve_user_settings(env: &Env, cwd: &Path, shell: &mut Shell) -> Result<(), ConfigError> {
let loaded = cuno_manifest::resolve_user(env, cwd)?;
shell.configure(loaded.value.color, loaded.value.verbose);
for warning in &loaded.warnings {
shell.warning(warning);
}
Ok(())
}
fn dispatch(
cli: Cli,
given: Values<'_>,
shell: &mut Shell,
help_color: clap::ColorChoice,
stdout: &mut Box<dyn Write>,
) -> Result<i32, Box<dyn CunoError>> {
let env = given.env;
let Cli {
color: _,
verbose,
quiet,
command,
} = cli;
shell.set_verbosity(if quiet {
Verbosity::Quiet
} else if verbose {
Verbosity::Verbose
} else {
Verbosity::Normal
});
#[cfg(debug_assertions)]
test_trigger::fire(env)?;
let (goal, opts) = match command {
Some(Command::Build(opts)) => (build::Goal::Build, opts),
Some(Command::Check {
tests,
all_targets,
opts,
}) => (
build::Goal::Check {
programs: !tests || all_targets,
tests: tests || all_targets,
},
opts,
),
Some(Command::Run { bin, opts, args }) => (build::Goal::Run { bin, args }, opts),
Some(Command::Test {
filter,
nocapture,
opts,
}) => (build::Goal::Test { filter, nocapture }, opts),
Some(Command::Clean {
release,
profile,
target_dir,
}) => {
let cwd = given.cwd()?;
let cli = CliSettings {
target_dir,
..CliSettings::default()
};
let resolved = resolve_settings(
Inputs {
cwd: &cwd,
env,
cli: &cli,
},
shell,
);
clean::clean(
clean::CleanArgs { release, profile },
resolved,
&cwd,
given.host,
shell,
)?;
return Ok(0);
}
Some(Command::New {
path,
lang,
edition,
name,
vcs,
}) => {
let cwd = given.cwd()?;
resolve_user_settings(env, &cwd, shell).map_err(build::boxed)?;
let args = new::NewArgs {
path,
lang: lang
.map(|l| cuno_toolchain::flags::Lang::parse(&l).expect("a lang clap admits")),
edition: edition.map(|e| {
cuno_toolchain::flags::Edition::parse(&e).expect("an edition clap admits")
}),
name,
vcs: if vcs == "none" {
new::Vcs::None
} else {
new::Vcs::Git
},
};
new::new(args, &cwd, shell).map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
return Ok(0);
}
Some(Command::Fmt { check }) => {
let cwd = given.cwd()?;
let resolved = resolve_settings(
Inputs {
cwd: &cwd,
env,
cli: &CliSettings::default(),
},
shell,
);
return fmt::fmt(check, resolved, env, &cwd, given.host, given.temp, shell);
}
Some(Command::Lint { fix, compiler }) => {
let cwd = given.cwd()?;
let cli = CliSettings {
compiler,
..CliSettings::default()
};
let resolved = resolve_settings(
Inputs {
cwd: &cwd,
env,
cli: &cli,
},
shell,
);
return lint::lint(fix, resolved, env, &cwd, given.host, given.temp, shell);
}
Some(Command::Doctor { compiler }) => {
let cwd = given.cwd()?;
let cli = CliSettings {
compiler: compiler.clone(),
..CliSettings::default()
};
let resolved = resolve_settings(
Inputs {
cwd: &cwd,
env,
cli: &cli,
},
shell,
);
let problems =
doctor::doctor(compiler, resolved, env, &cwd, given.host, given.temp, shell);
return Ok(if problems == 0 { 0 } else { 1 });
}
None => {
let usage = Cli::command().render_help();
let _ = write_styled(stdout.as_mut(), &usage, help_color);
return Ok(0);
}
};
let cwd = given.cwd()?;
let cli = CliSettings {
compiler: opts.compiler.clone(),
target_dir: opts.target_dir.clone(),
jobs: opts.jobs,
};
let resolved = resolve_settings(
Inputs {
cwd: &cwd,
env,
cli: &cli,
},
shell,
);
build::build(
goal,
opts.into(),
resolved,
env,
&cwd,
given.host,
given.temp,
shell,
)
}
#[derive(Debug)]
struct CwdError(String);
impl std::fmt::Display for CwdError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "cannot read the current directory: {}", self.0)
}
}
impl std::error::Error for CwdError {}
impl CunoError for CwdError {
fn exit_class(&self) -> cuno_core::ExitClass {
cuno_core::ExitClass::Setup
}
}
fn report(shell: &mut Shell, error: &dyn CunoError) -> i32 {
shell.error(error);
if let Some(help) = error.help() {
shell.help(help);
}
error.exit_class().code()
}
#[cfg(debug_assertions)]
mod test_trigger {
use cuno_core::{CunoError, Env, ExitClass};
pub fn fire(env: &Env) -> Result<(), Box<dyn CunoError>> {
match env.get("CUNO_TEST_TRIGGER").and_then(|v| v.to_str()) {
Some("setup-error") => Err(Box::new(Triggered)),
Some("panic") => panic!("triggered by CUNO_TEST_TRIGGER"),
_ => Ok(()),
}
}
#[derive(Debug)]
struct Triggered;
impl std::fmt::Display for Triggered {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("triggered by CUNO_TEST_TRIGGER")
}
}
impl std::error::Error for Triggered {}
impl CunoError for Triggered {
fn exit_class(&self) -> ExitClass {
ExitClass::Setup
}
fn help(&self) -> Option<String> {
Some("unset CUNO_TEST_TRIGGER".into())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use cuno_core::NameCase;
use std::cell::RefCell;
use std::rc::Rc;
#[test]
fn the_profile_help_names_every_profile() {
let mut cli = Cli::command();
for command in ["build", "check", "run", "test", "clean"] {
let sub = cli.find_subcommand_mut(command).expect(command);
let help = sub
.get_arguments()
.find(|a| a.get_id() == "profile")
.and_then(|a| a.get_help())
.map(|h| h.to_string())
.expect(command);
for (_, name) in cuno_manifest::Profile::ALL {
assert!(help.contains(name), "{command}: {help}");
}
}
}
#[derive(Clone, Default)]
struct Captured {
text: Rc<RefCell<Vec<u8>>>,
pending: Rc<RefCell<Vec<u8>>>,
buffered: bool,
}
impl Write for Captured {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let to = if self.buffered {
&self.pending
} else {
&self.text
};
to.borrow_mut().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
let pending = std::mem::take(&mut *self.pending.borrow_mut());
self.text.borrow_mut().extend(pending);
Ok(())
}
}
impl Captured {
fn text(&self) -> String {
String::from_utf8(self.text.borrow().clone()).unwrap()
}
}
struct Setup {
stdout_is_terminal: bool,
stderr_is_terminal: bool,
cwd: Result<PathBuf, String>,
buffered: bool,
}
fn run_with(args: &[&str], setup: Setup) -> (i32, String, String) {
let dir = tempfile::tempdir().unwrap();
let env = Env::from_pairs(
[("CUNO_HOME".into(), dir.path().join("home").into_os_string())],
NameCase::Insensitive,
);
let stdout = Captured {
buffered: setup.buffered,
..Captured::default()
};
let stderr = Captured::default();
let code = run(Process {
args: std::iter::once("cuno")
.chain(args.iter().copied())
.map(OsString::from)
.collect(),
env,
cwd: setup.cwd.map(|_| dir.path().to_owned()),
host: HostOs::Windows,
temp: dir.path().to_owned(),
stdout: Box::new(stdout.clone()),
stdout_is_terminal: setup.stdout_is_terminal,
stderr: Box::new(stderr.clone()),
stderr_is_terminal: setup.stderr_is_terminal,
});
(code, stdout.text(), stderr.text())
}
fn terminals(stdout_is_terminal: bool, stderr_is_terminal: bool) -> Setup {
Setup {
stdout_is_terminal,
stderr_is_terminal,
cwd: Ok(PathBuf::new()),
buffered: false,
}
}
const ESC: char = '\u{1b}';
#[test]
fn each_stream_is_colored_by_its_own_terminal() {
for (stdout_tty, stderr_tty) in [(true, false), (false, true)] {
let at = format!("stdout terminal {stdout_tty}, stderr terminal {stderr_tty}");
let (code, out, _) = run_with(&["--help"], terminals(stdout_tty, stderr_tty));
assert_eq!((code, out.contains(ESC)), (0, stdout_tty), "{at}: {out}");
let (code, out, _) = run_with(&[], terminals(stdout_tty, stderr_tty));
assert_eq!((code, out.contains(ESC)), (0, stdout_tty), "{at}: {out}");
let (code, out, err) = run_with(&["bogus"], terminals(stdout_tty, stderr_tty));
assert_eq!((code, out.as_str()), (2, ""), "{at}");
assert_eq!(err.contains(ESC), stderr_tty, "{at}: {err}");
let (code, _, err) = run_with(&["clean"], terminals(stdout_tty, stderr_tty));
assert_eq!(code, 3, "{at}: {err}");
assert_eq!(err.contains(ESC), stderr_tty, "{at}: {err}");
}
}
#[test]
fn an_unreadable_current_directory_is_reported_by_each_command() {
let unreadable = || Setup {
cwd: Err("gone".to_owned()),
..terminals(false, false)
};
for args in [
&["build"][..],
&["check"],
&["run"],
&["test"],
&["clean"],
&["doctor"],
&["new", "app"],
] {
let (code, _, err) = run_with(args, unreadable());
assert_eq!(code, 3, "{args:?}: {err}");
assert_eq!(
err, "error: cannot read the current directory: gone\n",
"{args:?}"
);
}
let (code, out, _) = run_with(&["--help"], unreadable());
assert_eq!(code, 0);
assert!(out.starts_with("Everything C/C++"), "{out}");
}
#[test]
fn help_is_flushed() {
let (code, out, _) = run_with(
&["--help"],
Setup {
buffered: true,
..terminals(false, false)
},
);
assert_eq!(code, 0);
assert!(out.starts_with("Everything C/C++"), "{out:?}");
}
#[test]
fn color_values_map_to_the_same_choice() {
assert_eq!(ColorChoice::from(Color::Auto), ColorChoice::Auto);
assert_eq!(ColorChoice::from(Color::Always), ColorChoice::Always);
assert_eq!(ColorChoice::from(Color::Never), ColorChoice::Never);
}
fn given(args: &[&str]) -> Option<ColorChoice> {
let args: Vec<OsString> = std::iter::once("cuno")
.chain(args.iter().copied())
.map(OsString::from)
.collect();
color_before_parsing(&args)
}
#[test]
fn the_color_is_read_before_parsing() {
assert_eq!(
given(&["--color", "never", "build"]),
Some(ColorChoice::Never)
);
assert_eq!(
given(&["build", "--color=always"]),
Some(ColorChoice::Always)
);
assert_eq!(
given(&["--color", "never", "build", "--color", "always"]),
Some(ColorChoice::Always)
);
assert_eq!(given(&["run", "--", "--color", "never"]), None);
assert_eq!(given(&["--color", "bogus"]), None);
assert_eq!(given(&["--color=never", "--color=bogus"]), None);
assert_eq!(given(&["build"]), None);
assert_eq!(given(&["--color=always", "--color"]), None);
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt;
let lone = OsString::from_wide(&[0xD800]);
let mut equals = OsString::from("--color=");
equals.push(&lone);
for bad in [vec![OsString::from("--color"), lone], vec![equals]] {
let args: Vec<OsString> = ["cuno", "--color", "always"]
.into_iter()
.map(OsString::from)
.chain(bad)
.collect();
assert_eq!(color_before_parsing(&args), None, "{args:?}");
}
}
}
#[test]
fn what_clap_prints_follows_cunos_order() {
use clap::ColorChoice as Clap;
assert_eq!(
parser_color(Some(ColorChoice::Always), true, false),
Clap::Always
);
assert_eq!(
parser_color(Some(ColorChoice::Never), false, true),
Clap::Never
);
assert_eq!(
parser_color(Some(ColorChoice::Auto), true, true),
Clap::Always
);
assert_eq!(
parser_color(Some(ColorChoice::Auto), false, false),
Clap::Never
);
assert_eq!(parser_color(None, true, true), Clap::Never);
assert_eq!(parser_color(None, false, true), Clap::Always);
assert_eq!(parser_color(None, false, false), Clap::Never);
}
}