MCPcopy Create free account
hub / github.com/Louisym/MiniCC / execute_grep

Function execute_grep

tutorials/03_tool_system.py:199–237  ·  view source on GitHub ↗

搜索文件内容(简化版)。 对应源码: rust/crates/runtime/src/file_ops.rs

(params: dict)

Source from the content-addressed store, hash-verified

197
198
199def execute_grep(params: dict) -> str:
200 """
201 搜索文件内容(简化版)。
202 对应源码: rust/crates/runtime/src/file_ops.rs
203 """
204 import re
205 pattern = params["pattern"]
206 search_path = params.get("path", ".")
207
208 matches = []
209 try:
210 if os.path.isfile(search_path):
211 files = [search_path]
212 else:
213 files = []
214 for root, dirs, filenames in os.walk(search_path):
215 for fname in filenames:
216 files.append(os.path.join(root, fname))
217 if len(files) > 100: # 限制搜索范围
218 break
219
220 for fpath in files[:50]:
221 try:
222 with open(fpath, "r", encoding="utf-8", errors="ignore") as f:
223 for line_no, line in enumerate(f, 1):
224 if re.search(pattern, line):
225 matches.append(f"{fpath}:{line_no}: {line.rstrip()}")
226 if len(matches) >= 20:
227 break
228 except (PermissionError, IsADirectoryError):
229 continue
230 if len(matches) >= 20:
231 break
232 except Exception as e:
233 return f"[error] {e}"
234
235 if not matches:
236 return f"No matches found for pattern: {pattern}"
237 return "\n".join(matches)
238
239
240# ============================================================

Callers

nothing calls this directly

Calls 2

appendMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected