The TreeContext class is the core engine for AST-based searching. It takes a filename and the file's source code to build a context that can be queried for lines of interest.
Initialization:
TreeContext(filename, code, color=False, verbose=False, line_number=False)
Workflow:
- Initialize
TreeContext with the file path and content. - Call
.grep(pattern, ignore_case=False) to find lines of interest. - If matches are found, call
.add_lines_of_interest(loi). - Call
.add_context() to expand the context around the matches. - Call
.format() to get the final string representation of the search results.
from grep_ast.grep_ast import TreeContext
filename = "example.py"
code = "def hello():\n print('world')"
tc = TreeContext(filename, code, color=True, line_number=True)
loi = tc.grep("hello", ignore_case=False)
if loi:
tc.add_lines_of_interest(loi)
tc.add_context()
print(tc.format())