39 lines
1.5 KiB
Rust
39 lines
1.5 KiB
Rust
//! Small helpers shared across modules.
|
|
use anyhow::{Result, anyhow};
|
|
use serde_json::Value;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Command;
|
|
|
|
pub fn base(p: &Path) -> String {
|
|
p.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "root".into())
|
|
}
|
|
|
|
pub fn sanitize(s: &str) -> String {
|
|
s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c.to_ascii_lowercase() } else { '-' }).collect()
|
|
}
|
|
|
|
pub fn sq(s: &str) -> String {
|
|
format!("'{}'", s.replace('\'', r"'\''"))
|
|
}
|
|
|
|
/// Find a tool on PATH, else in its Homebrew keg (keg-only formulae like e2fsprogs aren't linked).
|
|
pub fn need(tool: &str, formula: &str) -> Result<PathBuf> {
|
|
let on_path = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).unwrap_or_default();
|
|
let find = |dirs: &[PathBuf]| dirs.iter().map(|d| d.join(tool)).find(|p| p.is_file());
|
|
find(&on_path)
|
|
.or_else(|| {
|
|
let o = Command::new("brew").args(["--prefix", formula]).output().ok()?;
|
|
let keg = PathBuf::from(String::from_utf8_lossy(&o.stdout).trim());
|
|
find(&[keg.join("sbin"), keg.join("bin")])
|
|
})
|
|
.ok_or_else(|| anyhow!("{tool} not found — install it with: brew install {formula}"))
|
|
}
|
|
|
|
pub fn strs(v: &Value) -> Vec<String> {
|
|
v.as_array().map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default()
|
|
}
|
|
|
|
pub fn now() -> u64 {
|
|
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()
|
|
}
|