1#![recursion_limit = "512"]2#![feature(try_blocks)]34pub(crate) mod cmds;56pub(crate) mod extra_args;78use std::{ffi::OsString, process::ExitCode};910use anyhow::{bail, Result};11use clap::{CommandFactory, Parser};12use cmds::{13 build_systems::{BuildSystems, Deploy},14 complete::Complete,15 info::Info,16 secrets::Secret,17 tf::Tf,18};19use fleet_base::{host::Config, opts::FleetOpts};20use futures::{future::LocalBoxFuture, stream::FuturesUnordered, TryStreamExt};2122#[cfg(feature = "indicatif")]23use human_repr::HumanCount;24#[cfg(feature = "indicatif")]25use indicatif::{ProgressState, ProgressStyle};26use tracing::{error, info, info_span, Instrument};27#[cfg(feature = "indicatif")]28use tracing_indicatif::IndicatifLayer;29use tracing_subscriber::{prelude::*, EnvFilter};3031#[derive(Parser)]32struct Prefetch {}33impl Prefetch {34 async fn run(&self, config: &Config) -> Result<()> {35 let mut prefetch_dir = config.directory.to_path_buf();36 prefetch_dir.push("prefetch");37 if !prefetch_dir.is_dir() {38 info!("nothing to prefetch: no prefetch directory");39 return Ok(());40 }41 let tasks = <FuturesUnordered<LocalBoxFuture<Result<()>>>>::new();42 for entry in std::fs::read_dir(&prefetch_dir)? {43 tasks.push(Box::pin(async {44 let entry = entry?;45 if !entry.metadata()?.is_file() {46 bail!("only files should exist in prefetch directory");47 }48 let span = info_span!(49 "prefetching",50 name = entry.file_name().to_string_lossy().as_ref()51 );52 let mut path = OsString::new();53 path.push("file://");54 path.push(entry.path());5556 let mut status = config.local_host().cmd("nix").await?;57 status.args(&config.nix_args);58 status.arg("store").arg("prefetch-file").arg(path);59 status.run_nix_string().instrument(span).await?;60 Ok(())61 }));62 }63 tasks.try_collect::<Vec<()>>().await?;64 Ok(())65 }66}6768#[derive(Parser)]69enum Opts {70 71 BuildSystems(BuildSystems),7273 Deploy(Deploy),74 75 #[clap(subcommand)]76 Secret(Secret),77 78 Prefetch(Prefetch),79 80 Info(Info),81 82 #[clap(hide(true))]83 Complete(Complete),84 85 #[clap(subcommand)]86 Tf(Tf),87}8889#[derive(Parser)]90#[clap(version, author)]91struct RootOpts {92 #[clap(flatten)]93 fleet_opts: FleetOpts,94 #[clap(subcommand)]95 command: Opts,96}9798async fn run_command(config: &Config, opts: FleetOpts, command: Opts) -> Result<()> {99 match command {100 Opts::BuildSystems(c) => c.run(config, &opts).await?,101 Opts::Deploy(d) => d.run(config, &opts).await?,102 Opts::Secret(s) => s.run(config, &opts).await?,103 Opts::Info(i) => i.run(config).await?,104 Opts::Prefetch(p) => p.run(config).await?,105 Opts::Tf(t) => t.run(config).await?,106 107 Opts::Complete(c) => {108 tokio::task::spawn_blocking(move || c.run(RootOpts::command())).await?109 }110 };111 Ok(())112}113114fn setup_logging() {115 #[cfg(feature = "indicatif")]116 let indicatif_layer = {117 use std::time::Duration;118119 IndicatifLayer::new().with_progress_style(120 ProgressStyle::with_template(121 "{color_start}{span_child_prefix} {span_name}{{{span_fields}}}{color_end} {wide_msg} {color_start}{download_progress} {elapsed}{color_end}",122 )123 .unwrap()124 .with_key("download_progress", |state: &ProgressState, writer: &mut dyn std::fmt::Write| {125 let Some(len) = state.len() else {126 return;127 };128 let pos = state.pos();129 if pos > len {130 let _ = write!(writer, "{}", pos.human_count_bare());131 } else {132 let _ = write!(writer, "{} / {}", pos.human_count_bare(), len.human_count_bare());133 }134 })135 .with_key(136 "color_start",137 |state: &ProgressState, writer: &mut dyn std::fmt::Write| {138 let elapsed = state.elapsed();139140 if elapsed > Duration::from_secs(60) {141 142 let _ = write!(writer, "\x1b[{}m", 1 + 30);143 } else if elapsed > Duration::from_secs(30) {144 145 let _ = write!(writer, "\x1b[{}m", 3 + 30);146 }147 },148 )149 .with_key(150 "color_end",151 |state: &ProgressState, writer: &mut dyn std::fmt::Write| {152 if state.elapsed() > Duration::from_secs(30) {153 let _ = write!(writer, "\x1b[0m");154 }155 },156 ),157 )158 };159160 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));161162 let reg = tracing_subscriber::registry().with({163 let sub = tracing_subscriber::fmt::layer()164 .without_time()165 .with_target(false);166 #[cfg(feature = "indicatif")]167 let sub = sub.with_writer(indicatif_layer.get_stdout_writer());168 sub.with_filter(filter) 169 });170 171 #[cfg(feature = "indicatif")]172 let reg = reg.with(indicatif_layer);173 reg.init();174}175176fn main() -> ExitCode {177 let opts = RootOpts::parse();178 if let Opts::Complete(c) = &opts.command {179 c.run(RootOpts::command());180 return ExitCode::SUCCESS;181 }182183 setup_logging();184 async_main(opts)185}186187#[tokio::main]188async fn async_main(opts: RootOpts) -> ExitCode {189 if let Err(e) = main_real(opts).await {190 191 192 #[cfg(feature = "indicatif")]193 info!("fixme: this line gets eaten by tracing-indicatif on levels info+");194 error!("{e:#}");195 return ExitCode::FAILURE;196 }197 ExitCode::SUCCESS198}199200async fn main_real(opts: RootOpts) -> Result<()> {201 nix_eval::init_tokio();202203 let nix_args = std::env::var_os("NIX_ARGS")204 .map(|a| extra_args::parse_os(&a))205 .transpose()?206 .unwrap_or_default();207 let config = opts.fleet_opts.build(nix_args).await?;208209 match run_command(&config, opts.fleet_opts, opts.command).await {210 Ok(()) => {211 config.save()?;212 Ok(())213 }214 Err(e) => {215 let _ = config.save();216 Err(e)217 }218 }219}220221#[cfg(test)]222mod tests {223 use super::*;224225 #[test]226 fn verify_command() {227 use clap::CommandFactory;228 RootOpts::command().debug_assert();229 }230}