helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! `.helmignore` rules, a port of Helm's `pkg/ignore/rules.go` (v4.3.0).
//!
//! Patterns use Go's `filepath.Match` syntax (`*`, `?`, `[a-z]`, `\` escapes; `*` never crosses
//! `/`). `**` is rejected, `!` negates, a trailing `/` matches directories only and a leading `/`
//! anchors the pattern at the chart root.

/// File name of an ignore file inside a chart.
pub const HELM_IGNORE: &str = ".helmignore";

/// A `.helmignore` pattern that cannot be used.
#[derive(Debug, thiserror::Error)]
pub enum IgnoreError {
    /// The pattern contains `**`.
    #[error("double-star (**) syntax is not supported")]
    DoubleStar,
    /// The pattern is not valid `filepath.Match` syntax.
    #[error("syntax error in pattern: {0:?}")]
    BadPattern(String),
}

/// An ordered collection of ignore patterns.
#[derive(Debug, Default)]
pub struct Rules {
    patterns: Vec<Pattern>,
}

/// One parsed rule.
#[derive(Debug)]
struct Pattern {
    glob: String,
    negate: bool,
    must_dir: bool,
    scope: Scope,
}

/// What part of a path a rule is matched against.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
    /// Only the file name (no `/` in the rule).
    Name,
    /// The whole path (`/` inside the rule).
    Path,
    /// The whole path, from the chart root (leading `/`).
    Root,
}

impl Rules {
    /// Returns an empty ruleset.
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Adds Helm's default rule, which ignores dotfiles in `templates/`.
    ///
    /// # Panics
    /// Never: the default pattern is valid.
    pub fn add_defaults(&mut self) {
        self.parse_rule("templates/.?*")
            .expect("the default rule is valid");
    }

    /// Parses the text of a `.helmignore` file.
    ///
    /// # Errors
    /// Fails on `**` or a malformed glob, like Helm.
    pub fn parse(text: &str) -> Result<Self, IgnoreError> {
        let mut rules = Self::empty();
        let text = text.strip_prefix('\u{feff}').unwrap_or(text);

        for line in text.lines() {
            rules.parse_rule(line)?;
        }

        Ok(rules)
    }

    /// Reports whether `path` (slash separated, relative to the chart root) is ignored.
    ///
    /// Rules are evaluated in order and the first decisive one wins; a matching negative rule
    /// does not decide, a non-matching one ignores the path, exactly as in Helm.
    #[must_use]
    pub fn ignore(&self, path: &str, is_dir: bool) -> bool {
        if path.is_empty() || path == "." || path == "./" {
            return false;
        }

        for pattern in &self.patterns {
            if pattern.negate {
                if pattern.must_dir && !is_dir {
                    return true;
                }
                if !pattern.matches(path) {
                    return true;
                }

                continue;
            }
            if pattern.must_dir && !is_dir {
                continue;
            }
            if pattern.matches(path) {
                return true;
            }
        }

        false
    }

    /// Parses one rule line and appends it.
    fn parse_rule(&mut self, rule: &str) -> Result<(), IgnoreError> {
        let rule = rule.trim();

        if rule.is_empty() || rule.starts_with('#') {
            return Ok(());
        }
        if rule.contains("**") {
            return Err(IgnoreError::DoubleStar);
        }
        if glob_match(rule, "abc").is_err() {
            return Err(IgnoreError::BadPattern(rule.to_owned()));
        }

        let mut glob = rule;
        let negate = glob.starts_with('!');

        if negate {
            glob = &glob[1..];
        }

        let must_dir = glob.ends_with('/');

        if must_dir {
            glob = &glob[..glob.len() - 1];
        }

        let anchored = glob.starts_with('/');

        if anchored {
            glob = &glob[1..];
        }

        let scope = match (anchored, glob.contains('/')) {
            (true, _) => Scope::Root,
            (false, true) => Scope::Path,
            (false, false) => Scope::Name,
        };

        self.patterns.push(Pattern {
            glob: glob.to_owned(),
            negate,
            must_dir,
            scope,
        });

        Ok(())
    }
}

impl Pattern {
    /// Matches the whole path for anchored or structural rules, else only the file name.
    fn matches(&self, path: &str) -> bool {
        let name = if self.scope == Scope::Name {
            go_base(path)
        } else {
            path
        };

        glob_match(&self.glob, name).unwrap_or(false)
    }
}

/// Marker for a malformed `filepath.Match` pattern.
#[derive(Debug)]
pub(crate) struct BadPattern;

/// Go's `filepath.Base`: the last element, ignoring trailing slashes.
fn go_base(path: &str) -> &str {
    let trimmed = path.trim_end_matches('/');

    match trimmed.rsplit('/').next() {
        Some("") | None if path.is_empty() => ".",
        Some("") | None => "/",
        Some(last) => last,
    }
}

