Skip to content

Commit

Permalink
Avoid applying filtering inside of quoted strings.
Browse files Browse the repository at this point in the history
  - If a string is quoted, don't treat | as a filter command.
  - Handles and matches both " and '.

Fixes #177
  • Loading branch information
terjekv committed Nov 28, 2023
1 parent f110351 commit a765c85
Showing 1 changed file with 40 additions and 10 deletions.
50 changes: 40 additions & 10 deletions mreg_cli/outputmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,28 +80,58 @@ def add_formatted_line_with_source(

# We want to use re.Pattern as the type here, but python 3.6 and older re-modules
# don't have that type. So we use Any instead.
def _find_split_index(self, command: str) -> int:
"""Finds the index to split the command for filtering.
It handles both single and double quotes, ensuring that the split
occurs outside of any quoted sections.
:param command: The command string to be processed.
:return: The index at which to split the command, or -1 if not found.
"""
in_quotes = False
current_quote = None

for i, char in enumerate(command):
if char in ["'", '"']:
if in_quotes and char == current_quote:
in_quotes = False
current_quote = None
elif not in_quotes:
in_quotes = True
current_quote = char
elif char == "|" and not in_quotes:
return i

return -1

def get_filter(self, command: str) -> Tuple[str, Any, bool]:
"""Returns the filter for the output.
:param command: The command to parse for the filter.
Parses the command string and extracts a filter if present, taking into
account both single and double quoted strings to avoid incorrect
splitting.
:param command: The command to parse for the filter.
:return: The filter and whether it is a negated filter.
"""
self.command = command
negate = False
filter_re = None

if command and "|" in command:
command, filter_str = command.split("|", 1)
filter_str = filter_str.strip()
if command:
split_index = self._find_split_index(command)

if split_index != -1:
filter_str = command[split_index + 1 :].strip()
command = command[:split_index].strip()

if filter_str.startswith("!"):
negate = True
filter_str = filter_str[1:].strip()
if filter_str.startswith("!"):
negate = True
filter_str = filter_str[1:].strip()

filter_re = re.compile(filter_str)
filter_re = re.compile(filter_str)

return (command, filter_re, negate)
return command, filter_re, negate

def lines(self) -> List[str]:
"""Return the lines of output.
Expand Down

0 comments on commit a765c85

Please sign in to comment.