style(rust): format to tabwidth-2

Fix: #22
Signed-off-by: Christina Sørensen <christina@cafkafk.com>
This commit is contained in:
Christina Sørensen 2024-09-06 11:26:56 +02:00
parent c7f6b2c256
commit 7db9d3a2e1
Signed by: cafkafk
GPG key ID: 26C542FD97F965CE
5 changed files with 202 additions and 202 deletions

View file

@ -14,30 +14,30 @@ use std::path::PathBuf;
include!("src/cli.rs"); include!("src/cli.rs");
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let real_outdir = match env::var_os("OUT_DIR") { let real_outdir = match env::var_os("OUT_DIR") {
None => return Ok(()), None => return Ok(()),
Some(outdir) => outdir, Some(outdir) => outdir,
}; };
let outdir = match env::var_os("MAN_OUT") { let outdir = match env::var_os("MAN_OUT") {
None => real_outdir, None => real_outdir,
Some(outdir) => outdir, Some(outdir) => outdir,
}; };
let mut cmd = build_cli(); let mut cmd = build_cli();
for &shell in Shell::value_variants() { for &shell in Shell::value_variants() {
// HACK: this is gross :( // HACK: this is gross :(
let output = std::process::Command::new("mkdir").arg("man").output(); 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 file = PathBuf::from(&outdir).join("nix-weather.1");
let mut file = File::create(file)?; 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(())
} }

View file

@ -10,29 +10,29 @@ use clap::{arg, command, crate_authors, value_parser, Arg, ArgAction, Command};
const DEFAULT_CACHE: &str = "cache.nixos.org"; const DEFAULT_CACHE: &str = "cache.nixos.org";
pub fn build_cli() -> Command { pub fn build_cli() -> Command {
use std::path::PathBuf; use std::path::PathBuf;
command!() command!()
.author(crate_authors!("\n")) .author(crate_authors!("\n"))
.arg( .arg(
arg!(--cache <CACHE> "check a specific cache") arg!(--cache <CACHE> "check a specific cache")
.required(false) .required(false)
.default_value(DEFAULT_CACHE), .default_value(DEFAULT_CACHE),
) )
.arg( .arg(
arg!(-n --name <HOST> "Hostname of machine.") arg!(-n --name <HOST> "Hostname of machine.")
.required(false) .required(false)
.value_parser(value_parser!(String)), .value_parser(value_parser!(String)),
) )
.arg( .arg(
arg!(-c --config <FILE> "Path to NixOS config.") arg!(-c --config <FILE> "Path to NixOS config.")
.required(false) .required(false)
.value_parser(value_parser!(String)), .value_parser(value_parser!(String)),
) )
.arg( .arg(
arg!(--timestamp "Add timestamp to log output.") arg!(--timestamp "Add timestamp to log output.")
.action(ArgAction::SetTrue) .action(ArgAction::SetTrue)
.required(false), .required(false),
) )
.arg(arg!(-v --verbose ... "Verbosity level.")) .arg(arg!(-v --verbose ... "Verbosity level."))
} }

View file

