diff --git a/openhands-tools/openhands/tools/grep/impl.py b/openhands-tools/openhands/tools/grep/impl.py index 0d8b27bd029..34f3641fd04 100644 --- a/openhands-tools/openhands/tools/grep/impl.py +++ b/openhands-tools/openhands/tools/grep/impl.py @@ -1,9 +1,9 @@ """Grep tool executor implementation.""" -import fnmatch import os import re import subprocess +from functools import lru_cache from pathlib import Path from typing import TYPE_CHECKING @@ -24,6 +24,106 @@ logger = get_logger(__name__) +_BRACE_GROUP = re.compile(r"\{([^{}]*)\}") + + +def _expand_braces(pattern: str) -> list[str]: + """Expand `{a,b}` alternatives, including nested groups, into plain globs.""" + match = _BRACE_GROUP.search(pattern) + if match is None: + return [pattern] + expanded: list[str] = [] + for alternative in match.group(1).split(","): + expanded.extend( + _expand_braces( + pattern[: match.start()] + alternative + pattern[match.end() :] + ) + ) + return list(dict.fromkeys(expanded)) + + +def _character_class_end(pattern: str, start: int) -> int | None: + """Return the index of the `]` closing the class opened at `start`.""" + i = start + 1 + if i < len(pattern) and pattern[i] in "!^": + i += 1 + if i < len(pattern) and pattern[i] == "]": + i += 1 + while i < len(pattern) and pattern[i] != "]": + i += 1 + return i if i < len(pattern) else None + + +def _glob_to_regex(pattern: str) -> str: + """Translate a glob so `*` and `?` stay within one path segment. + + A `**` covering a whole path segment matches zero or more segments, which + mirrors how both ripgrep and gitignore treat globstar patterns. + """ + regex: list[str] = [] + i = 0 + while i < len(pattern): + char = pattern[i] + if char == "*": + star_start = i + while i < len(pattern) and pattern[i] == "*": + i += 1 + whole_segment = star_start == 0 or pattern[star_start - 1] == "/" + if i - star_start >= 2 and whole_segment and i == len(pattern): + regex.append(".*") + elif i - star_start >= 2 and whole_segment and pattern[i] == "/": + i += 1 + # `**/**/` matches the same paths as `**/`, and adjacent + # repetitions would otherwise backtrack catastrophically. + while pattern.startswith("**/", i): + i += 3 + regex.append("(?:[^/]*/)*") + else: + regex.append("[^/]*") + elif char == "?": + regex.append("[^/]") + i += 1 + elif char == "[": + end = _character_class_end(pattern, i) + if end is None: + regex.append(re.escape(char)) + i += 1 + else: + body = pattern[i + 1 : end] + if body.startswith("!"): + body = "^" + body[1:] + body = body.replace("\\", "\\\\") + regex.append(f"[{body}]") + i = end + 1 + else: + regex.append(re.escape(char)) + i += 1 + return "".join(regex) + + +@lru_cache(maxsize=256) +def _compile_include_patterns( + include_pattern: str, +) -> tuple[tuple[re.Pattern[str], bool], ...]: + """Compile an include pattern into (regex, match-against-full-path) pairs. + + Like ripgrep, globs containing a `/` are matched against the path relative + to the search root; globs without one are matched against the file name. + """ + return tuple( + (re.compile(_glob_to_regex(glob)), "/" in glob) + for glob in _expand_braces(include_pattern) + ) + + +def _include_pattern_matches(relative_path: str, include_pattern: str) -> bool: + filename = relative_path.rpartition("/")[2] + for regex, match_relative_path in _compile_include_patterns(include_pattern): + candidate = relative_path if match_relative_path else filename + if regex.fullmatch(candidate): + return True + return False + class GrepExecutor(ToolExecutor[GrepAction, GrepObservation]): """Executor for grep content search operations. @@ -161,7 +261,8 @@ def _path_matches_filters( filename = relative_parts[-1] if relative_parts else path.name if include_pattern: - return fnmatch.fnmatch(filename, include_pattern) + relative_path = "/".join(relative_parts) if relative_parts else path.name + return _include_pattern_matches(relative_path, include_pattern) return not filename.startswith(".") def _match_mtime(self, path: Path) -> float: @@ -240,6 +341,8 @@ def _execute_with_ripgrep( if action.include: cmd.extend(["-g", action.include]) + # ripgrep resolves path-bearing globs against its working directory, + # so run it from the search root to keep include patterns relative to it. result = subprocess.run( cmd, capture_output=True, @@ -247,6 +350,7 @@ def _execute_with_ripgrep( timeout=30, check=False, env=sanitized_env(), + cwd=search_path, ) if result.returncode not in (0, 1): logger.warning( diff --git a/tests/tools/grep/test_consistency.py b/tests/tools/grep/test_consistency.py index a3f610df4b5..d2d9571639b 100644 --- a/tests/tools/grep/test_consistency.py +++ b/tests/tools/grep/test_consistency.py @@ -175,6 +175,54 @@ def test_include_pattern_consistency(self, temp_dir_with_content): for match in ripgrep_matches: assert match.endswith(".py"), f"Non-Python file found: {match}" + def test_include_brace_pattern_consistency(self, temp_dir_with_content): + """Test that brace include patterns behave consistently across backends.""" + executor = GrepExecutor(temp_dir_with_content) + action = GrepAction(pattern="hello", include="*.{py,json}") + + ripgrep_result = executor._execute_with_ripgrep( + action, Path(temp_dir_with_content) + ) + python_result = executor._execute_with_python_search( + action, Path(temp_dir_with_content) + ) + + ripgrep_matches = set(ripgrep_result.matches) + python_matches = set(python_result.matches) + + assert ripgrep_matches == python_matches, ( + f"Ripgrep found: {ripgrep_matches}\n" + f"Python fallback found: {python_matches}\n" + ) + assert ripgrep_matches, "Expected brace include to match files" + for match in ripgrep_matches: + assert match.endswith((".py", ".json")), f"Unexpected file: {match}" + + def test_include_path_pattern_consistency(self, temp_dir_with_content): + """Test that path-bearing includes are resolved against the search root.""" + executor = GrepExecutor(temp_dir_with_content) + for include in ("src/*.py", "src/**/*.py"): + action = GrepAction(pattern="hello", include=include) + + ripgrep_result = executor._execute_with_ripgrep( + action, Path(temp_dir_with_content) + ) + python_result = executor._execute_with_python_search( + action, Path(temp_dir_with_content) + ) + + ripgrep_matches = set(ripgrep_result.matches) + python_matches = set(python_result.matches) + + assert ripgrep_matches == python_matches, ( + f"Include: {include}\n" + f"Ripgrep found: {ripgrep_matches}\n" + f"Python fallback found: {python_matches}\n" + ) + assert ripgrep_matches, f"Expected {include} to match files" + for match in ripgrep_matches: + assert "/src/" in Path(match).as_posix(), f"Unexpected file: {match}" + def test_no_matches_consistency(self, temp_dir_with_content): """Test that ripgrep and the Python fallback handle no matches consistently.""" executor = GrepExecutor(temp_dir_with_content) diff --git a/tests/tools/grep/test_grep_executor.py b/tests/tools/grep/test_grep_executor.py index 46c07232a8d..8475d7a48fe 100644 --- a/tests/tools/grep/test_grep_executor.py +++ b/tests/tools/grep/test_grep_executor.py @@ -13,7 +13,7 @@ import pytest import openhands.tools.grep.impl as grep_impl -from openhands.tools.grep import GrepAction +from openhands.tools.grep import GrepAction, GrepObservation from openhands.tools.grep.impl import GrepExecutor from openhands.tools.utils import _check_grep_available, _check_ripgrep_available @@ -177,6 +177,176 @@ def test_grep_executor_include_filter_still_skips_hidden_directories(): assert observation.matches == [str(visible.resolve())] +@pytest.fixture +def include_tree(tmp_path: Path) -> Path: + """Create a directory tree for include-pattern tests.""" + (tmp_path / "root.ts").write_text("needle") + (tmp_path / "other.tsx").write_text("needle") + (tmp_path / "notes.js").write_text("needle") + (tmp_path / "sub").mkdir() + (tmp_path / "sub" / "direct.ts").write_text("needle") + (tmp_path / "sub" / "deep").mkdir() + (tmp_path / "sub" / "deep" / "nested.ts").write_text("needle") + (tmp_path / ".hidden").mkdir() + (tmp_path / ".hidden" / "secret.ts").write_text("needle") + return tmp_path + + +def _matched_names(observation: GrepObservation, root: Path) -> list[str]: + paths = (Path(path).relative_to(root).as_posix() for path in observation.matches) + return sorted(paths) + + +def test_grep_executor_include_glob_without_braces(include_tree, monkeypatch): + """Existing single-suffix include behavior is unchanged.""" + monkeypatch.setattr(grep_impl, "_check_ripgrep_available", lambda: False) + monkeypatch.setattr(grep_impl, "_check_grep_available", lambda: False) + executor = GrepExecutor(working_dir=str(include_tree)) + + action = GrepAction(pattern="needle", include="*.ts") + observation = executor(action) + + assert observation.is_error is False + assert _matched_names(observation, include_tree) == [ + "root.ts", + "sub/deep/nested.ts", + "sub/direct.ts", + ] + + +def test_grep_executor_python_include_brace_glob(include_tree): + """Test that `*.{ts,tsx}` include patterns work in the Python fallback.""" + executor = GrepExecutor(working_dir=str(include_tree)) + action = GrepAction(pattern="needle", include="*.{ts,tsx}") + observation = executor._execute_with_python_search(action, include_tree) + + assert observation.is_error is False + assert _matched_names(observation, include_tree) == [ + "other.tsx", + "root.ts", + "sub/deep/nested.ts", + "sub/direct.ts", + ] + + +@pytest.mark.skipif(not _check_ripgrep_available(), reason="ripgrep not available") +def test_grep_executor_ripgrep_include_brace_glob(include_tree): + """Test that `*.{ts,tsx}` include patterns work in the ripgrep backend.""" + executor = GrepExecutor(working_dir=str(include_tree)) + action = GrepAction(pattern="needle", include="*.{ts,tsx}") + observation = executor._execute_with_ripgrep(action, include_tree) + + assert observation.is_error is False + assert _matched_names(observation, include_tree) == [ + "other.tsx", + "root.ts", + "sub/deep/nested.ts", + "sub/direct.ts", + ] + + +def test_grep_executor_python_include_path_patterns(include_tree): + """Test that includes with path separators match relative to the search root.""" + executor = GrepExecutor(working_dir=str(include_tree)) + + direct = executor._execute_with_python_search( + GrepAction(pattern="needle", include="sub/*.ts"), include_tree + ) + assert _matched_names(direct, include_tree) == ["sub/direct.ts"] + + recursive = executor._execute_with_python_search( + GrepAction(pattern="needle", include="**/*.ts"), include_tree + ) + assert _matched_names(recursive, include_tree) == [ + "root.ts", + "sub/deep/nested.ts", + "sub/direct.ts", + ] + + +@pytest.mark.skipif(not _check_grep_available(), reason="grep not available") +def test_grep_executor_system_grep_include_brace_glob(include_tree): + """Test that brace and path includes work in the system grep backend.""" + executor = GrepExecutor(working_dir=str(include_tree)) + + brace_action = GrepAction(pattern="needle", include="*.{ts,tsx}") + grep_observation = executor._execute_with_system_grep(brace_action, include_tree) + python_observation = executor._execute_with_python_search( + brace_action, include_tree + ) + assert set(grep_observation.matches) == set(python_observation.matches) + assert _matched_names(grep_observation, include_tree) == [ + "other.tsx", + "root.ts", + "sub/deep/nested.ts", + "sub/direct.ts", + ] + + path_action = GrepAction(pattern="needle", include="sub/*.ts") + grep_observation = executor._execute_with_system_grep(path_action, include_tree) + assert _matched_names(grep_observation, include_tree) == ["sub/direct.ts"] + + +@pytest.mark.skipif(not _check_ripgrep_available(), reason="ripgrep not available") +def test_grep_executor_ripgrep_include_path_patterns(include_tree): + """Test that ripgrep applies path-bearing includes relative to the search root.""" + executor = GrepExecutor(working_dir=str(include_tree)) + + direct = executor._execute_with_ripgrep( + GrepAction(pattern="needle", include="sub/*.ts"), include_tree + ) + assert _matched_names(direct, include_tree) == ["sub/direct.ts"] + + recursive = executor._execute_with_ripgrep( + GrepAction(pattern="needle", include="**/*.ts"), include_tree + ) + assert _matched_names(recursive, include_tree) == [ + "root.ts", + "sub/deep/nested.ts", + "sub/direct.ts", + ] + + +def test_grep_executor_include_repeated_globstar_segments_is_fast(tmp_path: Path): + """Adjacent `**/` segments must not cause catastrophic regex backtracking.""" + deep_dir = tmp_path + for level in range(14): + deep_dir = deep_dir / f"level{level}" + deep_dir.mkdir(parents=True) + (deep_dir / "deep.ts").write_text("needle") + + executor = GrepExecutor(working_dir=str(tmp_path)) + include = "**/" * 20 + + start = time.monotonic() + matching = executor._execute_with_python_search( + GrepAction(pattern="needle", include=include + "*.ts"), tmp_path + ) + non_matching = executor._execute_with_python_search( + GrepAction(pattern="needle", include=include + "*.zzz"), tmp_path + ) + elapsed = time.monotonic() - start + + expected = "/".join(f"level{level}" for level in range(14)) + "/deep.ts" + assert _matched_names(matching, tmp_path) == [expected] + assert non_matching.matches == [] + assert elapsed < 1.0 + + +def test_grep_executor_include_brace_glob_without_matches(include_tree, monkeypatch): + """A brace include that matches nothing still reports a filtered empty result.""" + monkeypatch.setattr(grep_impl, "_check_ripgrep_available", lambda: False) + monkeypatch.setattr(grep_impl, "_check_grep_available", lambda: False) + executor = GrepExecutor(working_dir=str(include_tree)) + + observation = executor(GrepAction(pattern="needle", include="*.{md,mdx}")) + + assert observation.is_error is False + assert observation.matches == [] + assert "No files found" in observation.text + assert "(filtered by '*.{md,mdx}')" in observation.text + + @pytest.mark.skipif(not _check_grep_available(), reason="grep not available") def test_grep_executor_system_grep_matches_python_fallback_for_hidden_include(): with tempfile.TemporaryDirectory() as temp_dir: diff --git a/tests/tools/grep/test_grep_tool.py b/tests/tools/grep/test_grep_tool.py index 930d13c28d3..a3507b7ba4b 100644 --- a/tests/tools/grep/test_grep_tool.py +++ b/tests/tools/grep/test_grep_tool.py @@ -114,6 +114,26 @@ def test_grep_tool_include_filter(): assert observation.matches[0].endswith(".py") +def test_grep_tool_include_brace_glob(): + """Test the documented `*.{ts,tsx}` include example.""" + with tempfile.TemporaryDirectory() as temp_dir: + (Path(temp_dir) / "app.ts").write_text("print('hello')") + (Path(temp_dir) / "app.tsx").write_text("print('hello')") + (Path(temp_dir) / "app.js").write_text("print('hello')") + + conv_state = _create_test_conv_state(temp_dir) + tools = GrepTool.create(conv_state) + tool = tools[0] + + action = GrepAction(pattern="print", include="*.{ts,tsx}") + assert tool.executor is not None + observation = tool.executor(action) + + assert observation.is_error is False + assert len(observation.matches) == 2 + assert all(match.endswith((".ts", ".tsx")) for match in observation.matches) + + def test_grep_tool_specific_directory(): """Test searching in specific directory.""" with tempfile.TemporaryDirectory() as temp_dir: