tree2md 0.10.0

Like the tree command, but outputs in Markdown. Optimized for AI agents.
use crate::cli::{Args, FilterRule, RuleKind};

/// Declarative specification of file matching rules.
///
/// The list of `-I` / `-X` rules is kept as a single ordered `Vec` so that
/// last-match-wins semantics can be evaluated by the engine. Each rule's
/// pattern is normalized at construction time so the engine sees only
/// well-formed globs.
#[derive(Debug, Clone)]
pub struct MatchSpec {
    /// Ordered filter rules from CLI (-I / -X), preserving argv order.
    pub rules: Vec<FilterRule>,

    /// Whether to respect gitignore files
    pub respect_gitignore: bool,

    /// Whether to apply safety presets (exclude sensitive files)
    pub use_safety_preset: bool,

    /// Whether pattern matching is case sensitive
    pub case_sensitive: bool,
}

impl Default for MatchSpec {
    fn default() -> Self {
        Self {
            rules: Vec::new(),
            respect_gitignore: false,
            use_safety_preset: true,
            case_sensitive: true,
        }
    }
}

impl MatchSpec {
    #[allow(dead_code)]
    pub fn new() -> Self {
        Self::default()
    }

    /// Normalize a user-supplied glob pattern.
    ///
    /// Three things happen here:
    /// 1. Trailing `/` is stripped (`hoge/` and `hoge` are equivalent).
    /// 2. `**X` where X is not `/` is rewritten to `**/*X`. This is purely
    ///    a UX fix: globset treats `**.json` as a literal segment, not a
    ///    recursive match, so users who write `**.test.ts` silently get no
    ///    matches. We rewrite it to the intended form.
    /// 3. Patterns without `/` are anchored recursively: bare names like
    ///    `vendor` become `**/vendor/**`, file patterns like `*.rs` become
    ///    `**/*.rs`. This mirrors gitignore conventions so `-X build`
    ///    matches `build/` anywhere in the tree.
    pub fn normalize_pattern(pattern: &str) -> String {
        let pattern = pattern.strip_suffix('/').unwrap_or(pattern);
        let pattern = fix_double_star(pattern);

        if !pattern.contains('/') {
            if !pattern.contains('*') && !pattern.contains('.') {
                format!("**/{}/**", pattern)
            } else {
                format!("**/{}", pattern)
            }
        } else {
            pattern
        }
    }

    /// Build a MatchSpec from CLI arguments.
    pub fn from_args(args: &Args, target_path: &std::path::Path) -> Self {
        let rules = args
            .filter_rules
            .iter()
            .map(|r| FilterRule {
                kind: r.kind,
                pattern: Self::normalize_pattern(&r.pattern),
            })
            .collect();

        let respect_gitignore = match args.use_gitignore {
            crate::cli::UseGitignoreMode::Always => true,
            crate::cli::UseGitignoreMode::Never => false,
            crate::cli::UseGitignoreMode::Auto => Self::is_inside_git_repo(target_path),
        };

        Self {
            rules,
            respect_gitignore,
            use_safety_preset: args.is_safe_mode(),
            case_sensitive: true,
        }
    }

    fn is_inside_git_repo(path: &std::path::Path) -> bool {
        let mut current = path;
        loop {
            if current.join(".git").exists() {
                return true;
            }
            match current.parent() {
                Some(parent) => current = parent,
                None => return false,
            }
        }
    }

    pub fn has_includes(&self) -> bool {
        self.rules.iter().any(|r| r.kind == RuleKind::Include)
    }

    /// Test helper: append include rules in order.
    #[allow(dead_code)]
    pub fn with_include_glob(mut self, patterns: Vec<String>) -> Self {
        for p in patterns {
            self.rules.push(FilterRule {
                kind: RuleKind::Include,
                pattern: Self::normalize_pattern(&p),
            });
        }
        self
    }

    /// Test helper: append exclude rules in order.
    #[allow(dead_code)]
    pub fn with_exclude_glob(mut self, patterns: Vec<String>) -> Self {
        for p in patterns {
            self.rules.push(FilterRule {
                kind: RuleKind::Exclude,
                pattern: Self::normalize_pattern(&p),
            });
        }
        self
    }

