diff --git a/.github/workflows/labels.yml b/.github/workflows/labels.yml new file mode 100644 index 0000000..0f06767 --- /dev/null +++ b/.github/workflows/labels.yml @@ -0,0 +1,79 @@ +name: Labels + +# Reusable: makes repositories' labels match the toolkit's labels.yml and +# your own label files. A dry run unless apply is true; never deletes a label +# unless prune is true. + +on: + workflow_call: + inputs: + files: + description: "Your label files, space-separated paths in your repository, read after the toolkit's" + type: string + default: "" + base: + description: "Start from the toolkit's labels.yml" + type: boolean + default: true + groups: + description: "Comma-separated groups to use, from every file (empty: all)" + type: string + default: "type,status,priority" + repos: + description: "Space-separated OWNER/NAME list (default: the calling repository)" + type: string + default: "" + apply: + description: "Make the changes; otherwise only list them" + type: boolean + default: false + prune: + description: "Also delete labels that are not in the files" + type: boolean + default: false + toolkit-ref: + description: "The toolkit version to run the script from" + type: string + default: v0 + secrets: + token: + description: "A token that can edit labels in every repository listed (default: the workflow's own token)" + required: false + +permissions: + contents: read + issues: write + +jobs: + sync: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + + - uses: actions/checkout@v4 + with: + repository: Horrible-Dev/toolkit + ref: ${{ inputs.toolkit-ref }} + path: .toolkit + + - name: Install + run: python3 -m pip install --quiet pyyaml + + - name: Sync labels + env: + GH_TOKEN: ${{ secrets.token || github.token }} + FILES: ${{ inputs.files }} + BASE: ${{ inputs.base }} + LABEL_GROUPS: ${{ inputs.groups }} + REPOS: ${{ inputs.repos || github.repository }} + APPLY: ${{ inputs.apply }} + PRUNE: ${{ inputs.prune }} + run: | + set -- --groups "$LABEL_GROUPS" + [ "$BASE" = true ] && set -- "$@" --file .toolkit/labels/labels.yml + for file in $FILES; do set -- "$@" --file "$file"; done + for repo in $REPOS; do set -- "$@" --repo "$repo"; done + [ "$APPLY" = true ] && set -- "$@" --apply + [ "$PRUNE" = true ] && set -- "$@" --prune + python3 .toolkit/labels/sync_labels.py "$@" | tee -a "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index cb9e472..7f825d8 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,49 @@ Shared GitHub workflows, actions and scripts for Horrible Dev projects. Each pro Pin a major version tag, like `@v0`. Breaking changes only come with a new major version. +## Labels + +[labels/labels.yml](labels/labels.yml) is one shared set of labels, in groups: + +- `type`: bug, enhancement, documentation and the other GitHub defaults. +- `status`: the status words, the same everywhere. Fixed, Solved, Implemented, In progress, Planned, Needs info and Won't do, plus `needs-retest`. +- `priority`: high, medium and low. +- `platform` and `area`: examples. Pick the ones you need, or write your own. + +[labels/sync_labels.py](labels/sync_labels.py) makes a repository's labels match. It only lists changes unless you pass `--apply`. It never deletes a label unless you pass `--prune`. + +```sh +python3 labels/sync_labels.py --repo OWNER/NAME --groups type,status,priority +python3 labels/sync_labels.py --repo OWNER/NAME --file my-labels.yml --apply +``` + +Your own file uses the same format and can add groups. It's read after the base file, so it wins for the same name. To rename a label and keep it on its issues, list the old name under `renamed_from`. + +To run it from Actions, call the reusable workflow: + +```yaml +# .github/workflows/labels.yml +name: Labels +on: + workflow_dispatch: + inputs: + apply: + type: boolean + default: false +permissions: + contents: read + issues: write +jobs: + labels: + uses: Horrible-Dev/toolkit/.github/workflows/labels.yml@v0 + with: + files: .github/labels.yml + groups: type,status,priority,platform,project + apply: ${{ inputs.apply || false }} +``` + +To sync other repositories, list them in `repos` and pass a token that can edit their labels as the `token` secret. + ## Credits Parts of the toolkit are adapted from ChupathingyCE's release and housekeeping tools. diff --git a/labels/labels.yml b/labels/labels.yml new file mode 100644 index 0000000..633afbe --- /dev/null +++ b/labels/labels.yml @@ -0,0 +1,112 @@ +# Shared labels for Horrible Dev projects. Each top-level key is a group; +# sync_labels.py --groups picks which ones a repository gets. A project can +# add its own file after this one (later files win for the same name). +# +# Each label: name, color (six hex digits, no #), description (optional), +# renamed_from (optional: old names to rename, so issues keep the label). + +type: + - name: bug + color: d73a4a + description: Something isn't working + - name: enhancement + color: a2eeef + description: New feature or request + - name: documentation + color: 0075ca + description: Improvements or additions to documentation + - name: question + color: d876e3 + description: Further information is requested + - name: duplicate + color: cfd3d7 + description: This issue or pull request already exists + - name: invalid + color: e4e669 + description: This doesn't seem right + - name: good first issue + color: 7057ff + description: Good for newcomers + - name: help wanted + color: 008672 + description: Extra attention is needed + - name: accessibility + color: f143ab + description: Barrier affecting people with disabilities + +# The status words, the same on GitHub, forum tags and replies. +status: + - name: "status: fixed" + color: 0e8a16 + description: The bug is fixed + - name: "status: solved" + color: 0e8a16 + description: The question is answered + - name: "status: implemented" + color: 0e8a16 + description: The idea has shipped + - name: "status: in progress" + color: 1d76db + description: Being worked on for the next release + - name: "status: planned" + color: 5319e7 + description: Planned for a later release + - name: "status: needs info" + color: fbca04 + description: Waiting on details from the reporter + - name: "status: won't do" + color: ffffff + description: This will not be worked on + - name: needs-retest + color: c5def5 + description: Reported on an older build; needs a retest on the current release + +priority: + - name: "priority: high" + color: b60205 + description: "Fix soon: crashes, broken features, many people affected" + - name: "priority: medium" + color: fbca04 + description: Should be fixed in the next release or two + - name: "priority: low" + color: c2e0c6 + description: Nice to have, rare, or cosmetic + +# Examples: pick the platforms a project ships on. +platform: + - name: windows + color: c5def5 + - name: macos + color: "999999" + description: macOS builds + - name: linux + color: c5def5 + - name: steam-deck + color: c5def5 + - name: android + color: c5def5 + - name: xbox + color: c5def5 + - name: xbox-360 + color: c5def5 + - name: wii-u + color: c5def5 + - name: switch + color: c5def5 + +# Examples: areas most projects have. Add your own in a project file. +area: + - name: audio + color: c5def5 + - name: crash + color: c5def5 + - name: input + color: c5def5 + - name: network + color: c5def5 + - name: performance + color: c5def5 + - name: rendering + color: c5def5 + - name: ui + color: c5def5 diff --git a/labels/sync_labels.py b/labels/sync_labels.py new file mode 100755 index 0000000..7197834 --- /dev/null +++ b/labels/sync_labels.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Make a repository's labels match one or more label files. + + sync_labels.py --repo OWNER/NAME [--repo ...] [--file FILE ...] + [--groups type,status,...] [--apply] [--prune] + +Without --apply it only prints what it would change (a dry run). It never +deletes a label unless --prune is given; then labels not in the files are +deleted too. Reads and writes GitHub with gh (GH_TOKEN). + +Label files are YAML: groups of labels, each with name, color and an +optional description and renamed_from list. Later files win for the same +name. Without --file it reads labels.yml next to this script. +""" + +import argparse +import json +import subprocess +import sys +from pathlib import Path + +import yaml + +BASE = Path(__file__).resolve().parent / "labels.yml" + + +class LabelError(Exception): + pass + + +def normalize_color(color) -> str: + text = str(color).strip().lstrip("#").lower() + if len(text) != 6 or any(c not in "0123456789abcdef" for c in text): + raise LabelError(f"not a six-digit hex color: {color!r}") + return text + + +def load(paths, groups=None) -> dict: + """{name: {"name", "color", "description", "renamed_from"}} in file order""" + wanted = None if groups is None else set(groups) + labels, seen_groups = {}, set() + for path in paths: + data = yaml.safe_load(Path(path).read_text()) or {} + if not isinstance(data, dict): + raise LabelError(f"{path}: expected groups of labels at the top level") + for group, entries in data.items(): + seen_groups.add(group) + if wanted is not None and group not in wanted: + continue + for entry in entries or []: + if "name" not in entry or "color" not in entry: + raise LabelError(f"{path}: every label needs a name and a color ({entry!r})") + name = str(entry["name"]) + labels.pop(name, None) + labels[name] = { + "name": name, + "color": normalize_color(entry["color"]), + "description": str(entry.get("description") or ""), + "renamed_from": [str(old) for old in entry.get("renamed_from") or []], + } + if wanted is not None: + missing = wanted - seen_groups + if missing: + raise LabelError(f"no such group: {', '.join(sorted(missing))}") + return labels + + +def plan(desired: dict, existing: list, prune: bool = False) -> list: + """The changes, as (action, name, details) tuples: create, rename, + update, delete. Names compare without case, as GitHub's do.""" + current = {label["name"].lower(): label for label in existing} + actions, claimed = [], set() + for name, label in desired.items(): + key = name.lower() + have = current.get(key) + if have is None: + old = next((current[o.lower()] for o in label["renamed_from"] + if o.lower() in current and o.lower() not in claimed), None) + if old is not None: + claimed.add(old["name"].lower()) + actions.append(("rename", old["name"], label)) + continue + actions.append(("create", name, label)) + continue + claimed.add(key) + if (have["name"] != name or normalize_color(have["color"]) != label["color"] + or (have.get("description") or "") != label["description"]): + actions.append(("update", have["name"], label)) + if prune: + for key, have in current.items(): + if key not in claimed and key not in {n.lower() for n in desired}: + actions.append(("delete", have["name"], None)) + return actions + + +def describe(action: str, name: str, label) -> str: + if action == "create": + return f"create {name!r} #{label['color']} {label['description']!r}" + if action == "rename": + return f"rename {name!r} to {label['name']!r} #{label['color']}" + if action == "update": + return f"update {name!r} to {label['name']!r} #{label['color']} {label['description']!r}" + return f"delete {name!r}" + + +def run_gh(arguments: list) -> str: + result = subprocess.run(["gh", *arguments], capture_output=True, text=True) + if result.returncode != 0: + raise LabelError(f"gh {' '.join(arguments[:2])}: {result.stderr.strip()[:300]}") + return result.stdout + + +def existing_labels(repo: str) -> list: + return json.loads(run_gh(["label", "list", "--repo", repo, "--limit", "1000", + "--json", "name,color,description"]) or "[]") + + +def apply(repo: str, actions: list) -> None: + for action, name, label in actions: + if action == "create": + run_gh(["label", "create", label["name"], "--repo", repo, + "--color", label["color"], "--description", label["description"]]) + elif action in ("rename", "update"): + command = ["label", "edit", name, "--repo", repo, + "--color", label["color"], "--description", label["description"]] + if name != label["name"]: + command += ["--name", label["name"]] + run_gh(command) + elif action == "delete": + run_gh(["label", "delete", name, "--repo", repo, "--yes"]) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--repo", action="append", required=True, help="OWNER/NAME; repeat for more") + parser.add_argument("--file", action="append", type=Path, help="a label file; repeat for more") + parser.add_argument("--groups", help="comma-separated groups to use (default: all)") + parser.add_argument("--apply", action="store_true", help="make the changes (default: dry run)") + parser.add_argument("--prune", action="store_true", help="also delete labels not in the files") + options = parser.parse_args(argv) + groups = [g.strip() for g in options.groups.split(",") if g.strip()] if options.groups else None + try: + desired = load(options.file or [BASE], groups) + except (LabelError, OSError, yaml.YAMLError) as error: + print(f"error: {error}", file=sys.stderr) + return 2 + failed = False + for repo in options.repo: + try: + actions = plan(desired, existing_labels(repo), options.prune) + mode = "" if options.apply else " (dry run)" + print(f"{repo}: {len(actions)} change(s){mode}") + for action in actions: + print(f" {describe(*action)}") + if options.apply: + apply(repo, actions) + except LabelError as error: + print(f"{repo}: {error}", file=sys.stderr) + failed = True + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_sync_labels.py b/tests/test_sync_labels.py new file mode 100644 index 0000000..a7dee3c --- /dev/null +++ b/tests/test_sync_labels.py @@ -0,0 +1,106 @@ +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "labels")) +import sync_labels # noqa: E402 + +STATUS_WORDS = ["fixed", "solved", "implemented", "in progress", "planned", "needs info", "won't do"] + + +def write(tmp_path, name, text): + path = tmp_path / name + path.write_text(text) + return path + + +def test_base_file_has_the_status_words_and_valid_colors(): + labels = sync_labels.load([sync_labels.BASE]) + for word in STATUS_WORDS: + assert f"status: {word}" in labels + assert all(len(label["color"]) == 6 for label in labels.values()) + + +def test_groups_pick_labels_and_unknown_groups_fail(): + labels = sync_labels.load([sync_labels.BASE], ["priority"]) + assert list(labels) == ["priority: high", "priority: medium", "priority: low"] + with pytest.raises(sync_labels.LabelError): + sync_labels.load([sync_labels.BASE], ["nope"]) + + +def test_later_files_win(tmp_path): + first = write(tmp_path, "a.yml", "type:\n - {name: bug, color: d73a4a}\n") + second = write(tmp_path, "b.yml", "type:\n - {name: bug, color: '#00FF00', description: Broken}\n") + labels = sync_labels.load([first, second]) + assert labels["bug"]["color"] == "00ff00" + assert labels["bug"]["description"] == "Broken" + + +def test_bad_color_fails(tmp_path): + path = write(tmp_path, "a.yml", "type:\n - {name: bug, color: red}\n") + with pytest.raises(sync_labels.LabelError): + sync_labels.load([path]) + + +def label(name, color="000000", description="", renamed_from=()): + return {"name": name, "color": color, "description": description, "renamed_from": list(renamed_from)} + + +def test_plan_creates_updates_and_leaves_extras(): + desired = {"bug": label("bug", "d73a4a", "Broken"), "ui": label("ui")} + existing = [{"name": "bug", "color": "D73A4A", "description": "Old"}, {"name": "extra", "color": "ffffff"}] + actions = sync_labels.plan(desired, existing) + assert [(a, n) for a, n, _ in actions] == [("update", "bug"), ("create", "ui")] + + +def test_plan_is_empty_when_labels_match_ignoring_case_of_color(): + desired = {"bug": label("bug", "d73a4a", "Broken")} + existing = [{"name": "bug", "color": "D73A4A", "description": "Broken"}] + assert sync_labels.plan(desired, existing) == [] + + +def test_prune_deletes_only_unlisted_labels(): + desired = {"bug": label("bug")} + existing = [{"name": "Bug", "color": "000000", "description": ""}, {"name": "extra", "color": "ffffff"}] + actions = sync_labels.plan(desired, existing, prune=True) + assert [(a, n) for a, n, _ in actions] == [("update", "Bug"), ("delete", "extra")] + + +def test_rename_keeps_the_old_label(): + desired = {"status: won't do": label("status: won't do", "ffffff", renamed_from=["wontfix"])} + existing = [{"name": "wontfix", "color": "ffffff", "description": ""}] + actions = sync_labels.plan(desired, existing, prune=True) + assert [(a, n) for a, n, _ in actions] == [("rename", "wontfix")] + + +def test_dry_run_never_writes(monkeypatch, capsys): + calls = [] + + def fake_gh(arguments): + calls.append(arguments) + if arguments[:2] == ["label", "list"]: + return '[{"name": "extra", "color": "ffffff", "description": ""}]' + return "" + + monkeypatch.setattr(sync_labels, "run_gh", fake_gh) + assert sync_labels.main(["--repo", "o/r", "--groups", "priority"]) == 0 + assert all(call[:2] == ["label", "list"] for call in calls) + assert "3 change(s) (dry run)" in capsys.readouterr().out + + +def test_apply_creates_and_edits(monkeypatch): + calls = [] + + def fake_gh(arguments): + calls.append(arguments) + if arguments[:2] == ["label", "list"]: + return '[{"name": "Priority: High", "color": "b60205", "description": ""}]' + return "" + + monkeypatch.setattr(sync_labels, "run_gh", fake_gh) + assert sync_labels.main(["--repo", "o/r", "--groups", "priority", "--apply"]) == 0 + verbs = [call[:2] for call in calls[1:]] + assert verbs == [["label", "edit"], ["label", "create"], ["label", "create"]] + assert calls[1][-2:] == ["--name", "priority: high"]