/// Splits off the next chunk of `pattern`: leading stars, then text up to the next free `*`.
fn scan_chunk(pattern: &[char]) -> (bool, &[char], &[char]) {
    let stars = pattern.iter().take_while(|c| **c == '*').count();
    let pattern = &pattern[stars..];
    let mut in_range = false;
    let mut i = 0;

    while i < pattern.len() {
        match pattern[i] {
            '\\' if i + 1 < pattern.len() => i += 1,
            '[' => in_range = true,
            ']' => in_range = false,
            '*' if !in_range => break,
            _ => {}
        }
        i += 1;
    }

    (stars > 0, &pattern[..i], &pattern[i..])
}

/// Reads one possibly escaped character of a `[...]` class.
fn get_esc(chunk: &[char]) -> Result<(char, &[char]), BadPattern> {
    let mut chunk = chunk;

    if chunk.is_empty() || chunk[0] == '-' || chunk[0] == ']' {
        return Err(BadPattern);
    }
    if chunk[0] == '\\' {
        chunk = &chunk[1..];

        if chunk.is_empty() {
            return Err(BadPattern);
        }
    }

    let rest = &chunk[1..];

    if rest.is_empty() {
        return Err(BadPattern);
    }

    Ok((chunk[0], rest))
}

/// Matches one chunk (no free `*`) against the start of `s`; `Err` is a malformed pattern.
fn match_chunk<'a>(chunk: &[char], s: &'a [char]) -> Result<Option<&'a [char]>, BadPattern> {
    let mut chunk = chunk;
    let mut s = s;
    let mut failed = false;

    while !chunk.is_empty() {
        if !failed && s.is_empty() {
            failed = true;
        }

        match chunk[0] {
            '[' => {
                let mut r = '\0';

                if !failed {
                    r = s[0];
                    s = &s[1..];
                }
                chunk = &chunk[1..];

                let negated = chunk.first() == Some(&'^');

                if negated {
                    chunk = &chunk[1..];
                }

                let mut matched = false;
                let mut ranges = 0;

                loop {
                    if chunk.first() == Some(&']') && ranges > 0 {
                        chunk = &chunk[1..];
                        break;
                    }

                    let (lo, rest) = get_esc(chunk)?;
                    let mut hi = lo;

                    chunk = rest;
                    if chunk[0] == '-' {
                        let (h, rest) = get_esc(&chunk[1..])?;

                        hi = h;
                        chunk = rest;
                    }
                    if lo <= r && r <= hi {
                        matched = true;
                    }
                    ranges += 1;
                }
                if matched == negated {
                    failed = true;
                }
            }
            '?' => {
                if !failed {
                    if s[0] == '/' {
                        failed = true;
                    }
                    s = &s[1..];
                }
                chunk = &chunk[1..];
            }
            c => {
                if c == '\\' {
                    chunk = &chunk[1..];

                    if chunk.is_empty() {
                        return Err(BadPattern);
                    }
                }
                if !failed {
                    if chunk[0] != s[0] {
                        failed = true;
                    }
                    s = &s[1..];
                }
                chunk = &chunk[1..];
            }
        }
    }

    Ok((!failed).then_some(s))
}

/// Go's `filepath.Match` on Unix; `Err` is `ErrBadPattern`.
pub(crate) fn glob_match(pattern: &str, name: &str) -> Result<bool, BadPattern> {
    let mut pattern: &[char] = &pattern.chars().collect::<Vec<_>>();
    let mut name: &[char] = &name.chars().collect::<Vec<_>>();

    'pattern: while !pattern.is_empty() {
        let (star, chunk, rest) = scan_chunk(pattern);

        pattern = rest;
        if star && chunk.is_empty() {
            return Ok(!name.contains(&'/'));
        }

        let attempt = match_chunk(chunk, name);

        if let Ok(Some(tail)) = attempt
            && (tail.is_empty() || !pattern.is_empty())
        {
            name = tail;
            continue;
        }
        attempt?;
        if star {
            let mut i = 0;

            while i < name.len() && name[i] != '/' {
                let skipped = match_chunk(chunk, &name[i + 1..]);

                if let Ok(Some(tail)) = skipped {
                    if pattern.is_empty() && !tail.is_empty() {
                        i += 1;
                        continue;
                    }
                    name = tail;
                    continue 'pattern;
                }
                skipped?;
                i += 1;
            }
        }
        while !pattern.is_empty() {
            let (_, chunk, rest) = scan_chunk(pattern);

            pattern = rest;
            match_chunk(chunk, &[])?;
        }

        return Ok(false);
    }

    Ok(name.is_empty())
}

#[cfg(test)]
mod tests;