ignore_matcher.cpp

src/mcp/servers/ignore_matcher.cpp

@file ignore_matcher.cpp @brief Gitignore + explorerignore implementation (#15, v2.1.4).

Owners: @tvanfossen

add_pattern

void entropic::IgnoreMatcher::add_pattern(const std::string &pattern, const std::filesystem::path &base={})

Add a single pattern programmatically (test surface).

src/mcp/servers/ignore_matcher.cpp:424

Show on the map →

Called by TEST_CASE

Calls compile_pattern, push_rule, to_slash

Source · 6 lines
void IgnoreMatcher::add_pattern(const std::string& pattern,
                                const fs::path& base) {
    std::string trimmed = trim(pattern);
    if (trimmed.empty() || trimmed[0] == '#') { return; }
    push_rule(compile_pattern(trimmed, to_slash(base)));
}
Activity · 4 steps
lines 426–426std::string trimmed = trim(pattern);lines 427–427◇ if (trimmed.empty() || trimmed[0] == '#')lines 427–427return;lines 428–428push_rule(compile_pattern(trimmed, to_slash(base)));

Requirements

REQ-MCP-022

collect_buckets

void entropic::anonymous_namespace{ignore_matcher.cpp}::collect_buckets(const BaseIndex &index, const std::string &rel_path, std::vector< BucketCursor > &out)

Gather the buckets that can possibly match rel_path .

src/mcp/servers/ignore_matcher.cpp:612

Show on the map →

Called by is_ignored

Calls take

Source · 13 lines
void collect_buckets(const BaseIndex& index, const std::string& rel_path,
                     std::vector<BucketCursor>& out) {
    auto take = [&](const std::string& base) {
        auto found = index.find(base);
        if (found != index.end() && !found->second.empty()) {
            out.push_back({&found->second, found->second.size()});
        }
    };
    take("");
    for (std::size_t i = 0; i < rel_path.size(); ++i) {
        if (rel_path[i] == '/') { take(rel_path.substr(0, i)); }
    }
}
Activity · 5 steps
lines 614–619auto take = [&](const std::string& base) { auto found = index.find(base); if (found != index.end() && !found->second.empty()) { out.push_back({&found->second, found->second.size()}); } };lines 620–620take("");lines 621–621◇ for (std::size_t i = 0; i < rel_path.size(); ++i)lines 622–622◇ if (rel_path[i] == '/')lines 622–622take(rel_path.substr(0, i));

Requirements

REQ-MCP-022

compile_or_never

std::regex entropic::anonymous_namespace{ignore_matcher.cpp}::compile_or_never(const std::string &src, const std::string &original_pattern)

Compile a regex source; return a never-match regex on std::regex_error, with a warning log line.

src/mcp/servers/ignore_matcher.cpp:334

Source · 10 lines
std::regex compile_or_never(const std::string& src,
                            const std::string& original_pattern) {
    try {
        return std::regex(src);
    } catch (const std::regex_error& e) {
        logger->warn("Skipping malformed ignore pattern '{}': {}",
                     original_pattern, e.what());
        return std::regex("(?!)");
    }
}
Activity · 1 steps
lines 336–342try { return std::regex(src); } catch (const std::regex_error& e) { logger->warn("Skipping malformed ignore pattern '{}': {}", original_pattern, e.what()); return std::regex("(?!)"); }

Requirements

REQ-MCP-022

compile_pattern

IgnoreMatcher::Rule entropic::IgnoreMatcher::compile_pattern(const std::string &pattern, const std::string &base)

Compile a single pattern into a Rule .

src/mcp/servers/ignore_matcher.cpp:368

Source · 25 lines
IgnoreMatcher::Rule IgnoreMatcher::compile_pattern(
    const std::string& pattern, const std::string& base) {
    Rule rule;
    rule.original = pattern;
    rule.base = normalize_base(base);

    std::string body = pattern;
    strip_flags(body, rule);
    bool root_anchored = !body.empty() && body[0] == '/';
    if (root_anchored) { body.erase(0, 1); }
    bool anchored = root_anchored
        || body.find('/') != std::string::npos;

    std::string regex_body = pattern_to_regex(body);
    std::string base_prefix = make_base_prefix(rule.base);
    std::string anchor_left = anchored
        ? ("^" + base_prefix)
        : ("^" + base_prefix + "(?:.*/)?");

    rule.re_exact = compile_or_never(
        anchor_left + regex_body + "$", pattern);
    rule.re_under = compile_or_never(
        anchor_left + regex_body + "/.*$", pattern);
    return rule;
}
Activity · 15 steps
lines 370–370Rule rule;lines 371–371rule.original = pattern;lines 372–372rule.base = normalize_base(base);lines 374–374std::string body = pattern;lines 375–375strip_flags(body, rule);lines 376–376bool root_anchored = !body.empty() && body[0] == '/';lines 377–377◇ if (root_anchored)lines 377–377body.erase(0, 1);lines 378–379bool anchored = root_anchored || body.find('/') != std::string::npos;lines 381–381std::string regex_body = pattern_to_regex(body);lines 382–382std::string base_prefix = make_base_prefix(rule.base);lines 383–385std::string anchor_left = anchored ? ("^" + base_prefix) : ("^" + base_prefix + "(?:.*/)?");lines 387–388rule.re_exact = compile_or_never( anchor_left + regex_body + "$", pattern);lines 389–390rule.re_under = compile_or_never( anchor_left + regex_body + "/.*$", pattern);lines 391–391return rule;

Requirements

REQ-MCP-022

emit_one

void entropic::anonymous_namespace{ignore_matcher.cpp}::emit_one(const std::string &pattern, size_t &i, std::string &out)

Emit regex for ONE pattern character; advances i for multi-char tokens ( ** , [...] , escapes).

src/mcp/servers/ignore_matcher.cpp:197

Show on the map →

Called by pattern_to_regex

Calls emit_bracket, emit_escape, emit_star, is_regex_meta

Source · 22 lines
void emit_one(const std::string& pattern, size_t& i,
              std::string& out) {
    char c = pattern[i];
    bool handled = true;
    switch (c) {
    case '*': emit_star(pattern, i, out); break;
    case '?': out += "[^/]"; break;
    case '[': emit_bracket(pattern, i, out); break;
    case '\\':
        if (i + 1 < pattern.size()) {
            emit_escape(pattern, i, out);
        } else {
            handled = false;
        }
        break;
    default: handled = false; break;
    }
    if (!handled) {
        if (is_regex_meta(c)) { out += '\\'; }
        out += c;
    }
}
Activity · 7 steps
lines 199–199char c = pattern[i];lines 200–200bool handled = true;lines 201–213switch (c) { case '*': emit_star(pattern, i, out); break; case '?': out += "[^/]"; break; case '[': emit_bracket(pattern, i, out); break; case '\\': if (i + 1 < pattern.size()) { emit_escape(pattern, i, out); } else { handled = false; } break; default: handled = false; break; }lines 214–214◇ if (!handled)lines 215–215◇ if (is_regex_meta(c))lines 215–215out += '\\';lines 216–216out += c;

Requirements

REQ-MCP-022

is_ignored

bool entropic::IgnoreMatcher::is_ignored(const std::string &rel_path, bool is_dir) const

Test whether a path is ignored.

src/mcp/servers/ignore_matcher.cpp:708

Source · 15 lines
bool IgnoreMatcher::is_ignored(const std::string& rel_path,
                               bool is_dir) const {
    std::vector<BucketCursor> cursors;
    collect_buckets(by_base_, rel_path, cursors);

    bool ignored = false;
    for (std::size_t idx = pop_highest(cursors); idx != kNoRule;
         idx = pop_highest(cursors)) {
        if (rule_matches(rules_[idx], rel_path, is_dir, regex_evals_)) {
            ignored = !rules_[idx].negate;
            break;
        }
    }
    return ignored;
}
Activity · 8 steps
lines 710–710std::vector<BucketCursor> cursors;lines 711–711collect_buckets(by_base_, rel_path, cursors);lines 713–713bool ignored = false;lines 714–714◇ for (std::size_t idx = pop_highest(cursors); idx != kNoRule; idx = pop_highest(cursors))lines 716–716◇ if (rule_matches(rules_[idx], rel_path, is_dir, regex_evals_))lines 717–717ignored = !rules_[idx].negate;lines 718–718break;lines 721–721return ignored;

Requirements

REQ-MCP-022

is_skipped_dir_name

bool entropic::IgnoreMatcher::is_skipped_dir_name(const std::string &name)

Directory names never walked, by name alone (gh#161).

src/mcp/servers/ignore_matcher.cpp:107

Source · 10 lines
bool IgnoreMatcher::is_skipped_dir_name(const std::string& name) {
    static const std::vector<std::string> kSkipDirs = {
        ".git", "node_modules", "__pycache__", ".venv"
    };
    bool skipped = false;
    for (const auto& skip : kSkipDirs) {
        if (name == skip) { skipped = true; }
    }
    return skipped;
}
Activity · 6 steps
lines 108–110static const std::vector<std::string> kSkipDirs = { ".git", "node_modules", "__pycache__", ".venv" };lines 111–111bool skipped = false;lines 112–112◇ for (const auto& skip : kSkipDirs)lines 113–113◇ if (name == skip)lines 113–113skipped = true;lines 115–115return skipped;

Requirements

REQ-MCP-022

load

void entropic::IgnoreMatcher::load(const std::filesystem::path &root)

Load gitignore + explorerignore from a workspace root.

src/mcp/servers/ignore_matcher.cpp:473

Show on the map →

Called by FilesystemServer, IgnoreMatcher, TEST_CASE, set_working_dir

Calls load_file, load_nested_gitignores, reset_regex_evals

Source · 19 lines
void IgnoreMatcher::load(const fs::path& root) {
    rules_.clear();
    by_base_.clear();
    reset_regex_evals();
    if (!fs::exists(root) || !fs::is_directory(root)) {
        logger->warn("IgnoreMatcher::load: root does not exist: {}",
                     root.string());
        return;
    }

    auto canonical_root = fs::weakly_canonical(root);
    fs::path root_gi = canonical_root / ".gitignore";
    if (fs::exists(root_gi)) { load_file(root_gi, ""); }

    load_nested_gitignores(canonical_root, root_gi);

    fs::path explorer = canonical_root / ".explorerignore";
    if (fs::exists(explorer)) { load_file(explorer, ""); }
}
Activity · 14 steps
lines 474–474rules_.clear();lines 475–475by_base_.clear();lines 476–476reset_regex_evals();lines 477–477◇ if (!fs::exists(root) || !fs::is_directory(root))lines 478–479logger->warn("IgnoreMatcher::load: root does not exist: {}", root.string());lines 480–480return;lines 483–483auto canonical_root = fs::weakly_canonical(root);lines 484–484fs::path root_gi = canonical_root / ".gitignore";lines 485–485◇ if (fs::exists(root_gi))lines 485–485load_file(root_gi, "");lines 487–487load_nested_gitignores(canonical_root, root_gi);lines 489–489fs::path explorer = canonical_root / ".explorerignore";lines 490–490◇ if (fs::exists(explorer))lines 490–490load_file(explorer, "");

Requirements

REQ-MCP-022

load_file

void entropic::IgnoreMatcher::load_file(const std::filesystem::path &path, const std::string &base)

Load and parse a single ignore file.

src/mcp/servers/ignore_matcher.cpp:443

Source · 16 lines
void IgnoreMatcher::load_file(const fs::path& path,
                              const std::string& base) {
    std::ifstream in(path);
    if (!in.is_open()) { return; }
    std::string line;
    int loaded = 0;
    while (std::getline(in, line)) {
        std::string trimmed = trim(line);
        if (trimmed.empty() || trimmed[0] == '#') { continue; }
        push_rule(compile_pattern(trimmed, base));
        ++loaded;
    }
    std::string base_label = base.empty() ? std::string("<root>") : base;
    logger->info("Loaded {} ignore rules from {} (base='{}')",
                 loaded, path.string(), base_label);
}
Activity · 13 steps
lines 445–445std::ifstream in(path);lines 446–446◇ if (!in.is_open())lines 446–446return;lines 447–447std::string line;lines 448–448int loaded = 0;lines 449–449◇ while (std::getline(in, line))lines 450–450std::string trimmed = trim(line);lines 451–451◇ if (trimmed.empty() || trimmed[0] == '#')lines 451–451continue;lines 452–452push_rule(compile_pattern(trimmed, base));lines 453–453++loaded;lines 455–455std::string base_label = base.empty() ? std::string("<root>") : base;lines 456–457logger->info("Loaded {} ignore rules from {} (base='{}')", loaded, path.string(), base_label);

Requirements

REQ-MCP-022

load_nested_gitignores

void entropic::IgnoreMatcher::load_nested_gitignores(const std::filesystem::path &canonical_root, const std::filesystem::path &root_gi)

Recursively load nested .gitignore files under the root.

src/mcp/servers/ignore_matcher.cpp:500

Source · 14 lines
void IgnoreMatcher::load_nested_gitignores(
    const fs::path& canonical_root, const fs::path& root_gi) {
    try {
        fs::recursive_directory_iterator it(
            canonical_root,
            fs::directory_options::skip_permission_denied);
        const fs::recursive_directory_iterator end;
        for (; it != end; ++it) {
            visit_discovery_entry(it, canonical_root, root_gi);
        }
    } catch (const std::exception& e) {
        logger->warn("Recursive gitignore scan aborted: {}", e.what());
    }
}
Activity · 1 steps
lines 502–512try { fs::recursive_directory_iterator it( canonical_root, fs::directory_options::skip_permission_denied); const fs::recursive_directory_iterator end; for (; it != end; ++it) { visit_discovery_entry(it, canonical_root, root_gi); } } catch (const std::exception& e) { logger->warn("Recursive gitignore scan aborted: {}", e.what()); }

Requirements

REQ-MCP-022

make_base_prefix

std::string entropic::anonymous_namespace{ignore_matcher.cpp}::make_base_prefix(const std::string &base)

Build a regex prefix from a non-root anchor base.

src/mcp/servers/ignore_matcher.cpp:306

Show on the map →

Called by compile_pattern

Calls is_regex_meta

Source · 12 lines
std::string make_base_prefix(const std::string& base) {
    if (base.empty()) { return {}; }
    std::string raw = base + "/";
    std::string out;
    for (char c : raw) {
        if (is_regex_meta(c) || c == '*' || c == '?' || c == '[') {
            out += '\\';
        }
        out += c;
    }
    return out;
}
Activity · 9 steps
lines 307–307◇ if (base.empty())lines 307–307return {};lines 308–308std::string raw = base + "/";lines 309–309std::string out;lines 310–310◇ for (char c : raw)lines 311–311◇ if (is_regex_meta(c) || c == '*' || c == '?' || c == '[')lines 312–312out += '\\';lines 314–314out += c;lines 316–316return out;

Requirements

REQ-MCP-022

normalize_base

std::string entropic::anonymous_namespace{ignore_matcher.cpp}::normalize_base(const std::string &base)

Canonicalise an anchor base to the form a relative path prefix takes: no .

src/mcp/servers/ignore_matcher.cpp:288

Source · 7 lines
std::string normalize_base(const std::string& base) {
    std::string out = base;
    if (out.rfind("./", 0) == 0) { out.erase(0, 2); }
    if (out == ".") { out.clear(); }
    while (!out.empty() && out.back() == '/') { out.pop_back(); }
    return out;
}
Activity · 8 steps
lines 289–289std::string out = base;lines 290–290◇ if (out.rfind("./", 0) == 0)lines 290–290out.erase(0, 2);lines 291–291◇ if (out == ".")lines 291–291out.clear();lines 292–292◇ while (!out.empty() && out.back() == '/')lines 292–292out.pop_back();lines 293–293return out;

Requirements

REQ-MCP-022

pattern_to_regex

std::string entropic::IgnoreMatcher::pattern_to_regex(const std::string &pattern)

Convert a gitignore pattern body to a POSIX regex source.

src/mcp/servers/ignore_matcher.cpp:236

Source · 8 lines
std::string IgnoreMatcher::pattern_to_regex(const std::string& pattern) {
    std::string out;
    out.reserve(pattern.size() * 2);
    for (size_t i = 0; i < pattern.size(); ++i) {
        emit_one(pattern, i, out);
    }
    return out;
}
Activity · 5 steps
lines 237–237std::string out;lines 238–238out.reserve(pattern.size() * 2);lines 239–239◇ for (size_t i = 0; i < pattern.size(); ++i)lines 240–240emit_one(pattern, i, out);lines 242–242return out;

Requirements

REQ-MCP-022

pop_highest

std::size_t entropic::anonymous_namespace{ignore_matcher.cpp}::pop_highest(std::vector< BucketCursor > &cursors)

Pop the highest unexamined rule index across all buckets.

src/mcp/servers/ignore_matcher.cpp:639

Show on the map →

Called by is_ignored

Calls none

Source · 14 lines
std::size_t pop_highest(std::vector<BucketCursor>& cursors) {
    std::size_t best = kNoRule;
    BucketCursor* from = nullptr;
    for (auto& cursor : cursors) {
        if (cursor.remaining == 0) { continue; }
        std::size_t candidate = (*cursor.indices)[cursor.remaining - 1];
        if (from == nullptr || candidate > best) {
            best = candidate;
            from = &cursor;
        }
    }
    if (from != nullptr) { --from->remaining; }
    return best;
}
Activity · 12 steps
lines 640–640std::size_t best = kNoRule;lines 641–641BucketCursor* from = nullptr;lines 642–642◇ for (auto& cursor : cursors)lines 643–643◇ if (cursor.remaining == 0)lines 643–643continue;lines 644–644std::size_t candidate = (*cursor.indices)[cursor.remaining - 1];lines 645–645◇ if (from == nullptr || candidate > best)lines 646–646best = candidate;lines 647–647from = &cursor;lines 650–650◇ if (from != nullptr)lines 650–650--from->remaining;lines 651–651return best;

Requirements

REQ-MCP-022

prunes_discovery

bool entropic::IgnoreMatcher::prunes_discovery(const std::filesystem::path &dir, const std::filesystem::path &canonical_root) const

Whether the discovery walk must not descend into a directory (skip list, or already excluded) — gh#161.

src/mcp/servers/ignore_matcher.cpp:569

Source · 6 lines
bool IgnoreMatcher::prunes_discovery(
    const fs::path& dir, const fs::path& canonical_root) const {
    if (is_skipped_dir_name(dir.filename().string())) { return true; }
    auto rel = to_slash(fs::relative(dir, canonical_root));
    return !rel.empty() && is_ignored(rel, true);
}
Activity · 4 steps
lines 571–571◇ if (is_skipped_dir_name(dir.filename().string()))lines 571–571return true;lines 572–572auto rel = to_slash(fs::relative(dir, canonical_root));lines 573–573return !rel.empty() && is_ignored(rel, true);

Requirements

REQ-MCP-022

push_rule

void entropic::IgnoreMatcher::push_rule(Rule &&rule)

Append a compiled rule and index it by its anchor base.

src/mcp/servers/ignore_matcher.cpp:407

Source · 5 lines
void IgnoreMatcher::push_rule(Rule&& rule) {
    std::string base = rule.base;
    rules_.push_back(std::move(rule));
    by_base_[base].push_back(rules_.size() - 1);
}
Activity · 3 steps
lines 408–408std::string base = rule.base;lines 409–409rules_.push_back(std::move(rule));lines 410–410by_base_[base].push_back(rules_.size() - 1);

Requirements

REQ-MCP-022

rule_matches

bool entropic::anonymous_namespace{ignore_matcher.cpp}::rule_matches(const IgnoreMatcher::Rule &rule, const std::string &rel_path, bool is_dir, std::atomic< std::uint64_t > &evals)

Test one rule against a path, counting the regexes it runs.

src/mcp/servers/ignore_matcher.cpp:670

Show on the map →

Called by is_ignored

Calls none

Source · 14 lines
bool rule_matches(const IgnoreMatcher::Rule& rule,
                  const std::string& rel_path, bool is_dir,
                  std::atomic<std::uint64_t>& evals) {
    evals.fetch_add(1, std::memory_order_relaxed);
    bool matched = std::regex_match(rel_path, rule.re_under);
    // For dir_only rules an exact match only counts when the path is
    // itself a directory — a regular file named like a `dir/` pattern
    // is NOT excluded.
    if (!matched && (!rule.dir_only || is_dir)) {
        evals.fetch_add(1, std::memory_order_relaxed);
        matched = std::regex_match(rel_path, rule.re_exact);
    }
    return matched;
}
Activity · 6 steps
lines 673–673evals.fetch_add(1, std::memory_order_relaxed);lines 674–674bool matched = std::regex_match(rel_path, rule.re_under);lines 678–678◇ if (!matched && (!rule.dir_only || is_dir))lines 679–679evals.fetch_add(1, std::memory_order_relaxed);lines 680–680matched = std::regex_match(rel_path, rule.re_exact);lines 682–682return matched;

Requirements

REQ-MCP-022

strip_flags

void entropic::anonymous_namespace{ignore_matcher.cpp}::strip_flags(std::string &body, IgnoreMatcher::Rule &rule)

Strip leading ! (negation) and trailing / (dir_only) from a pattern body, recording flags on the rule.

src/mcp/servers/ignore_matcher.cpp:264

Source · 10 lines
void strip_flags(std::string& body, IgnoreMatcher::Rule& rule) {
    if (!body.empty() && body[0] == '!') {
        rule.negate = true;
        body.erase(0, 1);
    }
    if (!body.empty() && body.back() == '/') {
        rule.dir_only = true;
        body.pop_back();
    }
}
Activity · 6 steps
lines 265–265◇ if (!body.empty() && body[0] == '!')lines 266–266rule.negate = true;lines 267–267body.erase(0, 1);lines 269–269◇ if (!body.empty() && body.back() == '/')lines 270–270rule.dir_only = true;lines 271–271body.pop_back();

Requirements

REQ-MCP-022

visit_discovery_entry

void entropic::IgnoreMatcher::visit_discovery_entry(std::filesystem::recursive_directory_iterator &it, const std::filesystem::path &canonical_root, const std::filesystem::path &root_gi)

Handle one entry of the discovery walk: prune or load.

src/mcp/servers/ignore_matcher.cpp:536

Source · 18 lines
void IgnoreMatcher::visit_discovery_entry(
    fs::recursive_directory_iterator& it,
    const fs::path& canonical_root, const fs::path& root_gi) {
    const auto& entry = *it;
    if (entry.is_directory()) {
        if (prunes_discovery(entry.path(), canonical_root)) {
            it.disable_recursion_pending();
        }
        return;
    }
    if (entry.path().filename() != ".gitignore"
        || entry.path() == root_gi) {
        return;
    }
    auto rel_dir = fs::relative(entry.path().parent_path(),
                                canonical_root);
    load_file(entry.path(), to_slash(rel_dir));
}
Activity · 9 steps
lines 539–539const auto& entry = *it;lines 540–540◇ if (entry.is_directory())lines 541–541◇ if (prunes_discovery(entry.path(), canonical_root))lines 542–542it.disable_recursion_pending();lines 544–544return;lines 546–547◇ if (entry.path().filename() != ".gitignore" || entry.path() == root_gi)lines 548–548return;lines 550–551auto rel_dir = fs::relative(entry.path().parent_path(), canonical_root);lines 552–552load_file(entry.path(), to_slash(rel_dir));

Requirements

REQ-MCP-022