This commit is contained in:
@@ -228,28 +228,40 @@ _handle_re = re.compile(r"\s+#\s*handle\s+\d+\s*$")
|
|||||||
def extract_rule_lines_from_chain_text(text: str) -> List[str]:
|
def extract_rule_lines_from_chain_text(text: str) -> List[str]:
|
||||||
"""
|
"""
|
||||||
Given output of `nft list chain fam table chain`, extract the rule lines as strings.
|
Given output of `nft list chain fam table chain`, extract the rule lines as strings.
|
||||||
Keeps the rule text as printed by nft (one rule per line), strips leading/trailing whitespace,
|
- Only consider indented lines (rules are indented inside the chain block).
|
||||||
and removes trailing '# handle N' fragments.
|
- Skip chain header metadata lines that typically end with ';' (e.g. "type ...; policy ...;").
|
||||||
|
- Skip closing brace lines ('}').
|
||||||
|
- Remove trailing '# handle N' fragments.
|
||||||
|
Returns cleaned rule strings like "ip protocol icmp drop".
|
||||||
"""
|
"""
|
||||||
lines: List[str] = []
|
lines: List[str] = []
|
||||||
if not text:
|
if not text:
|
||||||
return lines
|
return lines
|
||||||
|
|
||||||
for raw in text.splitlines():
|
for raw in text.splitlines():
|
||||||
line = raw.rstrip()
|
# preserve the original raw to check indentation
|
||||||
# skip chain/table header lines which typically start with "table " or "chain "
|
if raw is None:
|
||||||
if line.strip() == "":
|
|
||||||
continue
|
continue
|
||||||
if line.lstrip().startswith("table "):
|
# ignore empty lines
|
||||||
|
if raw.strip() == "":
|
||||||
continue
|
continue
|
||||||
if line.lstrip().startswith("chain "):
|
# ignore closing braces (possibly with indentation)
|
||||||
|
if raw.strip() == "}":
|
||||||
|
continue
|
||||||
|
# Only accept lines that are indented (start with whitespace).
|
||||||
|
# This filters out top-level "table ..." and "chain ..." header lines.
|
||||||
|
if not raw.startswith((" ", "\t")):
|
||||||
|
# not indented => likely header/footer, skip
|
||||||
|
continue
|
||||||
|
# Now we have an indented line. Remove leading whitespace to get the content.
|
||||||
|
line = raw.lstrip().rstrip()
|
||||||
|
# skip chain metadata lines that end with ';' (e.g. "type filter hook ...; policy accept;")
|
||||||
|
if line.endswith(";"):
|
||||||
continue
|
continue
|
||||||
# rule lines are indented (start with whitespace). Accept them if non-empty after stripping.
|
|
||||||
# Remove leading indentation:
|
|
||||||
stripped = line.lstrip()
|
|
||||||
# remove trailing " # handle N" if present
|
# remove trailing " # handle N" if present
|
||||||
stripped = _handle_re.sub("", stripped)
|
line = _handle_re.sub("", line).rstrip()
|
||||||
if stripped:
|
if line:
|
||||||
lines.append(stripped)
|
lines.append(line)
|
||||||
return lines
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user