git.delta.rocks / jrsonnet / refs/commits / aac7f3854e2a

difftreelog

fix(fleet-cmd) include the required package for tab completions (#5)

Petr Portnov | PROgrm_JARvis2024-06-02parent: #ad7852d.patch.diff
in: trunk
* fix(fleet-cmd): include the required package for tab completions

* style(fleet-cmd): reformat automatically

9 files changed

modifiedcmds/fleet/src/better_nix_eval.rsdiffbeforeafterboth
--- a/cmds/fleet/src/better_nix_eval.rs
+++ b/cmds/fleet/src/better_nix_eval.rs
@@ -1,25 +1,24 @@
 //! Wrapper around nix repl, which allows to work on nix code, without relying on
 //! nix libexpr. I mean, nix libexpr is good, but until it has no C bindings, this is the royal PITA.
 
-use std::collections::HashMap;
-use std::ffi::{OsStr, OsString};
-use std::fmt::{self, Display};
-use std::path::PathBuf;
-use std::process::Stdio;
-use std::sync::{Arc, OnceLock};
+use std::{
+	collections::HashMap,
+	ffi::{OsStr, OsString},
+	fmt::{self, Display},
+	path::PathBuf,
+	process::Stdio,
+	sync::{Arc, OnceLock},
+};
 
 use anyhow::{anyhow, bail, ensure, Context, Result};
 use better_command::{ClonableHandler, Handler, NixHandler, NoopHandler};
 use futures::StreamExt;
 use itertools::Itertools;
-use serde::de::DeserializeOwned;
-use serde::{Deserialize, Serialize};
-use tokio::io::AsyncWriteExt;
-use tokio::process::{ChildStderr, ChildStdin, ChildStdout, Command};
-use tokio::select;
-use tokio::sync::{mpsc, oneshot, Mutex};
+use serde::{de::DeserializeOwned, Deserialize, Serialize};
+use tokio::{
+	io::AsyncWriteExt,
+	process::{ChildStderr, ChildStdin, ChildStdout, Command},
+	select,
+	sync::{mpsc, oneshot, Mutex},
+};
 use tracing::{debug, error, warn, Level};
-
-
-
-
modifiedcmds/fleet/src/cmds/build_systems.rsdiffbeforeafterboth
--- a/cmds/fleet/src/cmds/build_systems.rs
+++ b/cmds/fleet/src/cmds/build_systems.rs
@@ -1,9 +1,5 @@
-use std::os::unix::fs::symlink;
-use std::path::PathBuf;
-use std::{env::current_dir, time::Duration};
+use std::{env::current_dir, os::unix::fs::symlink, path::PathBuf, time::Duration};
 
-use crate::command::MyCommand;
-use crate::host::{Config, ConfigHost};
 use anyhow::{anyhow, Result};
 use clap::{Parser, ValueEnum};
 use itertools::Itertools as _;
@@ -11,6 +7,11 @@
 use tokio::{task::LocalSet, time::sleep};
 use tracing::{error, field, info, info_span, warn, Instrument};
 
+use crate::{
+	command::MyCommand,
+	host::{Config, ConfigHost},
+};
+
 #[derive(Parser)]
 pub struct Deploy {
 	/// Disable automatic rollback
modifiedcmds/fleet/src/cmds/info.rsdiffbeforeafterboth
--- a/cmds/fleet/src/cmds/info.rs
+++ b/cmds/fleet/src/cmds/info.rs
@@ -1,10 +1,11 @@
 use std::collections::BTreeSet;
 
-use crate::host::Config;
 use anyhow::{ensure, Result};
 use clap::Parser;
 use nix_eval::nix_go_json;
 
+use crate::host::Config;
+
 #[derive(Parser)]
 pub struct Info {
 	#[clap(long)]
modifiedcmds/fleet/src/cmds/mod.rsdiffbeforeafterboth
--- a/cmds/fleet/src/cmds/mod.rs
+++ b/cmds/fleet/src/cmds/mod.rs
@@ -1,4 +1,4 @@
 pub mod build_systems;
+pub mod complete;
 pub mod info;
 pub mod secrets;
-pub mod complete;
modifiedcmds/fleet/src/extra_args.rsdiffbeforeafterboth
--- a/cmds/fleet/src/extra_args.rs
+++ b/cmds/fleet/src/extra_args.rs
@@ -1,7 +1,7 @@
-use anyhow::anyhow;
-use anyhow::Result;
 use std::ffi::{OsStr, OsString};
 
+use anyhow::{anyhow, Result};
+
 pub fn parse_os(os: &OsStr) -> Result<Vec<OsString>> {
 	Ok(shlex::bytes::split(os.as_encoded_bytes())
 		.ok_or_else(|| anyhow!("invalid arguments"))?
modifiedcmds/fleet/src/keys.rsdiffbeforeafterboth
--- a/cmds/fleet/src/keys.rs
+++ b/cmds/fleet/src/keys.rs
@@ -1,12 +1,13 @@
 use std::str::FromStr;
 
-use crate::host::Config;
 use age::Recipient;
 use anyhow::{anyhow, Result};
 use futures::{StreamExt, TryStreamExt};
 use itertools::Itertools;
 use tracing::warn;
 
+use crate::host::Config;
+
 impl Config {
 	pub fn cached_key(&self, host: &str) -> Option<String> {
 		let data = self.data();
modifiedcmds/fleet/src/main.rsdiffbeforeafterboth
before · cmds/fleet/src/main.rs
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	/// Prepare systems for deployments77	BuildSystems(BuildSystems),7879	Deploy(Deploy),80	/// Secret management81	#[clap(subcommand)]82	Secret(Secret),83	/// Upload prefetch directory to the nix store84	Prefetch(Prefetch),85	/// Config parsing86	Info(Info),87	/// Command completions88	#[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		// TODO: actually parse commands before starting the async runtime109		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							// Red144							let _ = write!(writer, "\x1b[{}m", 1 + 30);145						} else if elapsed > Duration::from_secs(30) {146							// Yellow147							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) // .without,171	});172	// #[cfg(feature = "indicatif")]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		// If I remove this line, the next error!() line gets eaten.183		// This is a bug in indicatif, it needs to be fixed184		#[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}
after · cmds/fleet/src/main.rs
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	/// Prepare systems for deployments77	BuildSystems(BuildSystems),7879	Deploy(Deploy),80	/// Secret management81	#[clap(subcommand)]82	Secret(Secret),83	/// Upload prefetch directory to the nix store84	Prefetch(Prefetch),85	/// Config parsing86	Info(Info),87	/// Command completions88	#[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		// TODO: actually parse commands before starting the async runtime109		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							// Red144							let _ = write!(writer, "\x1b[{}m", 1 + 30);145						} else if elapsed > Duration::from_secs(30) {146							// Yellow147							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) // .without,171	});172	// #[cfg(feature = "indicatif")]173	#[cfg(feature = "indicatif")]174	let reg = reg.with(indicatif_layer);175	reg.init();176}177178fn main() -> ExitCode {179	let opts = RootOpts::parse();180	if let Opts::Complete(c) = &opts.command {181		c.run(RootOpts::command());182		return ExitCode::SUCCESS;183	}184185	setup_logging();186	async_main(opts)187}188189#[tokio::main]190async fn async_main(opts: RootOpts) -> ExitCode {191	if let Err(e) = main_real(opts).await {192		// If I remove this line, the next error!() line gets eaten.193		// This is a bug in indicatif, it needs to be fixed194		#[cfg(feature = "indicatif")]195		info!("fixme: this line gets eaten by tracing-indicatif on levels info+");196		error!("{e:#}");197		return ExitCode::FAILURE;198	}199	ExitCode::SUCCESS200}201202async fn main_real(opts: RootOpts) -> Result<()> {203	nix_eval::init_tokio();204205	let nix_args = std::env::var_os("NIX_ARGS")206		.map(|a| extra_args::parse_os(&a))207		.transpose()?208		.unwrap_or_default();209	let config = opts.fleet_opts.build(nix_args).await?;210211	match run_command(&config, opts.command).await {212		Ok(()) => {213			config.save()?;214			Ok(())215		}216		Err(e) => {217			let _ = config.save();218			Err(e)219		}220	}221}222223#[cfg(test)]224mod tests {225	use super::*;226227	#[test]228	fn verify_command() {229		use clap::CommandFactory;230		RootOpts::command().debug_assert();231	}232}
modifiedflake.lockdiffbeforeafterboth
--- a/flake.lock
+++ b/flake.lock
@@ -7,11 +7,11 @@
         ]
       },
       "locked": {
-        "lastModified": 1717025063,
-        "narHash": "sha256-dIubLa56W9sNNz0e8jGxrX3CAkPXsq7snuFA/Ie6dn8=",
+        "lastModified": 1717290123,
+        "narHash": "sha256-K8O2KQEbA+NIAc8BDsWV6QKqU3i9M+YTUi4zzmLRy1s=",
         "owner": "ipetkov",
         "repo": "crane",
-        "rev": "480dff0be03dac0e51a8dfc26e882b0d123a450e",
+        "rev": "ae1453ffd0f8f684e863685c317a953317db2b79",
         "type": "github"
       },
       "original": {
@@ -40,11 +40,11 @@
     },
     "nixpkgs": {
       "locked": {
-        "lastModified": 1717282945,
-        "narHash": "sha256-Jrn+/CdB/d2hUqduYQdTwGJYDAdaR5cAdlxnq+yEtXI=",
+        "lastModified": 1717336170,
+        "narHash": "sha256-hkD00+n53WNZ4k8hqIbekl5WGDsmb5urhAuDh5XYjyc=",
         "owner": "nixos",
         "repo": "nixpkgs",
-        "rev": "ab5efd0f3c62dd3b75d21d0de1dd63efc76be5d8",
+        "rev": "73bff846b4e8d0c8156c6fc726bf623fe3f3845c",
         "type": "github"
       },
       "original": {
@@ -56,11 +56,11 @@
     },
     "nixpkgs-stable-for-tests": {
       "locked": {
-        "lastModified": 1716991068,
-        "narHash": "sha256-Av0UWCCiIGJxsZ6TFc+OiKCJNqwoxMNVYDBChmhjNpo=",
+        "lastModified": 1717159533,
+        "narHash": "sha256-oamiKNfr2MS6yH64rUn99mIZjc45nGJlj9eGth/3Xuw=",
         "owner": "nixos",
         "repo": "nixpkgs",
-        "rev": "25cf937a30bf0801447f6bf544fc7486c6309234",
+        "rev": "a62e6edd6d5e1fa0329b8653c801147986f8d446",
         "type": "github"
       },
       "original": {
@@ -89,11 +89,11 @@
         ]
       },
       "locked": {
-        "lastModified": 1717208326,
-        "narHash": "sha256-4gVhbC+NjSQ4c6cJvJGNCI1oTcD+8jRRNAnOF9faGCE=",
+        "lastModified": 1717294752,
+        "narHash": "sha256-QhlS52cEQyx+iVcgrEoCnEEpWUA6uLdmeLRxk935inI=",
         "owner": "oxalica",
         "repo": "rust-overlay",
-        "rev": "ab69b67fac9a96709fbef0b899db308ca714a120",
+        "rev": "b46857a406d207a1de74e792ef3b83e800c30e08",
         "type": "github"
       },
       "original": {
modifiedpkgs/fleet.nixdiffbeforeafterboth
--- a/pkgs/fleet.nix
+++ b/pkgs/fleet.nix
@@ -1,4 +1,7 @@
-{craneLib}:
+{
+  craneLib,
+  installShellFiles,
+}:
 craneLib.buildPackage rec {
   pname = "fleet";
 
@@ -7,10 +10,12 @@
 
   cargoExtraArgs = "--locked -p ${pname}";
 
+  nativeBuildInputs = [installShellFiles];
+
   postInstall = ''
     for shell in bash fish zsh; do
       installShellCompletion --cmd fleet \
-        --$shell <($out/bin/fleet complete --shell $shell --print)
+        --$shell <($out/bin/fleet complete --shell $shell)
     done
   '';
 }