//! Global CLI Setup. use std::env; use std::io; use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum}; use clap_complete::Shell; use const_format::{concatcp, formatcp}; use tracing_subscriber::EnvFilter; use tracing_subscriber::filter::LevelFilter; use crate::{ command::{self, apply::DeployOpts}, error::{ColmenaError, ColmenaResult}, nix::{Hive, HivePath, NixFlags}, }; /// Base URL of the manual, without the trailing slash. const MANUAL_URL_BASE: &str = "https://colmena.cli.rs"; /// URL to the manual. /// /// We maintain CLI and Nix API stability for each minor version. /// This ensures that the user always sees accurate documentations, and we can /// easily perform updates to the manual after a release. const MANUAL_URL: &str = concatcp!( MANUAL_URL_BASE, "/", env!("CARGO_PKG_VERSION_MAJOR"), ".", env!("CARGO_PKG_VERSION_MINOR") ); /// The note shown when the user is using a pre-release version. /// /// API stability cannot be guaranteed for pre-release versions. /// Links to the version currently in development automatically /// leads the user to the unstable manual. const MANUAL_DISCREPANCY_NOTE: &str = "\nNote: You are using a pre-release version of Colmena, so the supported options may be different from what's in the manual."; static LONG_ABOUT: &str = formatcp!( r#"NixOS deployment tool Colmena helps you deploy to multiple hosts running NixOS. For more details, read the manual at <{}>. {}"#, MANUAL_URL, if !env!("CARGO_PKG_VERSION_PRE").is_empty() { MANUAL_DISCREPANCY_NOTE } else { "" } ); static CONFIG_HELP: &str = formatcp!( r#"If this argument is not specified, Colmena will search upwards from the current working directory for a file named "flake.nix" or "hive.nix". This behavior is disabled if --config/-f is given explicitly. For a sample configuration, check the manual at <{}>. "#, MANUAL_URL ); /// Display order in `--help` for arguments that should be shown first. /// /// Currently reserved for -f/--config. const HELP_ORDER_FIRST: usize = 100; /// Display order in `--help` for arguments that are not very important. const HELP_ORDER_LOW: usize = 2000; /// When to display color. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, ValueEnum)] enum ColorWhen { /// Detect automatically. #[default] Auto, /// Always display colors. Always, /// Never display colors. Never, } impl std::fmt::Display for ColorWhen { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::Auto => "auto", Self::Always => "always", Self::Never => "never", }) } } /// NixOS deployment tool #[derive(Parser)] #[command( name = "Colmena", bin_name = "colmena", author = "Zhaofeng Li ", version = env!("CARGO_PKG_VERSION"), long_about = LONG_ABOUT, max_term_width = 100, )] struct Opts { #[command(flatten)] hive: HiveOpts, /// When to colorize the output /// /// By default, Colmena enables colorized output when the terminal supports it. /// /// It's also possible to specify the preference using environment variables. See /// . #[arg( long, value_name = "WHEN", default_value_t, global = true, display_order = HELP_ORDER_LOW, )] color: ColorWhen, #[command(subcommand)] command: Command, } /// Global options locating the hive and configuring the Nix commands that /// evaluate it. /// /// They are kept apart from the subcommand because the hive is loaded /// after the subcommand has been taken out of [`Opts`]. #[derive(Args)] struct HiveOpts { /// Path to a hive.nix, a flake.nix, a directory containing a flake.nix, hive.nix or default.nix, or a Nix Flake URI #[arg( short = 'f', long, value_name = "CONFIG", long_help = CONFIG_HELP, display_order = HELP_ORDER_FIRST, global = true, )] config: Option, /// Show debug information for Nix commands /// /// Passes --show-trace to Nix commands #[arg(long, global = true)] show_trace: bool, /// Allow impure expressions /// /// Passes --impure to Nix commands #[arg(long, global = true)] impure: bool, /// Passes an arbitrary option to Nix commands /// /// Applies to every Nix invocation Colmena makes, on this machine and on /// deployment targets. A value naming a local path, such as /// extra-builtins-file, is passed to the targets unchanged, where the /// path may not exist. #[arg( long, global = true, num_args = 2, value_names = ["NAME", "VALUE"], )] nix_option: Vec, } #[derive(Subcommand)] enum Command { Apply(command::apply::Opts), #[cfg(target_os = "linux")] ApplyLocal(command::apply_local::Opts), /// Build configurations but not push to remote machines /// /// This subcommand behaves as if you invoked `apply` with the `build` goal. Build { #[command(flatten)] deploy: DeployOpts, }, Eval(command::eval::Opts), /// Upload keys to remote hosts /// /// This subcommand behaves as if you invoked `apply` with the pseudo `keys` goal. UploadKeys { #[command(flatten)] deploy: DeployOpts, }, Exec(command::exec::Opts), /// Start an interactive REPL with the complete configuration /// /// In the REPL, you can inspect the configuration interactively with tab /// completion. The node configurations are accessible under the `nodes` /// attribute set. Repl, /// Show information about the current Nix installation NixInfo, /// Run progress spinner tests #[cfg(debug_assertions)] #[command(hide = true)] TestProgress, /// Generate shell auto-completion files (Internal) #[command(hide = true)] GenCompletions { shell: Shell, }, } /// Builds the Nix flags from the CLI options. fn get_nix_flags(opts: &HiveOpts) -> NixFlags { let mut flags = NixFlags::default(); flags.set_show_trace(opts.show_trace); flags.set_impure(opts.impure); for [name, value] in opts.nix_option.as_chunks::<2>().0 { flags.add_option(name.clone(), value.clone()); } flags } async fn get_hive(opts: &HiveOpts, flags: NixFlags) -> ColmenaResult { let path = match &opts.config { Some(config) => HivePath::resolve(config, &flags).await?, None => { // traverse upwards until we find hive.nix let mut cur = std::env::current_dir()?; let mut file_path = None; loop { let flake = cur.join("flake.nix"); if flake.is_file() { file_path = Some(flake); break; } let legacy = cur.join("hive.nix"); if legacy.is_file() { file_path = Some(legacy); break; } match cur.parent() { Some(parent) => { cur = parent.to_owned(); } None => { break; } } } let Some(file_path) = file_path else { return Err(ColmenaError::NoHiveFound { dir: std::env::current_dir()?, }); }; HivePath::from_path(file_path, &flags).await? } }; match &path { HivePath::Legacy(p) => { tracing::info!("Using configuration: {}", p.to_string_lossy()); } HivePath::Flake(flake) => { tracing::info!("Using flake: {}", flake.uri()); } } Hive::new(path, flags) } /// Loads the hive, exiting with code 2 when that fails. async fn load_hive(opts: &HiveOpts, flags: NixFlags) -> Hive { match get_hive(opts, flags).await { Ok(hive) => hive, Err(error) => { tracing::error!("Failed to load the hive: {}", error); quit::with_code(2); } } } pub async fn run() { let opts = Opts::parse(); set_color_pref(&opts.color); init_logging(); if let Command::GenCompletions { shell } = opts.command { print_completions(shell, &mut Opts::command()); return; } let flags = get_nix_flags(&opts.hive); use crate::troubleshooter::run_wrapped as r; match opts.command { Command::Apply(args) => { let hive = load_hive(&opts.hive, flags).await; r(command::apply::run(hive, args)).await } #[cfg(target_os = "linux")] Command::ApplyLocal(args) => { let hive = load_hive(&opts.hive, flags).await; r(command::apply_local::run(hive, args)).await } Command::Eval(args) => { let hive = load_hive(&opts.hive, flags).await; r(command::eval::run(hive, args)).await } Command::Exec(args) => { let hive = load_hive(&opts.hive, flags).await; r(command::exec::run(hive, args)).await } Command::NixInfo => r(command::nix_info::run(flags)).await, Command::Repl => { let hive = load_hive(&opts.hive, flags).await; r(command::repl::run(hive)).await } #[cfg(debug_assertions)] Command::TestProgress => r(command::test_progress::run()).await, Command::Build { deploy } => { let hive = load_hive(&opts.hive, flags).await; let args = command::apply::Opts { deploy, goal: crate::nix::Goal::Build, }; r(command::apply::run(hive, args)).await } Command::UploadKeys { deploy } => { let hive = load_hive(&opts.hive, flags).await; let args = command::apply::Opts { deploy, goal: crate::nix::Goal::UploadKeys, }; r(command::apply::run(hive, args)).await } Command::GenCompletions { .. } => unreachable!(), } } fn print_completions(shell: Shell, cmd: &mut clap::Command) { let bin_name = cmd .get_bin_name() .expect("Must have a bin_name") .to_string(); clap_complete::generate(shell, cmd, bin_name, &mut std::io::stdout()); } fn set_color_pref(when: &ColorWhen) { if when != &ColorWhen::Auto { console::set_colors_enabled(when == &ColorWhen::Always); console::set_colors_enabled_stderr(when == &ColorWhen::Always); } } fn init_logging() { let colors_enabled = console::colors_enabled_stderr(); let filter = EnvFilter::builder() .with_default_directive(LevelFilter::INFO.into()) .from_env_lossy(); tracing_subscriber::fmt() .with_target(false) .with_level(true) .with_writer(io::stderr) .with_env_filter(filter) .without_time() .with_ansi(colors_enabled) .init(); }