349 lines
11 KiB
Python
349 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Remove comments and docstrings only, preserving all other source text.
|
|
|
|
This is the minimal-surface-change counterpart to ``obfuscator_v2.py``. It
|
|
does **not** rename identifiers, rewrite imports, generalise routes/templates,
|
|
or replace string literals. The output differs from the input only by:
|
|
|
|
* removed ``#`` comments;
|
|
* removed module/class/function docstrings.
|
|
|
|
Formatting, identifiers, string values, routes, and template paths are kept
|
|
byte-for-byte wherever possible. Removed docstrings are replaced with blank
|
|
lines so line numbers stay stable.
|
|
|
|
Usage:
|
|
python3 obfuscator_comments_only.py
|
|
python3 obfuscator_comments_only.py -i Samples -o Samples_CommentsRemoved
|
|
python3 obfuscator_comments_only.py --report validation/comments_removed_report.json
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import ast
|
|
import io
|
|
import json
|
|
import sys
|
|
import tokenize
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Source positions and token signatures
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _newline(line: str) -> str:
|
|
if line.endswith("\r\n"):
|
|
return "\r\n"
|
|
if line.endswith("\n"):
|
|
return "\n"
|
|
if line.endswith("\r"):
|
|
return "\r"
|
|
return ""
|
|
|
|
|
|
def _line_starts(text: str) -> list[int]:
|
|
starts: list[int] = []
|
|
offset = 0
|
|
for line in text.splitlines(keepends=True):
|
|
starts.append(offset)
|
|
offset += len(line)
|
|
return starts
|
|
|
|
|
|
def _is_constant_string(node: ast.AST) -> bool:
|
|
return isinstance(node, ast.Constant) and isinstance(node.value, str)
|
|
|
|
|
|
def collect_docstrings(tree: ast.AST) -> list[tuple[ast.Expr, ast.AST]]:
|
|
"""Return (docstring expression, enclosing scope) pairs."""
|
|
found: list[tuple[ast.Expr, ast.AST]] = []
|
|
for node in ast.walk(tree):
|
|
if not isinstance(
|
|
node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
|
|
):
|
|
continue
|
|
if not node.body:
|
|
continue
|
|
first = node.body[0]
|
|
if isinstance(first, ast.Expr) and _is_constant_string(first.value):
|
|
found.append((first, node))
|
|
return found
|
|
|
|
|
|
def _position_less(left: tuple[int, int], right: tuple[int, int]) -> bool:
|
|
return left[0] < right[0] or (left[0] == right[0] and left[1] < right[1])
|
|
|
|
|
|
def _position_in_span(
|
|
position: tuple[int, int], span: tuple[tuple[int, int], tuple[int, int]]
|
|
) -> bool:
|
|
start, end = span
|
|
return not _position_less(position, start) and _position_less(position, end)
|
|
|
|
|
|
def _token_signature(
|
|
source: str,
|
|
doc_spans: list[tuple[tuple[int, int], tuple[int, int]]] | None = None,
|
|
) -> list[tuple[int, str]]:
|
|
"""Return all code tokens, dropping comments, layout, and docstrings."""
|
|
doc_spans = doc_spans or []
|
|
ignored = {
|
|
tokenize.COMMENT,
|
|
tokenize.NL,
|
|
tokenize.NEWLINE,
|
|
tokenize.INDENT,
|
|
tokenize.DEDENT,
|
|
tokenize.ENDMARKER,
|
|
tokenize.ENCODING,
|
|
}
|
|
signature: list[tuple[int, str]] = []
|
|
for token in tokenize.generate_tokens(io.StringIO(source).readline):
|
|
if token.type in ignored:
|
|
continue
|
|
if token.type == tokenize.STRING and any(
|
|
_position_in_span(token.start, span) for span in doc_spans
|
|
):
|
|
continue
|
|
signature.append((token.type, token.string))
|
|
return signature
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Transformations
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def strip_comments(source: str) -> tuple[str, int]:
|
|
"""Remove every COMMENT token while preserving line count and layout."""
|
|
comments: dict[int, int] = {}
|
|
for token in tokenize.generate_tokens(io.StringIO(source).readline):
|
|
if token.type == tokenize.COMMENT:
|
|
comments[token.start[0]] = token.start[1]
|
|
|
|
lines = source.splitlines(keepends=True)
|
|
output: list[str] = []
|
|
for lineno, line in enumerate(lines, start=1):
|
|
comment_col = comments.get(lineno)
|
|
if comment_col is None:
|
|
output.append(line)
|
|
continue
|
|
|
|
prefix = line[:comment_col]
|
|
newline = _newline(line)
|
|
if prefix.strip():
|
|
output.append(prefix.rstrip() + newline)
|
|
else:
|
|
output.append(newline)
|
|
|
|
return "".join(output), len(comments)
|
|
|
|
|
|
def strip_docstrings(source: str) -> tuple[str, int]:
|
|
"""Remove module/class/function docstrings while preserving line count."""
|
|
tree = ast.parse(source)
|
|
docstrings = collect_docstrings(tree)
|
|
if not docstrings:
|
|
return source, 0
|
|
|
|
starts = _line_starts(source)
|
|
lines = source.splitlines(keepends=True)
|
|
replacements: list[tuple[int, int, str]] = []
|
|
|
|
for node, parent in docstrings:
|
|
start = starts[node.lineno - 1] + node.col_offset
|
|
end = starts[node.end_lineno - 1] + node.end_col_offset
|
|
|
|
first_line = lines[node.lineno - 1]
|
|
last_line = lines[node.end_lineno - 1]
|
|
prefix = first_line[: node.col_offset]
|
|
suffix = last_line[node.end_col_offset :]
|
|
standalone = not prefix.strip() and not suffix.strip()
|
|
line_count = node.end_lineno - node.lineno + 1
|
|
newline = _newline(first_line) or "\n"
|
|
|
|
if standalone:
|
|
# Keep the line count stable by replacing the docstring lines with
|
|
# blank lines. A scope whose body was only a docstring would become
|
|
# invalid, so use ``pass`` there.
|
|
if isinstance(
|
|
parent, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
|
|
) and len(parent.body) == 1:
|
|
replacement = prefix + "pass" + newline + newline * (line_count - 1)
|
|
else:
|
|
replacement = newline * line_count
|
|
else:
|
|
# Rare inline docstring: replace the expression with a no-op.
|
|
replacement = "pass"
|
|
|
|
replacements.append((start, end, replacement))
|
|
|
|
# Apply from the end so earlier offsets remain valid.
|
|
for start, end, replacement in sorted(replacements, reverse=True):
|
|
source = source[:start] + replacement + source[end:]
|
|
|
|
return source, len(docstrings)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Verification
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def verify_output(
|
|
source_code: str,
|
|
output_code: str,
|
|
original_doc_spans: list[tuple[tuple[int, int], tuple[int, int]]],
|
|
) -> list[str]:
|
|
errors: list[str] = []
|
|
|
|
try:
|
|
output_tree = ast.parse(output_code)
|
|
compile(output_code, "<comments-only>", "exec")
|
|
except (SyntaxError, ValueError) as exc:
|
|
return [f"does not parse/compile: {exc}"]
|
|
|
|
if collect_docstrings(output_tree):
|
|
errors.append("output still contains a docstring")
|
|
|
|
if any(
|
|
token.type == tokenize.COMMENT
|
|
for token in tokenize.generate_tokens(io.StringIO(output_code).readline)
|
|
):
|
|
errors.append("output still contains a comment")
|
|
|
|
original_tokens = _token_signature(source_code, original_doc_spans)
|
|
output_tokens = _token_signature(output_code)
|
|
if original_tokens != output_tokens:
|
|
errors.append("code tokens changed beyond comments/docstrings")
|
|
|
|
return errors
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Directory driver
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@dataclass
|
|
class FileResult:
|
|
file: str
|
|
comments_removed: int
|
|
docstrings_removed: int
|
|
bytes_before: int
|
|
bytes_after: int
|
|
|
|
|
|
def process_directory(input_dir: Path, output_dir: Path, report_path: Path | None) -> int:
|
|
if not input_dir.is_dir():
|
|
print(f"error: input directory not found: {input_dir}", file=sys.stderr)
|
|
return 2
|
|
if input_dir.resolve() == output_dir.resolve():
|
|
print("error: input and output directories must differ", file=sys.stderr)
|
|
return 2
|
|
|
|
sources = sorted(input_dir.glob("*.py"))
|
|
if not sources:
|
|
print(f"error: no .py files found in {input_dir}", file=sys.stderr)
|
|
return 2
|
|
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
report: list[dict[str, object]] = []
|
|
errors: list[str] = []
|
|
|
|
total_comments = 0
|
|
total_docstrings = 0
|
|
|
|
for source_path in sources:
|
|
source_code = source_path.read_text(encoding="utf-8")
|
|
tree = ast.parse(source_code)
|
|
original_doc_spans = [
|
|
(
|
|
(node.lineno, node.col_offset),
|
|
(node.end_lineno, node.end_col_offset),
|
|
)
|
|
for node, _ in collect_docstrings(tree)
|
|
]
|
|
|
|
without_comments, comments_removed = strip_comments(source_code)
|
|
output_code, docstrings_removed = strip_docstrings(without_comments)
|
|
|
|
problems = verify_output(
|
|
source_code, output_code, original_doc_spans
|
|
)
|
|
if problems:
|
|
errors.extend(f"{source_path.name}: {problem}" for problem in problems)
|
|
continue
|
|
|
|
destination = output_dir / source_path.name
|
|
destination.write_text(output_code, encoding="utf-8")
|
|
total_comments += comments_removed
|
|
total_docstrings += docstrings_removed
|
|
report.append(
|
|
{
|
|
"file": source_path.name,
|
|
"comments_removed": comments_removed,
|
|
"docstrings_removed": docstrings_removed,
|
|
"bytes_before": len(source_code.encode("utf-8")),
|
|
"bytes_after": len(output_code.encode("utf-8")),
|
|
}
|
|
)
|
|
|
|
print(f"Input: {input_dir}")
|
|
print(f"Output: {output_dir}")
|
|
print(f"Files: {len(report)}/{len(sources)} written")
|
|
print(f" comments removed: {total_comments}")
|
|
print(f" docstrings removed: {total_docstrings}")
|
|
|
|
if report_path is not None:
|
|
report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
|
print(f"Report: {report_path}")
|
|
|
|
if errors:
|
|
print("\nVerification errors:", file=sys.stderr)
|
|
for error in errors:
|
|
print(f" - {error}", file=sys.stderr)
|
|
return 1
|
|
|
|
print(
|
|
"Verification: all outputs compile; no comments or docstrings remain; "
|
|
"all other code tokens are unchanged."
|
|
)
|
|
return 0
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
base_dir = Path(__file__).resolve().parent
|
|
parser = argparse.ArgumentParser(
|
|
description="Remove only comments and docstrings from Python samples.",
|
|
)
|
|
parser.add_argument(
|
|
"-i",
|
|
"--input",
|
|
type=Path,
|
|
default=base_dir / "Samples",
|
|
help="directory containing the original .py files (default: <script>/Samples)",
|
|
)
|
|
parser.add_argument(
|
|
"-o",
|
|
"--output",
|
|
type=Path,
|
|
default=base_dir / "Samples_CommentsRemoved",
|
|
help="directory for stripped files (default: <script>/Samples_CommentsRemoved)",
|
|
)
|
|
parser.add_argument(
|
|
"--report",
|
|
type=Path,
|
|
default=None,
|
|
help="optional JSON file with per-file transformation statistics",
|
|
)
|
|
args = parser.parse_args(argv)
|
|
return process_directory(args.input, args.output, args.report)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|