Files
Hunt-AI/Modules/search_for_word.py

57 lines
2.1 KiB
Python

import os
import ast
from colorama import Fore, Style
from Modules.submenu import build_submenu
def search_for_word_in_file(file_path, search_term):
"""
Searches for a word in the titles and content of functions in a specified file.
Returns a list of matching results with the file name.
"""
results = []
with open(file_path, "r") as file:
try:
tree = ast.parse(file.read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef): # Look for function definitions
for child in ast.iter_child_nodes(node):
if isinstance(child, ast.Expr) and isinstance(child.value, ast.Str):
# Extract docstring or title-like expressions
docstring = child.value.s
if search_term.lower() in docstring.lower():
results.append(f"{file_path} -> {node.name}: {docstring.strip()}")
except Exception as e:
print(f"Error reading {file_path}: {e}")
return results
def search_for_word_in_directory(directory, search_term):
"""
Searches through all `.py` files in a directory for a specific term.
"""
matches = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".py"):
file_path = os.path.join(root, file)
matches.extend(search_for_word_in_file(file_path, search_term))
return matches
def create_search_submenu(search_results):
"""
Creates a dynamic submenu for search results.
"""
actions = {}
for idx, result in enumerate(search_results, start=1):
file_name, function_info = result.split(" -> ", 1)
actions[str(idx)] = {
"description": f"{file_name}: {function_info.split(':')[0]}",
"function": lambda: print(f"\nViewing: {result}\n"), # Placeholder action
}
actions["ALL"] = {
"description": "Display All Results",
"function": lambda: print("\n".join(search_results))
}
build_submenu("Search Results", actions)