diff --git a/.github/workflows/.ncmake-workflows.json b/.github/workflows/.ncmake-workflows.json index a1f2af0..013052c 100644 --- a/.github/workflows/.ncmake-workflows.json +++ b/.github/workflows/.ncmake-workflows.json @@ -14,6 +14,11 @@ "sha": "afdcfdfa32d1f58337e7cb47e8428cee6bf00054", "source": "local" }, + "github-changes.yml": { + "hash": "aa0ec225981850218e941b12b1f31f6217973a46aabb163761b81dfa02493d5a", + "sha": "0ee1ec36c1335a9475995e1b0266b91d16b816d1", + "source": "ncmake" + }, "lint-actions-security.yml": { "hash": "946a1c4508050dcdcafce853b06352d3b3849860bb1970f9c192305c8046daf1", "sha": "68d667016bbca1a53754fc86c678156f373519e4", diff --git a/.github/workflows/github-changes.yml b/.github/workflows/github-changes.yml new file mode 100644 index 0000000..0ee1ec3 --- /dev/null +++ b/.github/workflows/github-changes.yml @@ -0,0 +1,232 @@ +# SPDX-FileCopyrightText: 2026 [ernolf] Raphael Gradenwitz +# 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 .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'(?]+>', '', c)) + for c in re.findall(r']*>(.*?)', 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)