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");
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(())
}

View file

@ -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 <CACHE> "check a specific cache")
.required(false)
.default_value(DEFAULT_CACHE),
)
.arg(
arg!(-n --name <HOST> "Hostname of machine.")
.required(false)
.value_parser(value_parser!(String)),
)
.arg(
arg!(-c --config <FILE> "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 <CACHE> "check a specific cache")
.required(false)
.default_value(DEFAULT_CACHE),
)
.arg(
arg!(-n --name <HOST> "Hostname of machine.")
.required(false)
.value_parser(value_parser!(String)),
)
.arg(
arg!(-c --config <FILE> "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."))
}

View file

@ -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::<u8>("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::<u8>("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::<String>("name") {
host_name = name.to_owned();
} else {
host_name = gethostname().into_string().unwrap();
}
if let Some(name) = matches.get_one::<String>("name") {
host_name = name.to_owned();
} else {
host_name = gethostname().into_string().unwrap();
}
if let Some(cache) = matches.get_one::<String>("cache") {
cache_url = cache.to_owned();
} else {
cache_url = DEFAULT_CACHE.to_string();
}
if let Some(cache) = matches.get_one::<String>("cache") {
cache_url = cache.to_owned();
} else {
cache_url = DEFAULT_CACHE.to_string();
}
if let Some(config) = matches.get_one::<String>("config") {
config_dir = config.to_owned();
} else {
config_dir = DEFAULT_CONFIG_DIR.to_string();
}
if let Some(config) = matches.get_one::<String>("config") {
config_dir = config.to_owned();
} else {
config_dir = DEFAULT_CONFIG_DIR.to_string();
}
let domain = cache_url.to_owned();
let ips: Vec<std::net::IpAddr> = lookup_host(&domain).unwrap();
let domain = cache_url.to_owned();
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()
.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::<Vec<_>>();
let lines = binding
.lines()
.map(|line| line.to_owned())
.collect::<Vec<_>>();
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(())
}

View file

@ -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
}
}
}

View file

@ -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()
}