48 lines
1.8 KiB
Python
48 lines
1.8 KiB
Python
# .agent/tools/grep_project.py
|
|
import os
|
|
import sys
|
|
import pathspec
|
|
|
|
def search_in_files(keyword, start_path='.', gitignore_file='.gitignore'):
|
|
"""Busca string em arquivos de texto, ignorando binários e .gitignore."""
|
|
|
|
patterns = ['.git', '.agent', '__pycache__', 'node_modules', 'venv', '.idea', '.vscode', '*.png', '*.jpg', '*.exe']
|
|
if os.path.exists(gitignore_file):
|
|
with open(gitignore_file, 'r', encoding='utf-8') as f:
|
|
patterns.extend(f.read().splitlines())
|
|
|
|
spec = pathspec.PathSpec.from_lines('gitwildmatch', patterns)
|
|
results = []
|
|
|
|
print(f"🔍 Buscando por: '{keyword}'...")
|
|
|
|
for root, dirs, files in os.walk(start_path):
|
|
dirs[:] = [d for d in dirs if not spec.match_file(os.path.join(root, d))]
|
|
|
|
for file in files:
|
|
file_path = os.path.join(root, file)
|
|
if spec.match_file(file_path): continue
|
|
|
|
try:
|
|
# Tenta ler como utf-8, ignora se for binário
|
|
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
|
|
lines = f.readlines()
|
|
for i, line in enumerate(lines):
|
|
if keyword in line:
|
|
# Corta linhas muito longas (minified files)
|
|
content = line.strip()[:150]
|
|
results.append(f"{file_path}:{i+1} -> {content}")
|
|
except Exception:
|
|
continue
|
|
|
|
if not results:
|
|
return "❌ Nenhuma ocorrência encontrada."
|
|
|
|
return "\n".join(results[:100]) # Limita a 100 resultados para não estourar o contexto
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print("Uso: python grep_project.py 'termo'")
|
|
else:
|
|
term = " ".join(sys.argv[1:])
|
|
print(search_in_files(term)) |