| 1 |
#!/usr/bin/env python3 |
| 2 |
"""CSS validator: checks brace balance and detects truncated rules.""" |
| 3 |
import re |
| 4 |
import sys |
| 5 |
|
| 6 |
|
| 7 |
def validate(path: str) -> list[str]: |
| 8 |
errors = [] |
| 9 |
source = open(path, encoding="utf-8").read() |
| 10 |
|
| 11 |
# Strip comments and string literals before counting |
| 12 |
clean = re.sub(r"/\*.*?\*/", "", source, flags=re.DOTALL) |
| 13 |
clean = re.sub(r'"[^"]*"|\'[^\']*\'', "", clean) |
| 14 |
|
| 15 |
opens = clean.count("{") |
| 16 |
closes = clean.count("}") |
| 17 |
if opens != closes: |
| 18 |
errors.append(f"unbalanced braces: {opens} '{{' vs {closes} '}}'") |
| 19 |
|
| 20 |
# Detect rules without a closing brace (selector line immediately followed |
| 21 |
# by another selector or end-of-file without a matching }) |
| 22 |
# Simple heuristic: find { not followed eventually by } |
| 23 |
depth = 0 |
| 24 |
for i, ch in enumerate(clean): |
| 25 |
if ch == "{": |
| 26 |
depth += 1 |
| 27 |
elif ch == "}": |
| 28 |
depth -= 1 |
| 29 |
if depth < 0: |
| 30 |
line = clean[:i].count("\n") + 1 |
| 31 |
errors.append(f"unexpected '}}' at line {line}") |
| 32 |
depth = 0 |
| 33 |
|
| 34 |
if depth != 0: |
| 35 |
errors.append(f"unclosed rule block (depth={depth} at end of file)") |
| 36 |
|
| 37 |
return errors |
| 38 |
|
| 39 |
|
| 40 |
def main() -> int: |
| 41 |
ok = True |
| 42 |
for path in sys.argv[1:]: |
| 43 |
errs = validate(path) |
| 44 |
if errs: |
| 45 |
for e in errs: |
| 46 |
print(f"{path}: {e}") |
| 47 |
ok = False |
| 48 |
else: |
| 49 |
print(f"{path}: OK") |
| 50 |
return 0 if ok else 1 |
| 51 |
|
| 52 |
|
| 53 |
if __name__ == "__main__": |
| 54 |
sys.exit(main()) |