Repository navigation
Expand file tree
/
Copy pathgithub-changes.yml
More file actions
232 lines (208 loc) · 10.5 KB
/
Copy pathgithub-changes.yml
File metadata and controls
232 lines (208 loc) · 10.5 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# SPDX-FileCopyrightText: 2026 [ernolf] Raphael Gradenwitz <raphael.gradenwitz@googlemail.com>
# SPDX-License-Identifier: MIT
#
# ncmake GitHub changes: an issue for each change GitHub announces that
# concerns the workflows the repository maintains itself.
# https://github.com/ernolf/ncmake-workflows
#
# GitHub announces a change of Actions in its changelog, often weeks before it
# takes effect. Four times a day the job reads the changelog feed and opens an
# issue labelled github-change for an entry that
# - retires something in Actions, whatever it names, or
# - is neither a release nor an improvement and names an event, an action or
# a runner label one of the workflows uses.
# Release and Improvement entries add something and are left out.
#
# The workflows are the ones the repository maintains itself: those in
# .github/workflows/ that the workflow manager of ncmake does not manage, those
# in .ncmake/workflows/ and the templates next to a <name>.properties.json. A
# managed copy is watched where its template lives.
#
# The feed holds the newest ten entries, two or three days of the changelog, so
# a run every six hours sees each entry several times. An entry gets one issue:
# an entry that an issue with the label already links, open or closed, is
# skipped. The issue links the entry and lists what of the workflows it names
# and where; it quotes no text of the entry. It is assigned to the owner of the
# repository when that is a user.
name: ncmake GitHub changes
on:
schedule:
- cron: "41 */6 * * *"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ncmake-github-changes
cancel-in-progress: false
jobs:
changes:
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Open an issue for each change that concerns the workflows
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import html
import json
import os
import re
import subprocess
import sys
import time
import xml.etree.ElementTree as ET
FEED = 'https://github.blog/changelog/feed/'
LABEL = 'github-change'
REPO = os.environ['GITHUB_REPOSITORY']
LOCK = '.github/workflows/.ncmake-workflows.json'
CONTENT = '{http://purl.org/rss/1.0/modules/content/}encoded'
def read(args):
# Only for calls that may run twice, so a failed one goes again.
for attempt in range(1, 6):
p = subprocess.run(args, capture_output=True, text=True, encoding='utf-8')
if p.returncode == 0:
return p.stdout
sys.stderr.write(p.stderr)
if attempt < 5:
time.sleep(attempt * 10)
sys.exit('%s failed five times' % ' '.join(args[:3]))
# The workflows of the repository's own: unmanaged ones in
# .github/workflows/, the sources in .ncmake/workflows/ and templates.
managed = set()
if os.path.isfile(LOCK):
with open(LOCK, encoding='utf-8') as f:
managed = set(json.load(f))
watched = []
for path in read(['git', 'ls-files', '-z', '--', '*.yml', '*.yaml']).split('\0'):
if not path:
continue
folder, base = os.path.split(path)
stem = re.sub(r'\.ya?ml$', '', base)
if folder == '.github/workflows':
if base not in managed:
watched.append(path)
elif folder == '.ncmake/workflows':
watched.append(path)
elif os.path.isfile(os.path.join(folder, stem + '.properties.json')):
watched.append(path)
def as_list(value):
if isinstance(value, str):
return [value]
if isinstance(value, list):
return [v for v in value if isinstance(v, str)]
return []
# (kind, name) -> the files that use it. yq keeps the key on a string,
# where a YAML 1.1 reader such as PyYAML turns it into true.
used = {}
for path in watched:
doc = json.loads(read(['yq', '-o=json', '.', path]) or 'null')
if not isinstance(doc, dict):
continue
on = doc.get('on')
names = [('event', e) for e in (list(on) if isinstance(on, dict) else as_list(on))]
for job in (doc.get('jobs') or {}).values():
if not isinstance(job, dict):
continue
uses = [job.get('uses')] + [s.get('uses') for s in job.get('steps') or [] if isinstance(s, dict)]
for u in uses:
if isinstance(u, str) and not u.startswith(('./', 'docker://')):
names.append(('action', '/'.join(u.split('@')[0].split('/')[:2])))
runs_on = job.get('runs-on')
labels = runs_on.get('labels') if isinstance(runs_on, dict) else runs_on
# A label from an expression is not known before the run.
names += [('runner', r) for r in as_list(labels) if '{{' not in r]
for name in names:
used.setdefault(name, set()).add(path)
print('%d workflows, %d events, actions and runner labels' % (len(watched), len(used)))
def token(name):
return re.compile(r'(?<![\w.-])' + re.escape(name) + r'(?![\w-])', re.I)
def named(kind, name, title, codes, text):
# An action is named anywhere, links included. An event or a
# runner label with a - _ or . in it is named in the title or in
# code; a plain one such as push only as code of its own, since
# the word alone says nothing.
if kind == 'action':
return bool(token(name).search(title) or token(name).search(text))
if re.search(r'[-_.]', name):
return bool(token(name).search(title) or any(token(name).search(c) for c in codes))
return any(c.strip().lower() == name.lower() for c in codes)
root = ET.fromstring(read(['curl', '-fsSL', '--retry', '3', FEED]))
raised = []
for item in root.iter('item'):
title = (item.findtext('title') or '').strip()
link = (item.findtext('guid') or item.findtext('link') or '').strip().rstrip('/')
slug = link.rsplit('/', 1)[-1]
if not slug:
continue
categories = [(c.get('domain'), (c.text or '').strip()) for c in item.findall('category')]
types = [v for d, v in categories if d == 'changelog-type']
labels = [v for d, v in categories if d == 'changelog-label']
content = item.findtext(CONTENT) or item.findtext('description') or ''
codes = [html.unescape(re.sub(r'<[^>]+>', '', c))
for c in re.findall(r'<code[^>]*>(.*?)</code>', content, re.S)]
text = html.unescape(content)
hits = sorted((k, n) for k, n in used if named(k, n, title, codes, text))
retires_actions = 'Retired' in types and 'Actions' in labels
adds = bool(set(types) & {'Release', 'Improvement'})
if retires_actions or (hits and not adds):
raised.append((slug, title, types, labels, hits))
print('%d entries concern the workflows' % len(raised))
if not raised:
sys.exit(0)
# The slug stays when the changelog moves to another host, the link
# may not.
issues = json.loads(read(['gh', 'issue', 'list', '--repo', REPO, '--label', LABEL,
'--state', 'all', '--limit', '1000', '--json', 'body']))
known = '\n'.join(i.get('body') or '' for i in issues)
new = []
for r in raised:
if re.search(re.escape('/changelog/' + r[0]) + r'(?![\w-])', known):
print('already in an issue: %s' % r[0])
else:
new.append(r)
if not new:
sys.exit(0)
read(['gh', 'label', 'create', LABEL, '--repo', REPO, '--force', '--color', 'd93f0b',
'--description', 'A change GitHub announced that concerns a workflow of this repository'])
owner = REPO.split('/')[0]
is_user = read(['gh', 'api', 'repos/%s' % REPO, '--jq', '.owner.type']).strip() == 'User'
failed = False
for slug, title, types, labels, hits in new:
lines = [
'GitHub announced a change that concerns the workflows of this repository:',
'',
'https://github.blog/changelog/%s' % slug,
'',
'Type: %s. Labels: %s.' % (', '.join(types) or 'none', ', '.join(labels) or 'none'),
'',
]
if hits:
lines.append('What of the workflows it names:')
lines.append('')
for kind, name in hits:
files = ', '.join('`%s`' % p for p in sorted(used[(kind, name)]))
lines.append('- %s `%s`: %s' % (kind, name, files))
else:
lines.append('It retires something in Actions, and none of the workflows names an '
'event, an action or a runner label it mentions. Check whether it '
'concerns them all the same.')
lines += ['', 'Close this issue once the workflows are adapted, or once the change '
'turns out not to concern them.']
args = ['gh', 'issue', 'create', '--repo', REPO, '--label', LABEL,
'--title', 'GitHub change: %s' % title, '--body', '\n'.join(lines)]
if is_user:
args += ['--assignee', owner]
# Not repeated: a create that failed after all would leave two
# issues. The next run tries again.
p = subprocess.run(args, capture_output=True, text=True, encoding='utf-8')
sys.stdout.write(p.stdout)
sys.stderr.write(p.stderr)
failed = failed or p.returncode != 0
sys.exit(1 if failed else 0)