bath 0.7.0

A TUI tool to manage and export environment variable profiles
//! One-line text forms of definitions (`NAME  list  ':'`) and library values
//! (`value  # tag, tag`).

use crate::config::{CatalogItem, CustomVarDef, ItemKind, VarKind};
use crate::envfile::{quote, unquote, Diagnostic, Severity};

fn error(out: &mut Vec<Diagnostic>, line: usize, message: String) {
    out.push(Diagnostic {
        line,
        severity: Severity::Error,
        message,
    });
}

pub fn format_defs(defs: &[CustomVarDef]) -> Vec<String> {
    let width = defs.iter().map(|d| d.name.len()).max().unwrap_or(0).max(12) + 2;
    defs.iter()
        .map(|d| match d.kind {
            VarKind::Scalar => format!("{:<width$}value", d.name),
            VarKind::List => format!("{:<width$}list   {}", d.name, quote(&d.separator)),
        })
        .collect()
}

pub fn parse_defs(
    lines: &[String],
    is_builtin: impl Fn(&str) -> bool,
) -> (Vec<CustomVarDef>, Vec<Diagnostic>) {
    let mut defs: Vec<CustomVarDef> = Vec::new();
    let mut diags = Vec::new();
    for (i, line) in lines.iter().enumerate() {
        let text = line.trim();
        if text.is_empty() {
            continue;
        }
        let (name, rest) = text.split_once(char::is_whitespace).unwrap_or((text, ""));
        let rest = rest.trim();
        let (kind, sep) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
        if !crate::catalog::is_var_name(name) {
            error(
                &mut diags,
                i,
                format!("'{name}' is not a valid variable name"),
            );
            continue;
        }
        if is_builtin(name) {
            error(
                &mut diags,
                i,
                format!("{name} is built in and cannot be redefined"),
            );
            continue;
        }
        if defs.iter().any(|d| d.name == name) {
            error(&mut diags, i, format!("{name} is defined twice"));
            continue;
        }
        let parsed = match (kind, sep.trim()) {
            ("list", "") => Ok((VarKind::List, ":".to_string())),
            ("list", s) => unquote(s).map(|s| (VarKind::List, s)),
            ("value" | "scalar", "") => Ok((VarKind::Scalar, String::new())),
            ("value" | "scalar", _) => Err("a value takes no separator".to_string()),
            ("", _) => Err(format!("{name} needs a kind: list or value")),
            (other, _) => Err(format!("unknown kind '{other}', use list or value")),
        };
        match parsed {
            Ok((kind, separator)) => defs.push(CustomVarDef {
                name: name.to_string(),
                kind,
                separator,
            }),
            Err(message) => error(&mut diags, i, message),
        }
    }
    (defs, diags)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LibraryLine {
    pub value: String,
    pub tags: Vec<String>,
}

/// Byte offset of the `#` that starts the tags, if any.
pub fn tag_start(line: &str) -> Option<usize> {
    line.char_indices()
        .find(|(i, c)| *c == '#' && *i > 0 && line[..*i].ends_with(char::is_whitespace))
        .map(|(i, _)| i)
}

/// Split `value  # a, b` into the value and its tags. A `#` only starts the
/// tags after whitespace, so `https://x/#a` stays one value.
pub fn split_tags(line: &str) -> LibraryLine {
    let Some(i) = tag_start(line) else {
        return LibraryLine {
            value: line.trim().to_string(),
            tags: Vec::new(),
        };
    };
    LibraryLine {
        value: line[..i].trim().to_string(),
        tags: line[i + 1..]
            .split(',')
            .map(str::trim)
            .filter(|t| !t.is_empty())
            .map(str::to_string)
            .collect(),
    }
}

pub fn format_library(items: &[CatalogItem]) -> Vec<String> {
    let width = items
        .iter()
        .map(|i| i.value.len())
        .max()
        .unwrap_or(0)
        .max(20)
        + 2;
    items
        .iter()
        .map(|i| {
            if i.tags.is_empty() {
                return i.value.clone();
            }
            format!("{:<width$}# {}", i.value, i.tags.join(", "))
        })
        .collect()
}

fn guess_kind(value: &str) -> ItemKind {
    if value.contains('/') {
        return ItemKind::Path;
    }
    ItemKind::Text
}

/// Items for parsed lines, keeping id, kind, program and version of items
/// with the same value.
pub fn build_items(lines: &[LibraryLine], existing: &[CatalogItem]) -> Vec<CatalogItem> {
    lines
        .iter()
        .map(|l| {
            let found = existing.iter().find(|e| e.value == l.value);
            let Some(item) = found else {
                let kind = guess_kind(&l.value);
                return CatalogItem {
                    id: None,
                    kind,
                    value: l.value.clone(),
                    program: None,
                    version: None,
                    tags: l.tags.clone(),
                };
            };
            CatalogItem {
                tags: l.tags.clone(),
                ..item.clone()
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn lines(text: &str) -> Vec<String> {
        text.lines().map(str::to_string).collect()
    }

    fn def(name: &str, kind: VarKind, sep: &str) -> CustomVarDef {
        CustomVarDef {
            name: name.into(),
            kind,
            separator: sep.into(),
        }
    }

    #[test]
    fn defs_round_trip() {
        let defs = vec![
            def("ACME_HOSTS", VarKind::List, ","),
            def("MY_OPTS", VarKind::List, " "),
            def("TOKEN", VarKind::Scalar, ""),
        ];
        let (back, diags) = parse_defs(&format_defs(&defs), |_| false);
        assert!(diags.is_empty());
        assert_eq!(back, defs);
    }

    #[test]
    fn defs_errors() {
        let (defs, diags) = parse_defs(
            &lines("PATH list\nA list x\nA list\nA value\nB\nC frob\n9X value"),
            |n| n == "PATH",
        );
        assert_eq!(defs, vec![def("A", VarKind::List, ":")]);
        let lines_with_errors: Vec<usize> = diags.iter().map(|d| d.line).collect();
        assert_eq!(lines_with_errors, vec![0, 1, 3, 4, 5, 6]);
    }

    #[test]
    fn library_tags_need_whitespace_before_hash() {
        assert_eq!(
            split_tags("/opt/llvm/bin   # llvm, c"),
            LibraryLine {
                value: "/opt/llvm/bin".into(),
                tags: vec!["llvm".into(), "c".into()]
            }
        );
        assert_eq!(split_tags("https://x/#a").value, "https://x/#a");
    }

    #[test]
    fn library_round_trip_keeps_item_metadata() {
        let items = vec![CatalogItem {
            id: Some(7),
            kind: ItemKind::Path,
            value: "/opt/llvm/bin".into(),
            program: Some("clang".into()),
            version: Some("18".into()),
            tags: vec!["llvm".into()],
        }];
        let mut text = format_library(&items);
        text.push("-fsanitize=address".into());
        let parsed: Vec<LibraryLine> = text.iter().map(|l| split_tags(l)).collect();
        let built = build_items(&parsed, &items);
        assert_eq!(built[0], items[0]);
        assert_eq!(built[1].id, None);
        assert_eq!(built[1].kind, ItemKind::Text);
    }
}