use std::fs;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
pub const CONFIG_FILE_NAME: &str = "haj.toml";
const LEGACY_CONFIG_FILE_NAME: &str = "config.toml";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GeneralConfig {
pub aur_only: bool,
pub repo_only: bool,
pub verbose: bool,
pub diff_prog: String,
pub build_dir: String,
pub animations: bool,
pub privilege_cmd: Option<String>,
}
fn non_empty_env(name: &str) -> Option<String> {
std::env::var(name).ok().filter(|v| !v.trim().is_empty())
}
impl Default for GeneralConfig {
fn default() -> Self {
let home = non_empty_env("HOME").map_or_else(|| PathBuf::from("/"), PathBuf::from);
Self {
aur_only: false,
repo_only: false,
verbose: false,
diff_prog: "vimdiff".to_string(),
build_dir: home.join(".cache/haj/aur").to_string_lossy().to_string(),
animations: true,
privilege_cmd: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ColorConfig {
pub theme: String,
pub accent: String,
pub secondary: String,
pub heading: String,
pub text: String,
pub muted: String,
pub success: String,
pub warning: String,
pub error: String,
pub repo_core: String,
pub repo_extra: String,
pub repo_multilib: String,
pub repo_aur: String,
}
impl Default for ColorConfig {
fn default() -> Self {
Self {
theme: "default".into(),
accent: "cyan".into(),
secondary: "magenta".into(),
heading: "light_magenta".into(),
text: "white".into(),
muted: "dark_gray".into(),
success: "green".into(),
warning: "yellow".into(),
error: "red".into(),
repo_core: "cyan".into(),
repo_extra: "green".into(),
repo_multilib: "yellow".into(),
repo_aur: "magenta".into(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HajConfig {
pub general: GeneralConfig,
pub colors: ColorConfig,
}
enum TomlScalar {
Bool(bool),
Str(String),
}
fn strip_toml_comment(line: &str) -> &str {
let mut in_double = false;
let mut in_single = false;
let mut escaped = false;
for (idx, ch) in line.char_indices() {
if escaped {
escaped = false;
continue;
}
if in_double {
if ch == '\\' {
escaped = true;
} else if ch == '"' {
in_double = false;
}
} else if in_single {
if ch == '\'' {
in_single = false;
}
} else {
match ch {
'"' => in_double = true,
'\'' => in_single = true,
'#' => return &line[..idx],
_ => {}
}
}
}
line
}
fn parse_toml_scalar(raw: &str) -> Result<TomlScalar, String> {
let val = raw.trim();
if val == "true" {
return Ok(TomlScalar::Bool(true));
}
if val == "false" {
return Ok(TomlScalar::Bool(false));
}
if let Some(inner) = val.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
let mut out = String::with_capacity(inner.len());
let mut chars = inner.chars();
while let Some(ch) = chars.next() {
if ch == '\\' {
match chars.next() {
Some('"') => out.push('"'),
Some('\\') => out.push('\\'),
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('r') => out.push('\r'),
Some(other) => return Err(format!("unsupported escape \\{other}")),
None => return Err("unterminated escape sequence".to_string()),
}
} else if ch == '"' {
return Err("unexpected unescaped quote in string".to_string());
} else {
out.push(ch);
}
}
return Ok(TomlScalar::Str(out));
}
if let Some(inner) = val.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')) {
return Ok(TomlScalar::Str(inner.to_string()));
}
Err(format!("invalid config value: {val}"))
}
fn expect_bool(v: TomlScalar, key: &str) -> Result<bool, String> {
match v {
TomlScalar::Bool(b) => Ok(b),
TomlScalar::Str(_) => Err(format!("expected boolean for '{key}'")),
}
}
fn expect_string(v: TomlScalar, key: &str) -> Result<String, String> {
match v {
TomlScalar::Str(s) => Ok(s),
TomlScalar::Bool(_) => Err(format!("expected string for '{key}'")),
}
}
pub fn parse_haj_config(contents: &str) -> Result<HajConfig, String> {
let mut cfg = HajConfig::default();
let mut section = String::new();
for (idx, raw_line) in contents.lines().enumerate() {
let line_no = idx + 1;
let line = strip_toml_comment(raw_line).trim();
if line.is_empty() {
continue;
}
if line.starts_with('[') {
let Some(name) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) else {
return Err(format!("line {line_no}: invalid section header"));
};
section = name.trim().to_string();
continue;
}
let Some((key_raw, val_raw)) = line.split_once('=') else {
return Err(format!("line {line_no}: expected 'key = value'"));
};
let key = key_raw.trim();
if key.is_empty() {
return Err(format!("line {line_no}: empty key"));
}
let parsed = parse_toml_scalar(val_raw).map_err(|e| format!("line {line_no}: {e}"))?;
match section.as_str() {
"general" => match key {
"aur_only" => cfg.general.aur_only = expect_bool(parsed, key)?,
"repo_only" => cfg.general.repo_only = expect_bool(parsed, key)?,
"verbose" => cfg.general.verbose = expect_bool(parsed, key)?,
"animations" => cfg.general.animations = expect_bool(parsed, key)?,
"diff_prog" => cfg.general.diff_prog = expect_string(parsed, key)?,
"build_dir" => cfg.general.build_dir = expect_string(parsed, key)?,
"privilege_cmd" => cfg.general.privilege_cmd = Some(expect_string(parsed, key)?),
_ => {}
},
"colors" => {
let val = expect_string(parsed, key)?;
match key {
"theme" => cfg.colors.theme = val,
"accent" => cfg.colors.accent = val,
"secondary" => cfg.colors.secondary = val,
"heading" => cfg.colors.heading = val,
"text" => cfg.colors.text = val,
"muted" => cfg.colors.muted = val,
"success" => cfg.colors.success = val,
"warning" => cfg.colors.warning = val,
"error" => cfg.colors.error = val,
"repo_core" => cfg.colors.repo_core = val,
"repo_extra" => cfg.colors.repo_extra = val,
"repo_multilib" => cfg.colors.repo_multilib = val,
"repo_aur" => cfg.colors.repo_aur = val,
_ => {}
}
}
_ => {}
}
}
Ok(cfg)
}
fn escape_toml_string(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
_ => out.push(ch),
}
}
out
}
pub fn format_haj_config(cfg: &HajConfig) -> String {
let g = &cfg.general;
let mut out = format!(
"# haj package manager configuration\n\n[general]\naur_only = {}\nrepo_only = {}\nverbose = {}\ndiff_prog = \"{}\"\nbuild_dir = \"{}\"\nanimations = {}\n",
g.aur_only,
g.repo_only,
g.verbose,
escape_toml_string(&g.diff_prog),
escape_toml_string(&g.build_dir),
g.animations,
);
if let Some(ref priv_cmd) = g.privilege_cmd {
out.push_str(&format!(
"privilege_cmd = \"{}\"\n",
escape_toml_string(priv_cmd)
));
}
let c = &cfg.colors;
let is_custom = c.theme.trim().eq_ignore_ascii_case("custom");
out.push_str("\n[colors]\n");
out.push_str("# themes: default, custom, catppuccin-latte, catppuccin-frappe,\n");
out.push_str("# catppuccin-macchiato, catppuccin-mocha, tokyo-night, tokyo-storm,\n");
out.push_str("# dracula, nord, gruvbox-dark, gruvbox-material, onedark,\n");
out.push_str("# everforest-dark, kanagawa-wave, kanagawa-dragon,\n");
out.push_str("# solarized-dark, monokai, ayu, flexoki-dark\n");
out.push_str(&format!("theme = \"{}\"\n", escape_toml_string(&c.theme)));
out.push_str("\n# only used when theme = \"custom\"\n");
let prefix = if is_custom { "" } else { "# " };
for (k, v) in [
("accent", &c.accent),
("secondary", &c.secondary),
("heading", &c.heading),
("text", &c.text),
("muted", &c.muted),
("success", &c.success),
("warning", &c.warning),
("error", &c.error),
("repo_core", &c.repo_core),
("repo_extra", &c.repo_extra),
("repo_multilib", &c.repo_multilib),
("repo_aur", &c.repo_aur),
] {
out.push_str(&format!("{prefix}{k} = \"{}\"\n", escape_toml_string(v)));
}
out
}
pub fn expand_tilde(path: &str, home: Option<&str>) -> PathBuf {
if path == "~"
&& let Some(h) = home
{
return PathBuf::from(h);
}
if let Some(rest) = path.strip_prefix("~/")
&& let Some(h) = home
{
return PathBuf::from(h).join(rest);
}
PathBuf::from(path)
}
pub fn resolve_aur_cache_dir() -> PathBuf {
let cfg = load_config();
let home = non_empty_env("HOME");
expand_tilde(&cfg.general.build_dir, home.as_deref())
}
#[derive(Debug, PartialEq, Eq)]
enum ConfigDirSource {
User(PathBuf),
SystemReadOnly(PathBuf),
}
fn resolve_config_dir_from(xdg_config_home: Option<&str>, home: Option<&str>) -> ConfigDirSource {
if let Some(xdg) = xdg_config_home.map(str::trim).filter(|s| !s.is_empty()) {
let p = Path::new(xdg);
if p.is_absolute() {
return ConfigDirSource::User(p.join("haj"));
}
}
if let Some(h) = home.map(str::trim).filter(|s| !s.is_empty()) {
return ConfigDirSource::User(Path::new(h).join(".config").join("haj"));
}
ConfigDirSource::SystemReadOnly(PathBuf::from("/etc/haj"))
}
fn read_and_parse_config(path: &Path) -> HajConfig {
match fs::read_to_string(path) {
Ok(contents) => match parse_haj_config(&contents) {
Ok(config) => config,
Err(e) => {
eprintln!("\x1b[31m✗ failed to parse {}: {e}\x1b[0m", path.display());
HajConfig::default()
}
},
Err(_) => HajConfig::default(),
}
}
#[cfg(test)]
pub fn load_config_from_env(xdg_config_home: Option<&str>, home: Option<&str>) -> HajConfig {
load_config_from_env_with_write(xdg_config_home, home, true)
}
pub fn load_config_from_env_with_write(
xdg_config_home: Option<&str>,
home: Option<&str>,
create_if_missing: bool,
) -> HajConfig {
let dir_source = resolve_config_dir_from(xdg_config_home, home);
let (config_dir, can_write) = match &dir_source {
ConfigDirSource::User(dir) => (dir.as_path(), create_if_missing),
ConfigDirSource::SystemReadOnly(dir) => (dir.as_path(), false),
};
let haj_path = config_dir.join(CONFIG_FILE_NAME);
let legacy_path = config_dir.join(LEGACY_CONFIG_FILE_NAME);
if haj_path.exists() {
return read_and_parse_config(&haj_path);
}
if legacy_path.exists() {
return read_and_parse_config(&legacy_path);
}
let default_config = HajConfig::default();
if can_write {
if let Err(e) = fs::create_dir_all(config_dir) {
eprintln!("\x1b[31m✗ failed to create config directory: {e}\x1b[0m");
return default_config;
}
let toml_string = format_haj_config(&default_config);
if let Err(e) = fs::write(&haj_path, toml_string) {
eprintln!("\x1b[31m✗ failed to write {CONFIG_FILE_NAME}: {e}\x1b[0m");
}
}
default_config
}
static CACHED_CONFIG: OnceLock<HajConfig> = OnceLock::new();
pub fn init_config(create_if_missing: bool) -> &'static HajConfig {
CACHED_CONFIG.get_or_init(|| {
let xdg = non_empty_env("XDG_CONFIG_HOME");
let home = non_empty_env("HOME");
load_config_from_env_with_write(xdg.as_deref(), home.as_deref(), create_if_missing)
})
}
pub fn load_config() -> &'static HajConfig {
init_config(true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_and_format_config_roundtrip() {
let input = r#"
# custom user settings
[general]
aur_only = true
diff_prog = "nvim -d" # inline comment
build_dir = '/tmp/aur#dir'
animations = false
privilege_cmd = "doas"
"#;
let cfg = parse_haj_config(input).unwrap();
assert!(cfg.general.aur_only);
assert!(!cfg.general.repo_only);
assert!(!cfg.general.animations);
assert_eq!(cfg.general.diff_prog, "nvim -d");
assert_eq!(cfg.general.build_dir, "/tmp/aur#dir");
assert_eq!(cfg.general.privilege_cmd.as_deref(), Some("doas"));
let rendered = format_haj_config(&cfg);
let reparsed = parse_haj_config(&rendered).unwrap();
assert_eq!(cfg, reparsed);
}
#[test]
fn test_parse_config_rejects_invalid_toml() {
assert!(parse_haj_config("invalid toml syntax = {[").is_err());
assert!(parse_haj_config("[general\naur_only = true").is_err());
assert!(parse_haj_config("[general]\nverbose = \"yes\"").is_err());
assert!(parse_haj_config("[general]\ndiff_prog = \"unclosed").is_err());
}
#[test]
fn test_expand_tilde() {
assert_eq!(
expand_tilde("~/.cache/haj/aur", Some("/home/alice")),
PathBuf::from("/home/alice/.cache/haj/aur")
);
assert_eq!(
expand_tilde("/var/tmp/aur", Some("/home/alice")),
PathBuf::from("/var/tmp/aur")
);
}
#[test]
fn test_xdg_config_home_edge_cases() {
assert_eq!(
resolve_config_dir_from(Some("/tmp/custom-xdg"), Some("/home/alice")),
ConfigDirSource::User(PathBuf::from("/tmp/custom-xdg/haj"))
);
assert_eq!(
resolve_config_dir_from(Some(""), Some("/home/alice")),
ConfigDirSource::User(PathBuf::from("/home/alice/.config/haj"))
);
assert_eq!(
resolve_config_dir_from(Some("relative/path"), Some("/home/alice")),
ConfigDirSource::User(PathBuf::from("/home/alice/.config/haj"))
);
assert_eq!(
resolve_config_dir_from(Some(" "), Some("")),
ConfigDirSource::SystemReadOnly(PathBuf::from("/etc/haj"))
);
assert_eq!(
resolve_config_dir_from(None, None),
ConfigDirSource::SystemReadOnly(PathBuf::from("/etc/haj"))
);
}
#[test]
fn test_load_config_prefers_haj_toml_with_legacy_fallback_and_preserves_comments() {
let base = std::env::temp_dir().join(format!("haj_cfg_unit_{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
let xdg = base.join("xdg");
let dir = xdg.join("haj");
let xdg_str = xdg.to_str().unwrap();
let cfg = load_config_from_env(Some(xdg_str), None);
assert_eq!(cfg, HajConfig::default());
let haj_path = dir.join("haj.toml");
assert!(haj_path.exists());
let custom = "# keep my comment\n[general]\naur_only = true\n";
fs::write(&haj_path, custom).unwrap();
let reloaded = load_config_from_env(Some(xdg_str), None);
assert!(reloaded.general.aur_only);
assert_eq!(fs::read_to_string(&haj_path).unwrap(), custom);
fs::remove_file(&haj_path).unwrap();
fs::write(dir.join("config.toml"), "[general]\nverbose = true\n").unwrap();
let legacy = load_config_from_env(Some(xdg_str), None);
assert!(legacy.general.verbose);
assert!(!haj_path.exists());
let _ = fs::remove_dir_all(&base);
}
#[test]
fn test_parse_colors_section_roundtrip() {
let input = r##"
[colors]
theme = "custom"
accent = "#8bd5ca" # inline comment
secondary = "light_magenta"
muted = "240"
error = '#ed8796'
"##;
let cfg = parse_haj_config(input).unwrap();
assert_eq!(cfg.colors.theme, "custom");
assert_eq!(cfg.colors.accent, "#8bd5ca");
assert_eq!(cfg.colors.secondary, "light_magenta");
assert_eq!(cfg.colors.muted, "240");
assert_eq!(cfg.colors.error, "#ed8796");
assert_eq!(cfg.colors.success, "green");
let rendered = format_haj_config(&cfg);
let reparsed = parse_haj_config(&rendered).unwrap();
assert_eq!(cfg, reparsed);
let default_rendered = format_haj_config(&HajConfig::default());
assert!(default_rendered.contains("theme = \"default\""));
assert!(default_rendered.contains("# only used when theme = \"custom\""));
assert!(default_rendered.contains("# accent = \"cyan\""));
}
#[test]
fn test_dry_run_config_load_does_not_create_haj_toml() {
let base = std::env::temp_dir().join(format!("haj_cfg_dry_{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
let xdg = base.join("xdg");
let xdg_str = xdg.to_str().unwrap();
let cfg = load_config_from_env_with_write(Some(xdg_str), None, false);
assert_eq!(cfg, HajConfig::default());
assert!(!xdg.join("haj/haj.toml").exists());
let _ = fs::remove_dir_all(&base);
}
}