Skip to content

Commit

Permalink
Working first pass at experimental 'grep'
Browse files Browse the repository at this point in the history
  • Loading branch information
ktbyers committed Oct 1, 2024
1 parent 5dc95ce commit 9633c7f
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion netmiko/cli_tools/outputters.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ def output_text(results, pattern=None):

for device_name, output in results.items():
if pattern:
output = highlight_regex(output, pattern)
# output = highlight_regex(output, pattern)
output = highlight_regex_with_context(output, pattern)
else:
output = Text(output)

Expand Down Expand Up @@ -162,6 +163,40 @@ def highlight_regex(text, pattern, highlight_color="red"):
return text_obj


def highlight_regex_with_context(text, pattern, highlight_color="red", context_lines=2):
"""
Highlight text matching a regex pattern using Rich, showing only the matching lines
with a specified number of context lines before and after.
"""
lines = text.split("\n")
text_obj = Text()
pattern = re.compile(pattern)

for i, line in enumerate(lines):
if pattern.search(line):
# Add context lines before
start = max(0, i - context_lines)
for j in range(start, i):
text_obj.append(lines[j] + "\n")

# Add the matching line with highlighting
line_obj = Text(line + "\n")
for match in pattern.finditer(line):
line_obj.stylize(highlight_color, match.start(), match.end())
text_obj.append(line_obj)

# Add context lines after
end = min(len(lines), i + context_lines + 1)
for j in range(i + 1, end):
text_obj.append(lines[j] + "\n")

# Add a separator if this isn't the last match
if i + context_lines + 1 < len(lines):
text_obj.append("...\n\n")

return text_obj


def output_dispatcher(out_format, results, pattern=None):

# Sort the results dictionary by device_name
Expand Down

0 comments on commit 9633c7f

Please sign in to comment.