Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions _msg.txt
Original file line number Diff line number Diff line change
@@ -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.
41 changes: 41 additions & 0 deletions _pr_body.md
Original file line number Diff line number Diff line change
@@ -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.
31 changes: 4 additions & 27 deletions openhands-tools/openhands/tools/glob/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]):
Expand Down
9 changes: 8 additions & 1 deletion openhands-tools/openhands/tools/grep/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
_check_grep_available,
_check_ripgrep_available,
_log_ripgrep_fallback_warning,
expand_braces,
)


Expand Down Expand Up @@ -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:
Expand Down
29 changes: 29 additions & 0 deletions openhands-tools/openhands/tools/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
]
25 changes: 25 additions & 0 deletions tests/tools/grep/test_grep_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Loading