glory_cli/ext/
util.rs

1use crate::ext::anyhow::{bail, Context, Result};
2use camino::Utf8PathBuf;
3use std::borrow::Cow;
4
5pub fn os_arch() -> Result<(&'static str, &'static str)> {
6    let target_os = if cfg!(target_os = "windows") {
7        "windows"
8    } else if cfg!(target_os = "macos") {
9        "macos"
10    } else if cfg!(target_os = "linux") {
11        "linux"
12    } else {
13        bail!("unsupported OS")
14    };
15
16    let target_arch = if cfg!(target_arch = "x86_64") {
17        "x86_64"
18    } else if cfg!(target_arch = "aarch64") {
19        "aarch64"
20    } else {
21        bail!("unsupported target architecture")
22    };
23    Ok((target_os, target_arch))
24}
25
26pub fn is_linux_musl_env() -> bool {
27    cfg!(target_os = "linux") && cfg!(target_env = "musl")
28}
29
30pub trait StrAdditions {
31    fn with(&self, append: &str) -> String;
32    fn pad_left_to(&self, len: usize) -> Cow<str>;
33    /// returns the string as a canonical path (creates the dir if necessary)
34    fn to_created_dir(&self) -> Result<Utf8PathBuf>;
35}
36
37impl StrAdditions for str {
38    fn with(&self, append: &str) -> String {
39        let mut s = self.to_string();
40        s.push_str(append);
41        s
42    }
43
44    fn pad_left_to(&self, len: usize) -> Cow<str> {
45        let chars = self.chars().count();
46        if chars < len {
47            Cow::Owned(format!("{}{self}", " ".repeat(len - chars)))
48        } else {
49            Cow::Borrowed(self)
50        }
51    }
52
53    fn to_created_dir(&self) -> Result<Utf8PathBuf> {
54        let path = Utf8PathBuf::from(self);
55        if !path.exists() {
56            std::fs::create_dir_all(&path).context(format!("Could not create dir {self:?}"))?;
57        }
58        Ok(path)
59    }
60}
61
62impl StrAdditions for String {
63    fn with(&self, append: &str) -> String {
64        let mut s = self.clone();
65        s.push_str(append);
66        s
67    }
68
69    fn pad_left_to(&self, len: usize) -> Cow<str> {
70        self.as_str().pad_left_to(len)
71    }
72
73    fn to_created_dir(&self) -> Result<Utf8PathBuf> {
74        self.as_str().to_created_dir()
75    }
76}