afetch/
utils.rs

1use std::collections::HashMap;
2use std::process::Command;
3
4pub const fn div_mod(dividend: u64, divisor: u64) -> (u64, u64) {
5    (dividend / divisor, dividend % divisor)
6}
7
8pub fn return_str_from_command(command: &mut Command) -> String {
9    match command.output() {
10        Ok(output) => String::from_utf8_lossy(&output.stdout).to_string(),
11        Err(_) => String::default(),
12    }
13}
14
15pub fn get_file_content_without_lines(file_path: &str) -> String {
16    std::fs::read_to_string(file_path)
17        .unwrap_or_default()
18        .replace('\n', "")
19}
20
21pub fn get_file_content(file_path: &str) -> String {
22    std::fs::read_to_string(file_path).unwrap_or_default()
23}
24
25pub fn command_exist(program: &str) -> bool {
26    which::which(program).is_ok()
27}
28
29pub fn format_time(time_to_format: u64, language: &HashMap<&'static str, &'static str>) -> String {
30    let (minutes, seconds): (u64, u64) = div_mod(time_to_format, 60);
31    let (hours, minutes): (u64, u64) = div_mod(minutes, 60);
32    let (days, hours): (u64, u64) = div_mod(hours, 24);
33    let mut time_formatted: Vec<String> = Vec::new();
34
35    match days {
36        0 => (),
37        1 => time_formatted.push(format!("{} {}", days, language["day"])),
38        _ => time_formatted.push(format!("{} {}", days, language["days"])),
39    }
40
41    match hours {
42        0 => (),
43        1 => time_formatted.push(format!("{} {}", hours, language["hour"])),
44        _ => time_formatted.push(format!("{} {}", hours, language["hours"])),
45    }
46
47    match minutes {
48        0 => (),
49        1 => time_formatted.push(format!("{} {}", minutes, language["minute"])),
50        _ => time_formatted.push(format!("{} {}", minutes, language["minutes"])),
51    }
52
53    if seconds > 0 && minutes == 0 && hours == 0 {
54        match minutes {
55            0 => (),
56            1 => time_formatted.push(format!("{} {}", seconds, language["second"])),
57            _ => time_formatted.push(format!("{} {}", seconds, language["seconds"])),
58        }
59    }
60    time_formatted.join(", ")
61}
62
63// Based on the human_bytes library of Forkbomb9: https://gitlab.com/forkbomb9/human_bytes-rs
64pub fn convert_to_readable_unity<T: Into<f64>>(size: T) -> String {
65    const SUFFIX: [&str; 9] = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
66    let size_converted: f64 = size.into();
67    if size_converted <= 0.0_f64 {
68        return "0 B".to_owned();
69    }
70    let base: f64 = size_converted.log10() / 1024_f64.log10();
71    let mut result: String = format!("{:.1}", 1024_f64.powf(base - base.floor()))
72        .trim_end_matches(".0")
73        .to_owned();
74    result.push_str(SUFFIX[base.floor() as usize]);
75    result
76}
77
78pub fn env_exist(env_var: &str) -> bool {
79    std::env::var(env_var).is_ok()
80}
81
82pub fn get_env(env_var: &str) -> String {
83    std::env::var(env_var).unwrap_or_default()
84}