@ -27,123 +27,123 @@ const DEFAULT_CONFIG_DIR: &str = "/etc/nixos";
#[tokio::main(flavor = "multi_thread")] #[tokio::main(flavor = "multi_thread")]
async fn main() -> io::Result<()> { async fn main() -> io::Result<()> {
let initial_time = Instant::now(); let initial_time = Instant::now();
let host_name: String; let host_name: String;
let cache_url: String; let cache_url: String;
let config_dir: 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 /// If the users inputs more -v flags than we have log levels, send them a
/// message informing them. /// message informing them.
let mut very_bose = false; let mut very_bose = false;
match matches match matches
.get_one::<u8>("verbose") .get_one::<u8>("verbose")
.expect("Counts aren't defaulted") .expect("Counts aren't defaulted")
{ {
0 => env::set_var("RUST_LOG", "error"), 0 => env::set_var("RUST_LOG", "error"),
1 => env::set_var("RUST_LOG", "warn"), 1 => env::set_var("RUST_LOG", "warn"),
2 => env::set_var("RUST_LOG", "info"), 2 => env::set_var("RUST_LOG", "info"),
3 => env::set_var("RUST_LOG", "debug"), 3 => env::set_var("RUST_LOG", "debug"),
4 => env::set_var("RUST_LOG", "trace"), 4 => env::set_var("RUST_LOG", "trace"),
_ => { _ => {
very_bose = true; very_bose = true;
env::set_var("RUST_LOG", "trace") env::set_var("RUST_LOG", "trace")
}
} }
}
if matches.get_flag("timestamp") { if matches.get_flag("timestamp") {
pretty_env_logger::formatted_timed_builder() pretty_env_logger::formatted_timed_builder()
.parse_env("RUST_LOG") .parse_env("RUST_LOG")
.init(); .init();
} else { } else {
pretty_env_logger::formatted_builder() pretty_env_logger::formatted_builder()
.parse_env("RUST_LOG") .parse_env("RUST_LOG")
.init(); .init();
} }
if very_bose { if very_bose {
log::trace!("More than four -v flags don't increase log level."); log::trace!("More than four -v flags don't increase log level.");
} }
if let Some(name) = matches.get_one::<String>("name") { if let Some(name) = matches.get_one::<String>("name") {
host_name = name.to_owned(); host_name = name.to_owned();
} else { } else {
host_name = gethostname().into_string().unwrap(); host_name = gethostname().into_string().unwrap();
} }
if let Some(cache) = matches.get_one::<String>("cache") { if let Some(cache) = matches.get_one::<String>("cache") {
cache_url = cache.to_owned(); cache_url = cache.to_owned();
} else { } else {
cache_url = DEFAULT_CACHE.to_string(); cache_url = DEFAULT_CACHE.to_string();
} }
if let Some(config) = matches.get_one::<String>("config") { if let Some(config) = matches.get_one::<String>("config") {
config_dir = config.to_owned(); config_dir = config.to_owned();
} else { } else {
config_dir = DEFAULT_CONFIG_DIR.to_string(); config_dir = DEFAULT_CONFIG_DIR.to_string();
} }
let domain = cache_url.to_owned(); let domain = cache_url.to_owned();
let ips: Vec<std::net::IpAddr> = lookup_host(&domain).unwrap(); let ips: Vec<std::net::IpAddr> = 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() let client = reqwest::Client::builder()
.resolve(&domain, domain_addr) .resolve(&domain, domain_addr)
.build() .build()
.unwrap(); .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!( println!(
"Found Nix Requisites in {} seconds", "Found Nix Requisites in {} seconds",
get_requisites_duration get_requisites_duration
); );
let network_time = Instant::now(); let network_time = Instant::now();
let lines = binding let lines = binding
.lines() .lines()
.map(|line| line.to_owned()) .map(|line| line.to_owned())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let count = lines.len(); let count = lines.len();
let tasks = lines let tasks = lines
.into_iter() .into_iter()
.map(|hash| { .map(|hash| {
let client = client.clone(); let client = client.clone();
let domain = domain.clone(); let domain = domain.clone();
tokio::spawn(async move { tokio::spawn(async move {
log::trace!("connecting to {domain} {domain_addr:#?} for {hash}"); log::trace!("connecting to {domain} {domain_addr:#?} for {hash}");
net::nar_exists(client, &domain, &hash, SLIDE).await net::nar_exists(client, &domain, &hash, SLIDE).await
}) })
}) })
.collect_vec(); .collect_vec();
let sum: usize = join_all(tasks) let sum: usize = join_all(tasks)
.await .await
.into_iter() .into_iter()
.map(|result| result.unwrap()) .map(|result| result.unwrap())
.sum(); .sum();
println!( println!(
"Checked {count} packages in {} seconds", "Checked {count} packages in {} seconds",
network_time.elapsed().as_secs() network_time.elapsed().as_secs()
); );
println!( println!(
"Found {:#?}/{} ({:.2}%) in cache", "Found {:#?}/{} ({:.2}%) in cache",
sum, sum,
count, count,
(sum as f64 / count as f64) * 100. (sum as f64 / count as f64) * 100.
); );
Ok(()) Ok(())
} }

