From 7db9d3a2e1a049409afaa8dc1c67367dfb75504b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christina=20S=C3=B8rensen?= Date: Fri, 6 Sep 2024 11:26:56 +0200 Subject: [PATCH] style(rust): format to `tabwidth-2` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix: #22 Signed-off-by: Christina Sørensen --- crates/nix-weather/build.rs | 38 +++---- crates/nix-weather/src/cli.rs | 48 ++++----- crates/nix-weather/src/main.rs | 190 ++++++++++++++++----------------- crates/nix-weather/src/net.rs | 44 ++++---- crates/nix-weather/src/nix.rs | 84 +++++++-------- 5 files changed, 202 insertions(+), 202 deletions(-) diff --git a/crates/nix-weather/build.rs b/crates/nix-weather/build.rs index 460c33f..e86ad04 100644 --- a/crates/nix-weather/build.rs +++ b/crates/nix-weather/build.rs @@ -14,30 +14,30 @@ use std::path::PathBuf; include!("src/cli.rs"); fn main() -> Result<(), Error> { - let real_outdir = match env::var_os("OUT_DIR") { - None => return Ok(()), - Some(outdir) => outdir, - }; + let real_outdir = match env::var_os("OUT_DIR") { + None => return Ok(()), + Some(outdir) => outdir, + }; - let outdir = match env::var_os("MAN_OUT") { - None => real_outdir, - Some(outdir) => outdir, - }; + let outdir = match env::var_os("MAN_OUT") { + None => real_outdir, + Some(outdir) => outdir, + }; - let mut cmd = build_cli(); - for &shell in Shell::value_variants() { - // HACK: this is gross :( - let output = std::process::Command::new("mkdir").arg("man").output(); + let mut cmd = build_cli(); + for &shell in Shell::value_variants() { + // HACK: this is gross :( + let output = std::process::Command::new("mkdir").arg("man").output(); - generate_to(shell, &mut cmd, "nix-weather", &outdir)?; - } + generate_to(shell, &mut cmd, "nix-weather", &outdir)?; + } - let file = PathBuf::from(&outdir).join("nix-weather.1"); - let mut file = File::create(file)?; + let file = PathBuf::from(&outdir).join("nix-weather.1"); + let mut file = File::create(file)?; - Man::new(cmd).render(&mut file)?; + Man::new(cmd).render(&mut file)?; - println!("cargo:warning=completion file is generated: {outdir:?}"); + println!("cargo:warning=completion file is generated: {outdir:?}"); - Ok(()) + Ok(()) } diff --git a/crates/nix-weather/src/cli.rs b/crates/nix-weather/src/cli.rs index 038af7f..205d355 100644 --- a/crates/nix-weather/src/cli.rs +++ b/crates/nix-weather/src/cli.rs @@ -10,29 +10,29 @@ use clap::{arg, command, crate_authors, value_parser, Arg, ArgAction, Command}; const DEFAULT_CACHE: &str = "cache.nixos.org"; pub fn build_cli() -> Command { - use std::path::PathBuf; + use std::path::PathBuf; - command!() - .author(crate_authors!("\n")) - .arg( - arg!(--cache "check a specific cache") - .required(false) - .default_value(DEFAULT_CACHE), - ) - .arg( - arg!(-n --name "Hostname of machine.") - .required(false) - .value_parser(value_parser!(String)), - ) - .arg( - arg!(-c --config "Path to NixOS config.") - .required(false) - .value_parser(value_parser!(String)), - ) - .arg( - arg!(--timestamp "Add timestamp to log output.") - .action(ArgAction::SetTrue) - .required(false), - ) - .arg(arg!(-v --verbose ... "Verbosity level.")) + command!() + .author(crate_authors!("\n")) + .arg( + arg!(--cache "check a specific cache") + .required(false) + .default_value(DEFAULT_CACHE), + ) + .arg( + arg!(-n --name "Hostname of machine.") + .required(false) + .value_parser(value_parser!(String)), + ) + .arg( + arg!(-c --config "Path to NixOS config.") + .required(false) + .value_parser(value_parser!(String)), + ) + .arg( + arg!(--timestamp "Add timestamp to log output.") + .action(ArgAction::SetTrue) + .required(false), + ) + .arg(arg!(-v --verbose ... "Verbosity level.")) } diff --git a/crates/nix-weather/src/main.rs b/crates/nix-weather/src/main.rs index d394f7f..cce531c 100644 --- a/crates/nix-weather/src/main.rs +++ b/crates/nix-weather/src/main.rs @@ -27,123 +27,123 @@ const DEFAULT_CONFIG_DIR: &str = "/etc/nixos"; #[tokio::main(flavor = "multi_thread")] async fn main() -> io::Result<()> { - let initial_time = Instant::now(); + let initial_time = Instant::now(); - let host_name: String; - let cache_url: String; - let config_dir: String; + let host_name: String; + let cache_url: String; + let config_dir: String; - let matches = cli::build_cli().get_matches(); + let matches = cli::build_cli().get_matches(); - /// If the users inputs more -v flags than we have log levels, send them a - /// message informing them. - let mut very_bose = false; + /// If the users inputs more -v flags than we have log levels, send them a + /// message informing them. + let mut very_bose = false; - match matches - .get_one::("verbose") - .expect("Counts aren't defaulted") - { - 0 => env::set_var("RUST_LOG", "error"), - 1 => env::set_var("RUST_LOG", "warn"), - 2 => env::set_var("RUST_LOG", "info"), - 3 => env::set_var("RUST_LOG", "debug"), - 4 => env::set_var("RUST_LOG", "trace"), - _ => { - very_bose = true; - env::set_var("RUST_LOG", "trace") - } + match matches + .get_one::("verbose") + .expect("Counts aren't defaulted") + { + 0 => env::set_var("RUST_LOG", "error"), + 1 => env::set_var("RUST_LOG", "warn"), + 2 => env::set_var("RUST_LOG", "info"), + 3 => env::set_var("RUST_LOG", "debug"), + 4 => env::set_var("RUST_LOG", "trace"), + _ => { + very_bose = true; + env::set_var("RUST_LOG", "trace") } + } - if matches.get_flag("timestamp") { - pretty_env_logger::formatted_timed_builder() - .parse_env("RUST_LOG") - .init(); - } else { - pretty_env_logger::formatted_builder() - .parse_env("RUST_LOG") - .init(); - } + if matches.get_flag("timestamp") { + pretty_env_logger::formatted_timed_builder() + .parse_env("RUST_LOG") + .init(); + } else { + pretty_env_logger::formatted_builder() + .parse_env("RUST_LOG") + .init(); + } - if very_bose { - log::trace!("More than four -v flags don't increase log level."); - } + if very_bose { + log::trace!("More than four -v flags don't increase log level."); + } - if let Some(name) = matches.get_one::("name") { - host_name = name.to_owned(); - } else { - host_name = gethostname().into_string().unwrap(); - } + if let Some(name) = matches.get_one::("name") { + host_name = name.to_owned(); + } else { + host_name = gethostname().into_string().unwrap(); + } - if let Some(cache) = matches.get_one::("cache") { - cache_url = cache.to_owned(); - } else { - cache_url = DEFAULT_CACHE.to_string(); - } + if let Some(cache) = matches.get_one::("cache") { + cache_url = cache.to_owned(); + } else { + cache_url = DEFAULT_CACHE.to_string(); + } - if let Some(config) = matches.get_one::("config") { - config_dir = config.to_owned(); - } else { - config_dir = DEFAULT_CONFIG_DIR.to_string(); - } + if let Some(config) = matches.get_one::("config") { + config_dir = config.to_owned(); + } else { + config_dir = DEFAULT_CONFIG_DIR.to_string(); + } - let domain = cache_url.to_owned(); - let ips: Vec = lookup_host(&domain).unwrap(); + let domain = cache_url.to_owned(); + let ips: Vec = lookup_host(&domain).unwrap(); - log::debug!("{:#?}", &ips); + log::debug!("{:#?}", &ips); - let domain_addr = SocketAddr::new(ips[0], 443); + let domain_addr = SocketAddr::new(ips[0], 443); - let client = reqwest::Client::builder() - .resolve(&domain, domain_addr) - .build() - .unwrap(); + let client = reqwest::Client::builder() + .resolve(&domain, domain_addr) + .build() + .unwrap(); - let binding = get_requisites(&host_name, &config_dir); + let binding = get_requisites(&host_name, &config_dir); - let get_requisites_duration = initial_time.elapsed().as_secs(); + let get_requisites_duration = initial_time.elapsed().as_secs(); - println!( - "Found Nix Requisites in {} seconds", - get_requisites_duration - ); + println!( + "Found Nix Requisites in {} seconds", + get_requisites_duration + ); - let network_time = Instant::now(); + let network_time = Instant::now(); - let lines = binding - .lines() - .map(|line| line.to_owned()) - .collect::>(); + let lines = binding + .lines() + .map(|line| line.to_owned()) + .collect::>(); - let count = lines.len(); + let count = lines.len(); - let tasks = lines - .into_iter() - .map(|hash| { - let client = client.clone(); - let domain = domain.clone(); - tokio::spawn(async move { - log::trace!("connecting to {domain} {domain_addr:#?} for {hash}"); - net::nar_exists(client, &domain, &hash, SLIDE).await - }) - }) - .collect_vec(); + let tasks = lines + .into_iter() + .map(|hash| { + let client = client.clone(); + let domain = domain.clone(); + tokio::spawn(async move { + log::trace!("connecting to {domain} {domain_addr:#?} for {hash}"); + net::nar_exists(client, &domain, &hash, SLIDE).await + }) + }) + .collect_vec(); - let sum: usize = join_all(tasks) - .await - .into_iter() - .map(|result| result.unwrap()) - .sum(); + let sum: usize = join_all(tasks) + .await + .into_iter() + .map(|result| result.unwrap()) + .sum(); - println!( - "Checked {count} packages in {} seconds", - network_time.elapsed().as_secs() - ); - println!( - "Found {:#?}/{} ({:.2}%) in cache", - sum, - count, - (sum as f64 / count as f64) * 100. - ); + println!( + "Checked {count} packages in {} seconds", + network_time.elapsed().as_secs() + ); + println!( + "Found {:#?}/{} ({:.2}%) in cache", + sum, + count, + (sum as f64 / count as f64) * 100. + ); - Ok(()) + Ok(()) } diff --git a/crates/nix-weather/src/net.rs b/crates/nix-weather/src/net.rs index 902e3b1..7ecc379 100644 --- a/crates/nix-weather/src/net.rs +++ b/crates/nix-weather/src/net.rs @@ -13,28 +13,28 @@ use log; const MAX_SLIDE: u64 = 1000; pub async fn nar_exists(client: Client, domain: &str, hash: &str, slide: u64) -> usize { - let response = client - .head(format!("https://{domain}/{hash}.narinfo")) - .send() - .await; + let response = client + .head(format!("https://{domain}/{hash}.narinfo")) + .send() + .await; - match response { - Ok(response) if response.status().as_u16() == 200 => 1, - Ok(response) if response.status().as_u16() == 404 => 0, - _ => { - // We're so fast now we get rate limited. - // - // Writng an actual sliding window seems kinda hard, - // so we do this instead. - log::trace!("rate limited! {slide}"); - sleep(Duration::from_millis(slide)).await; - Box::pin(nar_exists( - client, - domain, - hash, - std::cmp::min(slide * 2, MAX_SLIDE), - )) - .await - } + match response { + Ok(response) if response.status().as_u16() == 200 => 1, + Ok(response) if response.status().as_u16() == 404 => 0, + _ => { + // We're so fast now we get rate limited. + // + // Writng an actual sliding window seems kinda hard, + // so we do this instead. + log::trace!("rate limited! {slide}"); + sleep(Duration::from_millis(slide)).await; + Box::pin(nar_exists( + client, + domain, + hash, + std::cmp::min(slide * 2, MAX_SLIDE), + )) + .await } + } } diff --git a/crates/nix-weather/src/nix.rs b/crates/nix-weather/src/nix.rs index ab17408..783327b 100644 --- a/crates/nix-weather/src/nix.rs +++ b/crates/nix-weather/src/nix.rs @@ -5,53 +5,53 @@ use serde_json::Value; use std::{ - path::Path, - process::{Command, Stdio}, + path::Path, + process::{Command, Stdio}, }; pub fn get_requisites(host: &str, config_dir: &str) -> String { - let get_drv_path = Command::new("nix") - .current_dir(Path::new(config_dir)) - .args([ - "build", - "--impure", - "--quiet", - &format!( - "./#nixosConfigurations.{}.config.system.build.toplevel", - host - ), - "--dry-run", - "--json", - "--option", - "eval-cache", - "true", - ]) - .output() - .unwrap(); + let get_drv_path = Command::new("nix") + .current_dir(Path::new(config_dir)) + .args([ + "build", + "--impure", + "--quiet", + &format!( + "./#nixosConfigurations.{}.config.system.build.toplevel", + host + ), + "--dry-run", + "--json", + "--option", + "eval-cache", + "true", + ]) + .output() + .unwrap(); - let drv_path_json: Value = - serde_json::from_str(&String::from_utf8(get_drv_path.stdout).unwrap()).unwrap(); - let drv_path = drv_path_json[0]["drvPath"].clone(); + let drv_path_json: Value = + serde_json::from_str(&String::from_utf8(get_drv_path.stdout).unwrap()).unwrap(); + let drv_path = drv_path_json[0]["drvPath"].clone(); - log::debug!("drv_path: {}", &drv_path); + log::debug!("drv_path: {}", &drv_path); - let get_drv_requisites = Command::new("nix-store") - .args(["--query", "--requisites", drv_path.as_str().unwrap()]) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let drv_requisites_remove_base = Command::new("cut") - .args(["-d", "/", "-f4"]) - .stdin(Stdio::from(get_drv_requisites.stdout.unwrap())) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let drv_requisites_to_hash = Command::new("cut") - .args(["-d", "-", "-f1"]) - .stdin(Stdio::from(drv_requisites_remove_base.stdout.unwrap())) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); + let get_drv_requisites = Command::new("nix-store") + .args(["--query", "--requisites", drv_path.as_str().unwrap()]) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let drv_requisites_remove_base = Command::new("cut") + .args(["-d", "/", "-f4"]) + .stdin(Stdio::from(get_drv_requisites.stdout.unwrap())) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let drv_requisites_to_hash = Command::new("cut") + .args(["-d", "-", "-f1"]) + .stdin(Stdio::from(drv_requisites_remove_base.stdout.unwrap())) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); - String::from_utf8(drv_requisites_to_hash.wait_with_output().unwrap().stdout).unwrap() + String::from_utf8(drv_requisites_to_hash.wait_with_output().unwrap().stdout).unwrap() }