📦 deps(playbook): sync playbook snapshot

This commit is contained in:
csh
2026-02-02 10:51:41 +08:00
192 changed files with 109197 additions and 135276 deletions
@@ -0,0 +1,210 @@
#!/usr/bin/env python3
from __future__ import annotations
import json
import os
import pathlib
import re
import subprocess
import sys
from typing import Dict, List, Optional, Tuple
def _eprint(*args: object) -> None:
print(*args, file=sys.stderr)
def _git(*args: str) -> str:
return subprocess.check_output(["git", *args], text=True).strip()
def _repo_root() -> pathlib.Path:
return pathlib.Path(_git("rev-parse", "--show-toplevel"))
def _find_commit_spec(root: pathlib.Path) -> pathlib.Path:
candidates = [
root / "docs" / "common" / "commit_message.md",
root / "docs" / "standards" / "playbook" / "docs" / "common" / "commit_message.md",
]
for path in candidates:
if path.is_file():
return path
raise FileNotFoundError(
"commit_message.md not found; expected one of:\n"
+ "\n".join(f"- {p}" for p in candidates)
)
def _parse_type_emoji_mapping(md_text: str) -> Dict[str, str]:
mapping: Dict[str, str] = {}
for raw_line in md_text.splitlines():
line = raw_line.strip()
if not (line.startswith("|") and line.endswith("|")):
continue
if "type" in line and "emoji" in line:
continue
if re.fullmatch(r"\|\s*-+\s*(\|\s*-+\s*)+\|", line):
continue
cols = [c.strip() for c in line.strip("|").split("|")]
if len(cols) < 2:
continue
m_type = re.search(r"`([^`]+)`", cols[0])
m_emoji = re.search(r"`(:[^`]+:)`", cols[1])
if not m_type or not m_emoji:
continue
type_name = m_type.group(1).strip()
emoji_code = m_emoji.group(1).strip()
mapping[type_name] = emoji_code
if not mapping:
raise ValueError("failed to parse type/emoji mapping from commit_message.md")
return mapping
def _validate_subject_line(
line: str,
mapping: Dict[str, str],
*,
require_emoji: bool,
) -> Optional[str]:
subject = line.strip()
if not subject:
return "empty subject"
m = re.match(
r"^(?:(?P<emoji>:[a-z0-9_+-]+:)\s+)?"
r"(?P<type>[a-z]+)"
r"(?P<scope>\([a-z0-9_]+\))?"
r":\s+(?P<text>.+)$",
subject,
)
if not m:
return "does not match ':emoji: type(scope): subject' or 'type(scope): subject'"
emoji = m.group("emoji")
type_name = m.group("type")
text = (m.group("text") or "").rstrip()
if type_name not in mapping:
return f"unknown type: {type_name}"
if emoji:
expected = mapping[type_name]
if emoji != expected:
return f"emoji/type mismatch: got {emoji} {type_name}, expected {expected} for type {type_name}"
elif require_emoji:
return "missing emoji (set COMMIT_LINT_REQUIRE_EMOJI=0 to allow)"
if text.endswith((".", "")):
return "subject should not end with a period"
return None
def _load_event_payload() -> Tuple[str, Optional[dict]]:
event_name = os.getenv("GITHUB_EVENT_NAME") or os.getenv("GITEA_EVENT_NAME") or ""
event_path = os.getenv("GITHUB_EVENT_PATH") or os.getenv("GITEA_EVENT_PATH") or ""
if not event_path:
return event_name, None
path = pathlib.Path(event_path)
if not path.is_file():
return event_name, None
try:
return event_name, json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
_eprint(f"WARN: failed to parse event payload: {path} ({exc})")
return event_name, None
def _gather_subjects(event_name: str, payload: Optional[dict]) -> List[Tuple[str, str]]:
subjects: List[Tuple[str, str]] = []
if isinstance(payload, dict):
if event_name.startswith("pull_request"):
pr = payload.get("pull_request")
if isinstance(pr, dict):
title = (pr.get("title") or "").strip()
if title:
subjects.append(("pull_request.title", title.splitlines()[0].strip()))
if event_name == "push":
commits = payload.get("commits")
if isinstance(commits, list):
for commit in commits:
if not isinstance(commit, dict):
continue
msg = (commit.get("message") or "").strip()
if not msg:
continue
subject = msg.splitlines()[0].strip()
sha = commit.get("id") or commit.get("sha") or ""
label = f"push.commit {sha[:7]}" if sha else "push.commit"
subjects.append((label, subject))
if subjects:
return subjects
try:
subjects.append(("HEAD", _git("log", "-1", "--format=%s", "HEAD")))
except Exception:
pass
return subjects
def main() -> int:
try:
root = _repo_root()
except Exception as exc:
_eprint(f"ERROR: not a git repository: {exc}")
return 2
os.chdir(root)
require_emoji = os.getenv("COMMIT_LINT_REQUIRE_EMOJI", "1") not in ("0", "false", "False")
try:
spec_path = _find_commit_spec(root)
except FileNotFoundError as exc:
_eprint(f"ERROR: {exc}")
return 2
try:
mapping = _parse_type_emoji_mapping(spec_path.read_text(encoding="utf-8"))
except Exception as exc:
_eprint(f"ERROR: failed to read/parse {spec_path}: {exc}")
return 2
event_name, payload = _load_event_payload()
subjects = _gather_subjects(event_name, payload)
print(f"commit spec: {spec_path}")
if event_name:
print(f"event: {event_name}")
print(f"require emoji: {require_emoji}")
print(f"checks: {len(subjects)} subject(s)")
errors: List[str] = []
for label, subject in subjects:
err = _validate_subject_line(subject, mapping, require_emoji=require_emoji)
if err:
errors.append(f"- {label}: {err}\n subject: {subject}")
if errors:
_eprint("ERROR: commit message lint failed:")
for item in errors:
_eprint(item)
return 1
print("OK")
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,128 @@
#!/usr/bin/env bash
set -euo pipefail
REPO_DIR="${REPO_DIR:-$(pwd)}"
SUPERPOWERS_BRANCH="${SUPERPOWERS_BRANCH:-thirdparty/skill}"
SUPERPOWERS_DIR="${SUPERPOWERS_DIR:-superpowers}"
SUPERPOWERS_LIST="${SUPERPOWERS_LIST:-codex/skills/.sources/superpowers.list}"
TARGET_BRANCH="${TARGET_BRANCH:-main}"
COMMIT_AUTHOR_NAME="${COMMIT_AUTHOR_NAME:-playbook-bot}"
COMMIT_AUTHOR_EMAIL="${COMMIT_AUTHOR_EMAIL:-playbook-bot@local}"
cd "$REPO_DIR"
git config user.name "$COMMIT_AUTHOR_NAME"
git config user.email "$COMMIT_AUTHOR_EMAIL"
git fetch origin "$SUPERPOWERS_BRANCH"
git fetch origin "$TARGET_BRANCH"
tmp_dir="$(mktemp -d)"
cleanup() {
rm -rf "$tmp_dir"
}
trap cleanup EXIT
git archive --format=tar "origin/${SUPERPOWERS_BRANCH}" "${SUPERPOWERS_DIR}/skills" | tar -xf - -C "$tmp_dir"
tmp_skills_dir="$tmp_dir/${SUPERPOWERS_DIR}/skills"
if [ ! -d "$tmp_skills_dir" ]; then
echo "ERROR: ${SUPERPOWERS_DIR}/skills not found in ${SUPERPOWERS_BRANCH}" >&2
exit 1
fi
git checkout -B "$TARGET_BRANCH" "origin/$TARGET_BRANCH"
mkdir -p "$(dirname "$SUPERPOWERS_LIST")"
old_list="$SUPERPOWERS_LIST"
if [ -f "$old_list" ]; then
while IFS= read -r name; do
[ -n "$name" ] || continue
rm -rf "codex/skills/$name"
done < "$old_list"
fi
names=()
for dir in "$tmp_skills_dir"/*; do
[ -d "$dir" ] || continue
name="$(basename "$dir")"
if [ -d "codex/skills/$name" ] && ! grep -qx "$name" "$old_list" 2>/dev/null; then
echo "ERROR: skill name conflict: $name" >&2
exit 1
fi
rm -rf "codex/skills/$name"
cp -R "$dir" "codex/skills/$name"
names+=("$name")
done
printf "%s\n" "${names[@]}" | sort > "$SUPERPOWERS_LIST"
update_block() {
local file="$1"
local start="<!-- superpowers:skills:start -->"
local end="<!-- superpowers:skills:end -->"
local tmp
tmp="$(mktemp)"
{
echo "### Third-party Skills (superpowers)"
echo ""
echo "$start"
while IFS= read -r name; do
[ -n "$name" ] || continue
echo "- $name"
done < "$SUPERPOWERS_LIST"
echo "$end"
} > "$tmp"
if grep -q "$start" "$file"; then
awk -v start="$start" -v end="$end" -v block="$tmp" '
BEGIN {
while ((getline line < block) > 0) { buf[++n] = line }
close(block)
inblock=0
replaced=0
}
{
if (!replaced && $0 == start) {
for (i=1; i<=n; i++) print buf[i]
inblock=1
replaced=1
next
}
if (inblock) {
if ($0 == end) { inblock=0 }
next
}
print
}
' "$file" > "${file}.tmp"
mv "${file}.tmp" "$file"
else
echo "" >> "$file"
cat "$tmp" >> "$file"
fi
rm -f "$tmp"
}
update_block "SKILLS.md"
git add codex/skills SKILLS.md "$SUPERPOWERS_LIST"
if git diff --cached --quiet; then
echo "No changes to sync."
exit 0
fi
git commit -m ":package: deps(skills): sync superpowers"
TOKEN="${WORKFLOW:-}"
if [ -n "$TOKEN" ] && [ -n "${GITHUB_SERVER_URL:-}" ] && [ -n "${GITHUB_REPOSITORY:-}" ]; then
git remote set-url origin "https://oauth2:${TOKEN}@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git"
fi
git push origin "$TARGET_BRANCH"