Repository navigation
163 lines (152 loc) · 6.05 KB
/
Copy pathpatch-notes.yml
File metadata and controls
163 lines (152 loc) · 6.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
name: Patch notes
on:
push:
branches:
- main
paths:
- "patch-notes/**/*.md"
- "patch-notes/*.md"
permissions:
contents: write
jobs:
publish:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 2
- name: Publish new / changed notes
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DISCORD_PATCH_WEBHOOK_URL: ${{ secrets.DISCORD_PATCH_WEBHOOK_URL }}
SITE_ORIGIN: https://lightkeepers.moe
run: |
python3 <<'PY'
import json, os, re, subprocess, urllib.error, urllib.parse, urllib.request
from pathlib import Path
root = Path("patch-notes")
note_re = re.compile(r"^\d{4}-\d{2}-\d{2}-.+\.md$", re.I)
def changed_note_files() -> list[Path]:
before = subprocess.check_output(
["git", "rev-parse", "HEAD^"], text=True
).strip()
out = subprocess.check_output(
["git", "diff", "--name-only", "--diff-filter=AM", before, "HEAD", "--", "patch-notes"],
text=True,
)
files = []
for line in out.splitlines():
p = Path(line.strip())
if p.name == "README.md":
continue
if note_re.match(p.name):
files.append(p)
return files
def parse(path: Path) -> dict:
text = path.read_text(encoding="utf-8").lstrip("\ufeff").replace("\r\n", "\n")
m = re.match(r"^---\n([\s\S]*?)\n---\n([\s\S]*)$", text)
if not m:
raise SystemExit(f"{path}: missing frontmatter")
fields = {}
for line in m.group(1).split("\n"):
if ":" not in line:
continue
k, v = line.split(":", 1)
fields[k.strip()] = v.strip().strip("\"'")
for key in ("title", "date", "summary"):
if not fields.get(key):
raise SystemExit(f"{path}: missing {key}")
slug = path.stem
return {
"slug": slug,
"title": fields["title"],
"date": fields["date"],
"summary": fields["summary"],
"body": m.group(2).strip(),
}
site = os.environ["SITE_ORIGIN"].rstrip("/")
webhook = os.environ.get("DISCORD_PATCH_WEBHOOK_URL", "").strip()
files = changed_note_files()
if not files:
print("No dated patch-note files changed.")
raise SystemExit(0)
for path in sorted(files):
note = parse(path)
tag = f"patch-notes/{note['slug']}"
site_url = f"{site}/patch-notes/{note['slug']}"
notes = f"{note['summary']}\n\n{note['body']}\n\n---\nSite: {site_url}"
existing = subprocess.run(
["gh", "release", "view", tag],
capture_output=True,
text=True,
)
if existing.returncode == 0:
print(f"Updating release {tag}")
subprocess.check_call(
[
"gh",
"release",
"edit",
tag,
"--title",
note["title"],
"--notes",
notes,
]
)
else:
print(f"Creating release {tag}")
subprocess.check_call(
[
"gh",
"release",
"create",
tag,
"--title",
note["title"],
"--notes",
notes,
"--target",
os.environ.get("GITHUB_SHA", "main"),
]
)
if webhook:
repo = os.environ.get("GITHUB_REPOSITORY", "")
gh_base = os.environ.get("GITHUB_SERVER_URL", "https://github.com")
gh_url = f"{gh_base}/{repo}/releases/tag/{urllib.parse.quote(tag, safe='')}"
embed = {
"title": note["title"],
"description": note["summary"],
"url": site_url,
"color": 0xC9A227,
"fields": [
{"name": "Date", "value": note["date"], "inline": True},
{
"name": "Links",
"value": f"[Site]({site_url}) · [GitHub]({gh_url})",
"inline": False,
},
],
}
req = urllib.request.Request(
webhook,
data=json.dumps({"embeds": [embed]}).encode(),
headers={
"Content-Type": "application/json",
# Cloudflare in front of Discord blocks Python-urllib's default UA (403).
"User-Agent": "lightkeepers-patch-notes/1.0",
},
method="POST",
)
try:
with urllib.request.urlopen(req) as resp:
print(f"Discord webhook status {resp.status} for {tag}")
except urllib.error.HTTPError as err:
detail = err.read().decode("utf-8", errors="replace")[:500]
print(
f"::warning::Discord webhook HTTP {err.code} for {tag}: {detail}"
)
else:
print("DISCORD_PATCH_WEBHOOK_URL unset — skipped Discord post")
PY