Something went wrong. Try again.
forked from zhaofengli/colmena
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390//! 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 <hello@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 /// <https://bixense.com/clicolors>. #[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<String>,
/// 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<String>,}
#[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<Hive> { 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();}