eb_pipeline/
util.rs

1//! Small helpers.
2
3use crate::exit::Fail;
4
5/// Split a string on whitespace, honouring single and double quotes.
6pub fn split_args(s: &str) -> Result<Vec<String>, Fail> {
7    let mut out = Vec::new();
8    let mut cur = String::new();
9    let mut quote: Option<char> = None;
10    let mut have = false;
11    for c in s.chars() {
12        match quote {
13            Some(q) if c == q => quote = None,
14            Some(_) => cur.push(c),
15            None if c == '\'' || c == '"' => {
16                quote = Some(c);
17                have = true;
18            }
19            None if c.is_whitespace() => {
20                if have || !cur.is_empty() {
21                    out.push(std::mem::take(&mut cur));
22                    have = false;
23                }
24            }
25            None => cur.push(c),
26        }
27    }
28    if quote.is_some() {
29        return Err(Fail::usage(format!("unterminated quote in `{s}`")));
30    }
31    if have || !cur.is_empty() {
32        out.push(cur);
33    }
34    Ok(out)
35}
36
37/// Whether `s` is a log stamp: a UTC time as `YYYYMMDD_HHMMSS`, the name
38/// `eb-keep-logs rotate` ages as a run directory.
39pub fn is_log_stamp(s: &str) -> bool {
40    let b = s.as_bytes();
41    b.len() == 15
42        && b[8] == b'_'
43        && b[..8].iter().chain(&b[9..]).all(u8::is_ascii_digit)
44        && chrono::NaiveDateTime::parse_from_str(s, "%Y%m%d_%H%M%S").is_ok()
45}
46
47/// Parse dotted numbers (`1.2.3`); a leading `v` is accepted.
48pub fn parse_version(s: &str) -> Option<Vec<u64>> {
49    let s = s.trim().trim_start_matches('v');
50    if s.is_empty() {
51        return None;
52    }
53    s.split('.').map(|p| p.parse::<u64>().ok()).collect()
54}
55
56/// Compare two dotted versions; missing components count as zero.
57pub fn cmp_version(a: &[u64], b: &[u64]) -> std::cmp::Ordering {
58    let n = a.len().max(b.len());
59    for i in 0..n {
60        let x = a.get(i).copied().unwrap_or(0);
61        let y = b.get(i).copied().unwrap_or(0);
62        if x != y {
63            return x.cmp(&y);
64        }
65    }
66    std::cmp::Ordering::Equal
67}
68
69/// First dotted-number token of a `--version` output.
70pub fn find_version(output: &str) -> Option<Vec<u64>> {
71    for tok in output.split(|c: char| c.is_whitespace() || c == ',' || c == '(' || c == ')') {
72        let t = tok.trim_start_matches('v');
73        if t.chars().next().is_some_and(|c| c.is_ascii_digit()) {
74            let core: String = t
75                .chars()
76                .take_while(|c| c.is_ascii_digit() || *c == '.')
77                .collect();
78            if let Some(v) = parse_version(core.trim_end_matches('.')) {
79                return Some(v);
80            }
81        }
82    }
83    None
84}
85
86/// One line of a build list.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct ListLine {
89    /// The line as written, trimmed.
90    pub raw: String,
91    /// Easyconfig file name or path.
92    pub easyconfig: String,
93    /// Remaining easybuild arguments.
94    pub args: Vec<String>,
95}
96
97/// Read build list lines: blank lines and `#` comments are skipped.
98pub fn parse_list(text: &str) -> Result<Vec<ListLine>, Fail> {
99    let mut out = Vec::new();
100    for l in text.lines() {
101        let t = l.trim();
102        if t.is_empty() || t.starts_with('#') {
103            continue;
104        }
105        let mut parts = split_args(t)?;
106        let easyconfig = parts.remove(0);
107        out.push(ListLine {
108            raw: t.to_string(),
109            easyconfig,
110            args: parts,
111        });
112    }
113    Ok(out)
114}
115
116/// Package name and version of an easyconfig file name `Name-version[-toolchain].eb`.
117pub fn package_of(easyconfig: &str) -> (String, Option<String>) {
118    let base = easyconfig.rsplit('/').next().unwrap_or(easyconfig);
119    let stem = base.strip_suffix(".eb").unwrap_or(base);
120    let parts: Vec<&str> = stem.split('-').collect();
121    let mut name = Vec::new();
122    let mut i = 0;
123    while i < parts.len() {
124        if i > 0 && parts[i].chars().next().is_some_and(|c| c.is_ascii_digit()) {
125            break;
126        }
127        name.push(parts[i]);
128        i += 1;
129    }
130    (name.join("-"), parts.get(i).map(|s| s.to_string()))
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn split_quotes() {
139        assert_eq!(
140            split_args("-p batch --comment 'a b' \"\"").unwrap(),
141            vec!["-p", "batch", "--comment", "a b", ""]
142        );
143        assert!(split_args("'open").is_err());
144    }
145
146    #[test]
147    fn versions() {
148        assert_eq!(find_version("eb-stack 0.7.4 (abc)"), Some(vec![0, 7, 4]));
149        assert_eq!(find_version("tool v1.2"), Some(vec![1, 2]));
150        assert_eq!(cmp_version(&[1, 2], &[1, 2, 0]), std::cmp::Ordering::Equal);
151        assert_eq!(cmp_version(&[0, 7, 4], &[0, 10]), std::cmp::Ordering::Less);
152    }
153
154    #[test]
155    fn package_names() {
156        assert_eq!(
157            package_of("GROMACS-2025.2-foss-2025a.eb"),
158            ("GROMACS".into(), Some("2025.2".into()))
159        );
160        assert_eq!(
161            package_of("/x/y/R-bundle-Bioconductor-3.20-foss-2025a.eb"),
162            ("R-bundle-Bioconductor".into(), Some("3.20".into()))
163        );
164    }
165
166    #[test]
167    fn list_lines() {
168        let l = parse_list("# c\n\nFoo-1.0-foss-2025a.eb --rebuild\n").unwrap();
169        assert_eq!(l.len(), 1);
170        assert_eq!(l[0].args, vec!["--rebuild"]);
171    }
172
173    #[test]
174    fn log_stamps() {
175        for ok in ["20261116_024713", "20240229_235959", "19700101_000000"] {
176            assert!(is_log_stamp(ok), "{ok}");
177        }
178        for bad in [
179            "",
180            "2026-11-16",
181            "20261116",
182            "20261116_02471",
183            "20261116-024713",
184            "20261116_0247130",
185            "20261301_000000",
186            "20250229_000000",
187            "20261116_240000",
188            "20261116_006000",
189            "+2026116_024713",
190            " 2026116_024713",
191            "../20261116_0247",
192        ] {
193            assert!(!is_log_stamp(bad), "{bad:?}");
194        }
195    }
196}