Skip to content

Commit a765c85

Browse files
committed
Avoid applying filtering inside of quoted strings.
- If a string is quoted, don't treat | as a filter command. - Handles and matches both " and '. Fixes #177
1 parent f110351 commit a765c85

File tree

1 file changed

+40
-10
lines changed

1 file changed

+40
-10
lines changed

mreg_cli/outputmanager.py

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -80,28 +80,58 @@ def add_formatted_line_with_source(
8080

8181
# We want to use re.Pattern as the type here, but python 3.6 and older re-modules
8282
# don't have that type. So we use Any instead.
83+
def _find_split_index(self, command: str) -> int:
84+
"""Finds the index to split the command for filtering.
85+
86+
It handles both single and double quotes, ensuring that the split
87+
occurs outside of any quoted sections.
88+
89+
:param command: The command string to be processed.
90+
:return: The index at which to split the command, or -1 if not found.
91+
"""
92+
in_quotes = False
93+
current_quote = None
94+
95+
for i, char in enumerate(command):
96+
if char in ["'", '"']:
97+
if in_quotes and char == current_quote:
98+
in_quotes = False
99+
current_quote = None
100+
elif not in_quotes:
101+
in_quotes = True
102+
current_quote = char
103+
elif char == "|" and not in_quotes:
104+
return i
105+
106+
return -1
107+
83108
def get_filter(self, command: str) -> Tuple[str, Any, bool]:
84109
"""Returns the filter for the output.
85110
86-
:param command: The command to parse for the filter.
111+
Parses the command string and extracts a filter if present, taking into
112+
account both single and double quoted strings to avoid incorrect
113+
splitting.
87114
115+
:param command: The command to parse for the filter.
88116
:return: The filter and whether it is a negated filter.
89117
"""
90-
self.command = command
91118
negate = False
92119
filter_re = None
93120

94-
if command and "|" in command:
95-
command, filter_str = command.split("|", 1)
96-
filter_str = filter_str.strip()
121+
if command:
122+
split_index = self._find_split_index(command)
123+
124+
if split_index != -1:
125+
filter_str = command[split_index + 1 :].strip()
126+
command = command[:split_index].strip()
97127

98-
if filter_str.startswith("!"):
99-
negate = True
100-
filter_str = filter_str[1:].strip()
128+
if filter_str.startswith("!"):
129+
negate = True
130+
filter_str = filter_str[1:].strip()
101131

102-
filter_re = re.compile(filter_str)
132+
filter_re = re.compile(filter_str)
103133

104-
return (command, filter_re, negate)
134+
return command, filter_re, negate
105135

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

0 commit comments

Comments
 (0)