    /// Test helper: append rules preserving caller-specified order.
    #[allow(dead_code)]
    pub fn with_rules(mut self, rules: Vec<FilterRule>) -> Self {
        for r in rules {
            self.rules.push(FilterRule {
                kind: r.kind,
                pattern: Self::normalize_pattern(&r.pattern),
            });
        }
        self
    }

    #[allow(dead_code)]
    pub fn with_gitignore(mut self, respect: bool) -> Self {
        self.respect_gitignore = respect;
        self
    }

    #[allow(dead_code)]
    pub fn with_case_sensitive(mut self, sensitive: bool) -> Self {
        self.case_sensitive = sensitive;
        self
    }
}

/// Rewrite `**X` (where X is neither `/` nor `*`) as `**/*X`. This is the
/// pattern users intuitively write (`**.test.ts`) but globset treats as
/// a single literal segment. We patch it at the segment boundary only —
/// `**`, `**/`, `path/**`, `path/**/` are all left untouched.
fn fix_double_star(pattern: &str) -> String {
    let bytes = pattern.as_bytes();
    let n = bytes.len();
    let mut out = String::with_capacity(n + 4);
    let mut i = 0;
    while i < n {
        let at_segment_start = i == 0 || bytes[i - 1] == b'/';
        if at_segment_start
            && i + 2 < n
            && bytes[i] == b'*'
            && bytes[i + 1] == b'*'
            && bytes[i + 2] != b'/'
            && bytes[i + 2] != b'*'
        {
            out.push_str("**/*");
            i += 2;
            continue;
        }
        out.push(bytes[i] as char);
        i += 1;
    }
    out
}

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

    #[test]
    fn normalize_bare_name_to_recursive_dir() {
        assert_eq!(MatchSpec::normalize_pattern("vendor"), "**/vendor/**");
        assert_eq!(MatchSpec::normalize_pattern("__tests__"), "**/__tests__/**");
    }

    #[test]
    fn normalize_strips_trailing_slash() {
        assert_eq!(MatchSpec::normalize_pattern("hoge/"), "**/hoge/**");
        assert_eq!(MatchSpec::normalize_pattern("src/lib/"), "src/lib");
    }

    #[test]
    fn normalize_file_pattern_to_recursive() {
        assert_eq!(MatchSpec::normalize_pattern("*.rs"), "**/*.rs");
        assert_eq!(MatchSpec::normalize_pattern("foo.txt"), "**/foo.txt");
    }

    #[test]
    fn normalize_keeps_path_patterns() {
        assert_eq!(MatchSpec::normalize_pattern("src/*.go"), "src/*.go");
        assert_eq!(MatchSpec::normalize_pattern("**/*.md"), "**/*.md");
    }

    #[test]
    fn normalize_fixes_double_star_without_slash() {
        // The historical user-facing footgun.
        assert_eq!(MatchSpec::normalize_pattern("**.json"), "**/*.json");
        assert_eq!(MatchSpec::normalize_pattern("**.test.ts"), "**/*.test.ts");
        assert_eq!(
            MatchSpec::normalize_pattern("**.generated.json"),
            "**/*.generated.json"
        );
    }

    #[test]
    fn normalize_keeps_valid_double_star() {
        assert_eq!(MatchSpec::normalize_pattern("**/*.ts"), "**/*.ts");
        assert_eq!(MatchSpec::normalize_pattern("path/**"), "path/**");
        assert_eq!(MatchSpec::normalize_pattern("path/**/*.ts"), "path/**/*.ts");
        // Embedded `**`: `a/**/b/**.x` → `a/**/b/**/*.x`
        assert_eq!(MatchSpec::normalize_pattern("a/**/b/**.x"), "a/**/b/**/*.x");
    }

    #[test]
    fn has_includes_reflects_rules() {
        let spec = MatchSpec::new();
        assert!(!spec.has_includes());

        let spec = spec.with_include_glob(vec!["*.rs".into()]);
        assert!(spec.has_includes());

        let only_excl = MatchSpec::new().with_exclude_glob(vec!["build".into()]);
        assert!(!only_excl.has_includes());
    }
}