use std::path::{Path, PathBuf};
pub fn config_dir() -> PathBuf {
xdg_from(std::env::var_os("XDG_CONFIG_HOME"), ".config")
}
pub fn state_dir() -> PathBuf {
xdg_from(std::env::var_os("XDG_STATE_HOME"), ".local/state")
}
pub fn system_dir() -> PathBuf {
PathBuf::from("/etc/oomtop")
}
pub fn xdg_from(value: Option<std::ffi::OsString>, fallback: &str) -> PathBuf {
match value.map(PathBuf::from).filter(|p| p.is_absolute()) {
Some(v) => v.join("oomtop"),
None => home().join(fallback).join("oomtop"),
}
}
fn home() -> PathBuf {
dirs::home_dir().unwrap_or_else(|| PathBuf::from("."))
}
pub fn expand_tilde(p: &str) -> PathBuf {
if p == "~" {
return home();
}
match p.strip_prefix("~/") {
Some(rest) => home().join(rest),
None => PathBuf::from(p),
}
}
pub fn short_hostname() -> String {
let h = gethostname::gethostname().to_string_lossy().into_owned();
sanitize_hostname(&h)
}
pub fn sanitize_hostname(h: &str) -> String {
let s: String = h
.trim()
.split('.')
.next()
.unwrap_or("")
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'-'
}
})
.collect();
if s.trim_matches('-').is_empty() {
"localhost".into()
} else {
s
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigPaths {
pub dir: PathBuf,
pub config_toml: PathBuf,
pub config_d: PathBuf,
pub themes: PathBuf,
pub keymap: PathBuf,
pub layouts: PathBuf,
pub rules_d: PathBuf,
}
impl ConfigPaths {
pub fn new(dir: &Path) -> Self {
ConfigPaths {
dir: dir.to_path_buf(),
config_toml: dir.join("config.toml"),
config_d: dir.join("config.d"),
themes: dir.join("themes"),
keymap: dir.join("keymap.toml"),
layouts: dir.join("layouts"),
rules_d: dir.join("rules.d"),
}
}
pub fn default_user() -> Self {
Self::new(&config_dir())
}
pub fn host_file(&self, hostname: &str) -> PathBuf {
self.config_d.join(format!("host-{hostname}.toml"))
}
pub fn dropin(&self, name: &str) -> PathBuf {
let file = if name.ends_with(".toml") {
name.to_string()
} else {
format!("{name}.toml")
};
self.config_d.join(file)
}
pub fn theme_file(&self, name: &str) -> PathBuf {
self.themes.join(format!("{name}.toml"))
}
pub fn layout_file(&self, name: &str) -> PathBuf {
self.layouts.join(format!("{name}.toml"))
}
pub fn watch_paths(&self) -> Vec<PathBuf> {
if self.dir.exists() {
return vec![self.dir.clone()];
}
let mut cur = self.dir.parent();
while let Some(p) = cur {
if p.exists() {
return vec![p.to_path_buf()];
}
cur = p.parent();
}
Vec::new()
}
}
pub fn toml_files(dir: &Path) -> Vec<PathBuf> {
let mut v: Vec<PathBuf> = std::fs::read_dir(dir)
.map(|rd| {
rd.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.is_file() && p.extension().is_some_and(|x| x == "toml"))
.collect()
})
.unwrap_or_default();
v.sort();
v
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn xdg_rules() {
assert_eq!(
xdg_from(Some("/x/cfg".into()), ".config"),
PathBuf::from("/x/cfg/oomtop")
);
assert_eq!(
xdg_from(Some("rel".into()), ".config"),
home().join(".config/oomtop")
);
assert_eq!(
xdg_from(Some("".into()), ".local/state"),
home().join(".local/state/oomtop")
);
assert_eq!(xdg_from(None, ".config"), home().join(".config/oomtop"));
}
#[test]
fn layout_of_files() {
let p = ConfigPaths::new(Path::new("/c/oomtop"));
assert_eq!(
p.host_file("air"),
PathBuf::from("/c/oomtop/config.d/host-air.toml")
);
assert_eq!(p.dropin("50-x"), PathBuf::from("/c/oomtop/config.d/50-x.toml"));
assert_eq!(
p.dropin("50-x.toml"),
PathBuf::from("/c/oomtop/config.d/50-x.toml")
);
assert_eq!(
p.theme_file("ember"),
PathBuf::from("/c/oomtop/themes/ember.toml")
);
assert_eq!(sanitize_hostname("Alexs-MacBook-Air.local"), "Alexs-MacBook-Air");
assert_eq!(sanitize_hostname("we ird/host"), "we-ird-host");
assert_eq!(sanitize_hostname(""), "localhost");
assert_eq!(sanitize_hostname(".local"), "localhost");
assert_eq!(sanitize_hostname("//"), "localhost");
assert_eq!(expand_tilde("~/x"), home().join("x"));
assert_eq!(expand_tilde("/abs"), PathBuf::from("/abs"));
}
#[test]
fn watch_paths_fall_back_to_ancestor() {
let d = tempfile::tempdir().unwrap();
let p = ConfigPaths::new(&d.path().join("a/b/oomtop"));
assert_eq!(p.watch_paths(), vec![d.path().to_path_buf()]);
std::fs::create_dir_all(&p.dir).unwrap();
assert_eq!(p.watch_paths(), vec![p.dir.clone()]);
std::fs::write(p.dir.join("b.toml"), "").unwrap();
std::fs::write(p.dir.join("a.toml"), "").unwrap();
std::fs::write(p.dir.join("c.txt"), "").unwrap();
assert_eq!(
toml_files(&p.dir),
vec![p.dir.join("a.toml"), p.dir.join("b.toml")]
);
}
}