prosberry/format-css.sh

77 lines
1.5 KiB
Bash
Executable File

#!/bin/bash
set -euo pipefail
css_file="css/style.css"
if [[ ! -f "$css_file" ]]; then
echo "error: $css_file not found" >&2
exit 1
fi
python3 - <<'PY'
from pathlib import Path
css_path = Path("css/style.css")
text = css_path.read_text()
output = []
token = []
indent = 0
idx = 0
length = len(text)
def flush_token():
if token:
joined = " ".join("".join(token).split())
token.clear()
return joined
return ""
while idx < length:
if text.startswith("/*", idx):
comment_end = text.find("*/", idx + 2)
if comment_end == -1:
comment_end = length - 2
comment = text[idx : comment_end + 2]
output.append(" " * (indent * 4) + comment.strip() + "\n")
idx = comment_end + 2
continue
c = text[idx]
if c.isspace():
idx += 1
continue
if c == "{":
selector = flush_token()
output.append(selector + " {\n")
indent += 1
idx += 1
continue
if c == "}":
pending = flush_token()
if pending:
output.append(" " * (indent * 4) + pending + "\n")
indent = max(0, indent - 1)
output.append(" " * (indent * 4) + "}\n\n")
idx += 1
continue
if c == ";":
property_block = flush_token()
if property_block:
output.append(" " * (indent * 4) + property_block + ";\n")
idx += 1
continue
token.append(c)
idx += 1
result = "".join(output).rstrip() + "\n"
css_path.write_text(result)
PY
echo "Formatted $css_file"