View file

@ -13,28 +13,28 @@ use log;
const MAX_SLIDE: u64 = 1000; const MAX_SLIDE: u64 = 1000;
pub async fn nar_exists(client: Client, domain: &str, hash: &str, slide: u64) -> usize { pub async fn nar_exists(client: Client, domain: &str, hash: &str, slide: u64) -> usize {
let response = client let response = client
.head(format!("https://{domain}/{hash}.narinfo")) .head(format!("https://{domain}/{hash}.narinfo"))
.send() .send()
.await; .await;
match response { match response {
Ok(response) if response.status().as_u16() == 200 => 1, Ok(response) if response.status().as_u16() == 200 => 1,
Ok(response) if response.status().as_u16() == 404 => 0, Ok(response) if response.status().as_u16() == 404 => 0,
_ => { _ => {
// We're so fast now we get rate limited. // We're so fast now we get rate limited.
// //
// Writng an actual sliding window seems kinda hard, // Writng an actual sliding window seems kinda hard,
// so we do this instead. // so we do this instead.
log::trace!("rate limited! {slide}"); log::trace!("rate limited! {slide}");
sleep(Duration::from_millis(slide)).await; sleep(Duration::from_millis(slide)).await;
Box::pin(nar_exists( Box::pin(nar_exists(
client, client,
domain, domain,
hash, hash,
std::cmp::min(slide * 2, MAX_SLIDE), std::cmp::min(slide * 2, MAX_SLIDE),
)) ))
.await .await
}
} }
}
} }

View file

@ -5,53 +5,53 @@
use serde_json::Value; use serde_json::Value;
use std::{ use std::{
path::Path, path::Path,
process::{Command, Stdio}, process::{Command, Stdio},
}; };
pub fn get_requisites(host: &str, config_dir: &str) -> String { pub fn get_requisites(host: &str, config_dir: &str) -> String {
let get_drv_path = Command::new("nix") let get_drv_path = Command::new("nix")
.current_dir(Path::new(config_dir)) .current_dir(Path::new(config_dir))
.args([ .args([
"build", "build",
"--impure", "--impure",
"--quiet", "--quiet",
&format!( &format!(
"./#nixosConfigurations.{}.config.system.build.toplevel", "./#nixosConfigurations.{}.config.system.build.toplevel",
host host
), ),
"--dry-run", "--dry-run",
"--json", "--json",
"--option", "--option",
"eval-cache", "eval-cache",
"true", "true",
]) ])
.output() .output()
.unwrap(); .unwrap();
let drv_path_json: Value = let drv_path_json: Value =
serde_json::from_str(&String::from_utf8(get_drv_path.stdout).unwrap()).unwrap(); 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 = 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") let get_drv_requisites = Command::new("nix-store")
.args(["--query", "--requisites", drv_path.as_str().unwrap()]) .args(["--query", "--requisites", drv_path.as_str().unwrap()])
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.spawn() .spawn()
.unwrap(); .unwrap();
let drv_requisites_remove_base = Command::new("cut") let drv_requisites_remove_base = Command::new("cut")
.args(["-d", "/", "-f4"]) .args(["-d", "/", "-f4"])
.stdin(Stdio::from(get_drv_requisites.stdout.unwrap())) .stdin(Stdio::from(get_drv_requisites.stdout.unwrap()))
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.spawn() .spawn()
.unwrap(); .unwrap();
let drv_requisites_to_hash = Command::new("cut") let drv_requisites_to_hash = Command::new("cut")
.args(["-d", "-", "-f1"]) .args(["-d", "-", "-f1"])
.stdin(Stdio::from(drv_requisites_remove_base.stdout.unwrap())) .stdin(Stdio::from(drv_requisites_remove_base.stdout.unwrap()))
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.spawn() .spawn()
.unwrap(); .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()
} }