From 5b6e54b4b9e2ea1035de5816b4cd44a8aad91b9f Mon Sep 17 00:00:00 2001 From: lxcxjxhx Date: Mon, 9 Nov 2026 18:51:26 +0800 Subject: [PATCH] fix(tools): expand brace patterns in the grep include filter The include examples are brace patterns ("*.{ts,tsx}"), which ripgrep expands and fnmatch does not, so the Python fallback returned an empty result for a search ripgrep answers correctly. The expansion helper moves to the shared tools utils so glob and grep use one implementation. --- _msg.txt | 6 +++ _pr_body.md | 41 +++++++++++++++++++ openhands-tools/openhands/tools/glob/impl.py | 31 ++------------ openhands-tools/openhands/tools/grep/impl.py | 9 +++- .../openhands/tools/utils/__init__.py | 29 +++++++++++++ tests/tools/grep/test_grep_executor.py | 25 +++++++++++ 6 files changed, 113 insertions(+), 28 deletions(-) create mode 100644 _msg.txt create mode 100644 _pr_body.md diff --git a/_msg.txt b/_msg.txt new file mode 100644 index 00000000000..2776ac8257c --- /dev/null +++ b/_msg.txt @@ -0,0 +1,6 @@ +fix(tools): expand brace patterns in the grep include filter + +The include examples are brace patterns ("*.{ts,tsx}"), which ripgrep expands +and fnmatch does not, so the Python fallback returned an empty result for a +search ripgrep answers correctly. The expansion helper moves to the shared +tools utils so glob and grep use one implementation. diff --git a/_pr_body.md b/_pr_body.md new file mode 100644 index 00000000000..3ec92b2ca93 --- /dev/null +++ b/_pr_body.md @@ -0,0 +1,41 @@ +The glob Python fallback got brace expansion in #6615; grep's `include` never did, so the same search returned files through ripgrep and nothing through the fallback. + +`GrepAction.include` is documented with brace examples: + +```python + include: str | None = Field( + default=None, + description=( + "Optional file pattern to filter which files to search " + '(e.g., "*.js", "*.{ts,tsx}")' + ), + ) +``` + +`_path_matches_filters` matched the pattern with `fnmatch.fnmatch(filename, include_pattern)`, which has no brace support, so `*.{ts,tsx}` matched no filename at all. On a machine with ripgrep the search works; on one without it the same call returns an empty result, which reads as "no matches" rather than "the filter cannot match anything". + +Measured before the change, Python backend, three files containing the pattern: + +```text +include='*.ts' -> 1 match(es): ['a.ts'] +include='*.{ts,tsx}' -> 0 match(es): [] +include='*.{js,tsx}' -> 0 match(es): [] +``` + +and after: + +```text +include='*.ts' -> 1 match(es): ['a.ts'] +include='*.{ts,tsx}' -> 2 match(es): ['a.ts', 'b.tsx'] +include='*.{js,tsx}' -> 2 match(es): ['b.tsx', 'c.js'] +``` + +## What changed + +- `expand_braces()` moves from `openhands/tools/glob/impl.py` to the shared `openhands/tools/utils/` package, so both tools use one implementation instead of two. `glob` keeps its private name as an alias, which leaves its existing tests untouched. +- `grep`'s `_path_matches_filters` expands the pattern before matching, so `include` behaves the same on both backends. +- Regression test `test_python_backend_expands_brace_include_patterns` forces the Python backend (both availability probes return `False`) and asserts `*.{ts,tsx}` finds `a.ts` and `b.tsx` and not `c.js`. + +`tests/tools/grep` + `tests/tools/glob`: 83 passed, 32 skipped. `ruff check` and `ruff format` clean on the four touched files. + +The unbalanced-brace case still leaves the pattern alone (`"{a"` matching nothing) — the same behaviour ripgrep has, so there is nothing to align there. diff --git a/openhands-tools/openhands/tools/glob/impl.py b/openhands-tools/openhands/tools/glob/impl.py index 63eedc060a5..c9dfab48fba 100644 --- a/openhands-tools/openhands/tools/glob/impl.py +++ b/openhands-tools/openhands/tools/glob/impl.py @@ -17,36 +17,13 @@ from openhands.tools.utils import ( _check_ripgrep_available, _log_ripgrep_fallback_warning, + expand_braces, ) -def _expand_braces(pattern: str) -> list[str]: - """Expand ``{a,b}`` groups, which ripgrep's -g supports and glob does not.""" - start = pattern.find("{") - if start == -1: - return [pattern] - # Split the first group on its top-level commas; nested groups are - # expanded by the recursion. - depth, options, option_start = 0, [], start + 1 - for end in range(start, len(pattern)): - if pattern[end] == "{": - depth += 1 - elif pattern[end] == "}": - depth -= 1 - if depth == 0: - break - elif pattern[end] == "," and depth == 1: - options.append(pattern[option_start:end]) - option_start = end + 1 - else: - return [pattern] # unbalanced: leave it to glob as-is - options.append(pattern[option_start:end]) - head, tail = pattern[:start], pattern[end + 1 :] - return [ - expanded - for option in options - for expanded in _expand_braces(head + option + tail) - ] +# ripgrep supports {a,b} groups in -g; the glob module does not, so patterns are +# expanded before they reach it. +_expand_braces = expand_braces class GlobExecutor(ToolExecutor[GlobAction, GlobObservation]): diff --git a/openhands-tools/openhands/tools/grep/impl.py b/openhands-tools/openhands/tools/grep/impl.py index 0d8b27bd029..bed977c85b8 100644 --- a/openhands-tools/openhands/tools/grep/impl.py +++ b/openhands-tools/openhands/tools/grep/impl.py @@ -19,6 +19,7 @@ _check_grep_available, _check_ripgrep_available, _log_ripgrep_fallback_warning, + expand_braces, ) @@ -161,7 +162,13 @@ def _path_matches_filters( filename = relative_parts[-1] if relative_parts else path.name if include_pattern: - return fnmatch.fnmatch(filename, include_pattern) + # The documented examples are brace patterns ("*.{ts,tsx}"), which + # fnmatch matches literally; ripgrep expands them, so this backend + # has to expand them too or the same search returns nothing. + return any( + fnmatch.fnmatch(filename, expanded) + for expanded in expand_braces(include_pattern) + ) return not filename.startswith(".") def _match_mtime(self, path: Path) -> float: diff --git a/openhands-tools/openhands/tools/utils/__init__.py b/openhands-tools/openhands/tools/utils/__init__.py index 98d9da25098..966df29080f 100644 --- a/openhands-tools/openhands/tools/utils/__init__.py +++ b/openhands-tools/openhands/tools/utils/__init__.py @@ -58,3 +58,32 @@ def _log_ripgrep_fallback_warning(tool_name: str, fallback_method: str) -> None: f"For better performance, consider installing ripgrep: " f"https://github.com/BurntSushi/ripgrep#installation" ) + + +def expand_braces(pattern: str) -> list[str]: + """Expand ``{a,b}`` groups, which ripgrep supports and fnmatch and glob do not.""" + start = pattern.find("{") + if start == -1: + return [pattern] + # Split the first group on its top-level commas; nested groups are + # expanded by the recursion. + depth, options, option_start = 0, [], start + 1 + for end in range(start, len(pattern)): + if pattern[end] == "{": + depth += 1 + elif pattern[end] == "}": + depth -= 1 + if depth == 0: + break + elif pattern[end] == "," and depth == 1: + options.append(pattern[option_start:end]) + option_start = end + 1 + else: + return [pattern] # unbalanced: leave it to the caller as-is + options.append(pattern[option_start:end]) + head, tail = pattern[:start], pattern[end + 1 :] + return [ + expanded + for option in options + for expanded in expand_braces(head + option + tail) + ] diff --git a/tests/tools/grep/test_grep_executor.py b/tests/tools/grep/test_grep_executor.py index 46c07232a8d..2c2726d787c 100644 --- a/tests/tools/grep/test_grep_executor.py +++ b/tests/tools/grep/test_grep_executor.py @@ -346,3 +346,28 @@ def search_dir(name: str, path: str, pattern: str): assert all( all("beta_" in Path(f).name for f in matches) for matches in results_b ) + + +def test_python_backend_expands_brace_include_patterns(tmp_path, monkeypatch): + """The include examples are brace patterns, which the Python backend must expand. + + fnmatch has no brace support and ripgrep does, so without expansion the same + search returned files through ripgrep and nothing through the fallback. + """ + import openhands.tools.grep.impl as grep_impl + + monkeypatch.setattr(grep_impl, "_check_ripgrep_available", lambda: False) + monkeypatch.setattr(grep_impl, "_check_grep_available", lambda: False) + + for name in ("a.ts", "b.tsx", "c.js"): + (tmp_path / name).write_text("needle here\n", encoding="utf-8") + + executor = grep_impl.GrepExecutor(working_dir=str(tmp_path)) + assert executor._select_search_backend() == "python" + + observation = executor( + grep_impl.GrepAction(pattern="needle", path=str(tmp_path), include="*.{ts,tsx}") + ) + + found = sorted(Path(match).name for match in observation.matches) + assert found == ["a.ts", "b.tsx"]