1#![recursion_limit = "512"]2#![feature(try_blocks)]34pub(crate) mod cmds;5pub(crate) mod command;6pub(crate) mod host;7pub(crate) mod keys;89pub(crate) mod better_nix_eval;10pub(crate) mod extra_args;1112mod fleetdata;1314use std::{ffi::OsString, process::ExitCode};1516use anyhow::{bail, Result};17use clap::{CommandFactory, Parser};18use cmds::{19 build_systems::{BuildSystems, Deploy},20 complete::Complete,21 info::Info,22 secrets::Secret,23};24use futures::{future::LocalBoxFuture, stream::FuturesUnordered, TryStreamExt};25use host::{Config, FleetOpts};26#[cfg(feature = "indicatif")]27use human_repr::HumanCount;28#[cfg(feature = "indicatif")]29use indicatif::{ProgressState, ProgressStyle};30use tracing::{error, info, info_span, Instrument};31#[cfg(feature = "indicatif")]32use tracing_indicatif::IndicatifLayer;33use tracing_subscriber::{prelude::*, EnvFilter};3435use crate::command::MyCommand;3637#[derive(Parser)]38struct Prefetch {}39impl Prefetch {40 async fn run(&self, config: &Config) -> Result<()> {41 let mut prefetch_dir = config.directory.to_path_buf();42 prefetch_dir.push("prefetch");43 if !prefetch_dir.is_dir() {44 info!("nothing to prefetch: no prefetch directory");45 return Ok(());46 }47 let tasks = <FuturesUnordered<LocalBoxFuture<Result<()>>>>::new();48 for entry in std::fs::read_dir(&prefetch_dir)? {49 tasks.push(Box::pin(async {50 let entry = entry?;51 if !entry.metadata()?.is_file() {52 bail!("only files should exist in prefetch directory");53 }54 let span = info_span!(55 "prefetching",56 name = entry.file_name().to_string_lossy().as_ref()57 );58 let mut path = OsString::new();59 path.push("file://");60 path.push(entry.path());6162 let mut status = MyCommand::new("nix");63 status.args(&config.nix_args);64 status.arg("store").arg("prefetch-file").arg(path);65 status.run_nix_string().instrument(span).await?;66 Ok(())67 }));68 }69 tasks.try_collect::<Vec<()>>().await?;70 Ok(())71 }72}7374#[derive(Parser)]75enum Opts {76 77 BuildSystems(BuildSystems),7879 Deploy(Deploy),80 81 #[clap(subcommand)]82 Secret(Secret),83 84 Prefetch(Prefetch),85 86 Info(Info),87 88 #[clap(hide(true))]89 Complete(Complete),90}9192#[derive(Parser)]93#[clap(version, author)]94struct RootOpts {95 #[clap(flatten)]96 fleet_opts: FleetOpts,97 #[clap(subcommand)]98 command: Opts,99}100101async fn run_command(config: &Config, command: Opts) -> Result<()> {102 match command {103 Opts::BuildSystems(c) => c.run(config).await?,104 Opts::Deploy(d) => d.run(config).await?,105 Opts::Secret(s) => s.run(config).await?,106 Opts::Info(i) => i.run(config).await?,107 Opts::Prefetch(p) => p.run(config).await?,108 109 Opts::Complete(c) => {110 tokio::task::spawn_blocking(move || c.run(RootOpts::command())).await?111 }112 };113 Ok(())114}115116fn setup_logging() {117 #[cfg(feature = "indicatif")]118 let indicatif_layer = {119 use std::time::Duration;120121 IndicatifLayer::new().with_progress_style(122 ProgressStyle::with_template(123 "{color_start}{span_child_prefix} {span_name}{{{span_fields}}}{color_end} {wide_msg} {color_start}{download_progress} {elapsed}{color_end}",124 )125 .unwrap()126 .with_key("download_progress", |state: &ProgressState, writer: &mut dyn std::fmt::Write| {127 let Some(len) = state.len() else {128 return;129 };130 let pos = state.pos();131 if pos > len {132 let _ = write!(writer, "{}", pos.human_count_bare());133 } else {134 let _ = write!(writer, "{} / {}", pos.human_count_bare(), len.human_count_bare());135 }136 })137 .with_key(138 "color_start",139 |state: &ProgressState, writer: &mut dyn std::fmt::Write| {140 let elapsed = state.elapsed();141142 if elapsed > Duration::from_secs(60) {143 144 let _ = write!(writer, "\x1b[{}m", 1 + 30);145 } else if elapsed > Duration::from_secs(30) {146 147 let _ = write!(writer, "\x1b[{}m", 3 + 30);148 }149 },150 )151 .with_key(152 "color_end",153 |state: &ProgressState, writer: &mut dyn std::fmt::Write| {154 if state.elapsed() > Duration::from_secs(30) {155 let _ = write!(writer, "\x1b[0m");156 }157 },158 ),159 )160 };161162 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));163164 let reg = tracing_subscriber::registry().with({165 let sub = tracing_subscriber::fmt::layer()166 .without_time()167 .with_target(false);168 #[cfg(feature = "indicatif")]169 let sub = sub.with_writer(indicatif_layer.get_stdout_writer());170 sub.with_filter(filter) 171 });172 173 #[cfg(feature = "indicatif")]174 let reg = reg.with(indicatif_layer);175 reg.init();176}177178#[tokio::main]179async fn main() -> ExitCode {180 setup_logging();181 if let Err(e) = main_real().await {182 183 184 #[cfg(feature = "indicatif")]185 info!("fixme: this line gets eaten by tracing-indicatif on levels info+");186 error!("{e:#}");187 return ExitCode::FAILURE;188 }189 ExitCode::SUCCESS190}191192async fn main_real() -> Result<()> {193 nix_eval::init_tokio();194195 let nix_args = std::env::var_os("NIX_ARGS")196 .map(|a| extra_args::parse_os(&a))197 .transpose()?198 .unwrap_or_default();199 let opts = RootOpts::parse();200 let config = opts.fleet_opts.build(nix_args).await?;201202 match run_command(&config, opts.command).await {203 Ok(()) => {204 config.save()?;205 Ok(())206 }207 Err(e) => {208 let _ = config.save();209 Err(e)210 }211 }212}213214#[cfg(test)]215mod tests {216 use super::*;217218 #[test]219 fn verify_command() {220 use clap::CommandFactory;221 RootOpts::command().debug_assert();222 }223}