diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/1-bug.yml similarity index 98% rename from .github/ISSUE_TEMPLATE/bug_report.yml rename to .github/ISSUE_TEMPLATE/1-bug.yml index 1f92d4f..6d94627 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/1-bug.yml @@ -1,6 +1,6 @@ name: Bug report description: Something behaves differently from how it should -labels: ["bug"] +labels: ["type:bug", "needs-triage"] body: - type: markdown attributes: diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/2-story.yml similarity index 90% rename from .github/ISSUE_TEMPLATE/feature_request.yml rename to .github/ISSUE_TEMPLATE/2-story.yml index 67541ed..6b43d47 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/2-story.yml @@ -1,6 +1,6 @@ -name: Feature request -description: Propose something the product should do -labels: ["enhancement"] +name: Story (feature request) +description: Something a user should be able to do that they cannot today +labels: ["type:story", "needs-triage"] body: - type: markdown attributes: diff --git a/.github/ISSUE_TEMPLATE/3-task.yml b/.github/ISSUE_TEMPLATE/3-task.yml new file mode 100644 index 0000000..61860f2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/3-task.yml @@ -0,0 +1,41 @@ +name: Task +description: A piece of work with a clear finish line that is not a user-facing feature +labels: ["type:task", "needs-triage"] +body: + - type: markdown + attributes: + value: | + Chores, docs, CI, refactors, operations and playbook work. One task is one pull request. + **Never include real people's names, a PIN, a key or a token.** + + - type: textarea + id: goal + attributes: + label: What needs doing + description: The outcome, in a sentence or two. + validations: + required: true + + - type: textarea + id: done + attributes: + label: Done when + description: Checkable criteria. Someone else should be able to tell whether they are met. + placeholder: | + - [ ] ... + - [ ] ... + validations: + required: true + + - type: input + id: epic + attributes: + label: Epic + description: The phase epic this belongs to, if any. + placeholder: kaffeelisten/.github#2 + + - type: textarea + id: notes + attributes: + label: Notes + description: Links, dependencies, anything a newcomer would need. diff --git a/.github/ISSUE_TEMPLATE/4-spike.yml b/.github/ISSUE_TEMPLATE/4-spike.yml new file mode 100644 index 0000000..07d1931 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/4-spike.yml @@ -0,0 +1,27 @@ +name: Spike +description: A time-boxed question to answer before committing to an approach +labels: ["type:spike", "needs-triage"] +body: + - type: textarea + id: question + attributes: + label: The question + description: What we need to know, and which decision waits on the answer. + validations: + required: true + + - type: input + id: timebox + attributes: + label: Time box + placeholder: Half a day + validations: + required: true + + - type: textarea + id: output + attributes: + label: Output + description: What the spike leaves behind. Usually a short write-up and a recommendation, not production code. + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/5-epic.yml b/.github/ISSUE_TEMPLATE/5-epic.yml new file mode 100644 index 0000000..c34493e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/5-epic.yml @@ -0,0 +1,34 @@ +name: Epic +description: One phase of the build order, with its stories and tasks as sub-issues (maintainers) +title: "[P?] " +labels: ["type:epic"] +body: + - type: markdown + attributes: + value: | + Epics live in `kaffeelisten/.github`, one per phase, titled `[P2] …`. Their children can sit in + any repository of the organisation and are attached as native **sub-issues**. An epic is + never closed automatically: when its last sub-issue closes it gets `ready-for-acceptance`, + and a maintainer checks the outcome before closing it. + + - type: textarea + id: outcome + attributes: + label: Outcome + description: What is true when this phase is done. + validations: + required: true + + - type: textarea + id: criteria + attributes: + label: Done when + placeholder: | + - [ ] ... + validations: + required: true + + - type: textarea + id: out-of-scope + attributes: + label: Not in this phase diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index a4a5276..cd73f90 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -4,6 +4,15 @@ Closes # + + ## How it was verified @@ -26,7 +35,7 @@ Closes # - [ ] `CHANGELOG.md` updated under `[Unreleased]` — or not applicable, nothing user-visible - [ ] No secret, PIN, key or token in the diff, the description or a screenshot - [ ] No real member names in fixtures, tests or screenshots -- [ ] Branch name and commits follow the conventions in `CONTRIBUTING.md` +- [ ] Branch name, commits and title follow the conventions in `CONTRIBUTING.md` ## Anything a reviewer should look at first diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000..03800a5 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,13 @@ +# Path-based area labels for pull requests (actions/labeler v5 syntax). +area:org: + - changed-files: + - any-glob-to-any-file: ['profile/**', 'CODE_OF_CONDUCT.md', 'SECURITY.md', 'CONTRIBUTING.md', '.github/ISSUE_TEMPLATE/**', '.github/PULL_REQUEST_TEMPLATE.md'] +area:brand: + - changed-files: + - any-glob-to-any-file: ['brand/**'] +area:delivery: + - changed-files: + - any-glob-to-any-file: ['.github/workflows/**', '.github/labeler.yml', 'scripts/**', 'workflow-templates/**'] +area:docs: + - changed-files: + - any-glob-to-any-file: ['docs/**', '*.md'] diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..2cfd8de --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,24 @@ +name: Checks + +on: + pull_request: + branches: [main] + push: + branches: [main] + +permissions: + contents: read + +jobs: + scripts: + name: Convention scripts + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Unit tests + run: node --test scripts/conventions/conventions.test.cjs + - name: Config is valid JSON + run: node -e "JSON.parse(require('fs').readFileSync('scripts/conventions/project-config.json','utf8'))" diff --git a/.github/workflows/conventions.yml b/.github/workflows/conventions.yml new file mode 100644 index 0000000..3da7ac5 --- /dev/null +++ b/.github/workflows/conventions.yml @@ -0,0 +1,25 @@ +name: Conventions + +# This repository's own caller of the shared conventions in org-conventions.yml. Every other +# repository calls the same workflow by its full path; see workflow-templates/conventions.yml. +on: + pull_request_target: + types: [opened, edited, reopened, synchronize, ready_for_review, converted_to_draft, labeled, unlabeled, closed] + issues: + types: [opened, reopened, closed, assigned, labeled] + issue_comment: + types: [created] + schedule: + - cron: '23 5 * * *' + workflow_dispatch: + +permissions: {} + +jobs: + conventions: + uses: ./.github/workflows/org-conventions.yml + permissions: + contents: read + issues: write + pull-requests: write + secrets: inherit diff --git a/.github/workflows/org-conventions.yml b/.github/workflows/org-conventions.yml new file mode 100644 index 0000000..fe3dc8f --- /dev/null +++ b/.github/workflows/org-conventions.yml @@ -0,0 +1,135 @@ +name: Conventions + +# The organisation's shared conventions, called by a short `conventions.yml` in every repository +# (template: workflow-templates/conventions.yml). One entry point dispatches on the caller's event: +# +# pull request PR conventions: title, type label, linked issue, assignee, milestone; area labels +# /take, /drop self-assign or unassign an issue +# issue closed sub-issue roll-up: an epic whose children are all closed gets ready-for-acceptance +# any of these board sync, when the repository has a PROJECTS_TOKEN secret +# +# Under pull_request_target it checks out the caller's default branch and this repository's main, +# never the pull request's head, so no code from a pull request runs with these permissions. + +on: + workflow_call: + secrets: + PROJECTS_TOKEN: + required: false + +jobs: + pull-request: + name: PR conventions + if: github.event_name == 'pull_request_target' && github.event.action != 'closed' + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + pull-requests: write + concurrency: + group: pr-conventions-${{ github.repository }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: kaffeelisten/.github + ref: main + path: .org + persist-credentials: false + - name: Area labels from changed paths + if: hashFiles('.github/labeler.yml') != '' + uses: actions/labeler@v5 + with: + configuration-path: .github/labeler.yml + sync-labels: false + - name: Title, type label, issue link, assignee, milestone + uses: actions/github-script@v8 + with: + script: | + await require('./.org/scripts/conventions/pr-conventions.cjs')({ github, context, core }); + + issue-command: + name: Issue command + if: >- + github.event_name == 'issue_comment' && !github.event.issue.pull_request && + (startsWith(github.event.comment.body, '/take') || startsWith(github.event.comment.body, '/drop') || + startsWith(github.event.comment.body, '/assign') || startsWith(github.event.comment.body, '/unassign')) + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@v4 + with: + repository: kaffeelisten/.github + ref: main + path: .org + persist-credentials: false + - uses: actions/github-script@v8 + with: + script: | + await require('./.org/scripts/conventions/issue-commands.cjs')({ github, context, core }); + + roll-up: + name: Sub-issue roll-up + if: >- + (github.event_name == 'issues' && (github.event.action == 'closed' || github.event.action == 'reopened')) || + (github.repository == 'kaffeelisten/.github' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')) + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + concurrency: + group: roll-up-${{ github.repository }} + cancel-in-progress: false + steps: + - uses: actions/checkout@v4 + with: + repository: kaffeelisten/.github + ref: main + path: .org + persist-credentials: false + - uses: actions/github-script@v8 + with: + script: | + const rollup = require('./.org/scripts/conventions/sub-issue-rollup.cjs'); + if (context.eventName === 'issues') await rollup({ github, context, core }); + else await rollup.sweep({ github, context, core }); + + board: + name: Board sync + if: >- + github.event_name == 'pull_request_target' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || + (github.event_name == 'issues' && contains(fromJSON('["opened","reopened","closed","assigned","labeled"]'), github.event.action)) + runs-on: ubuntu-latest + permissions: + contents: read + issues: read + pull-requests: read + concurrency: + group: board-${{ github.repository }} + cancel-in-progress: false + env: + PROJECTS_TOKEN: ${{ secrets.PROJECTS_TOKEN }} + steps: + - name: Skip without a project token + if: env.PROJECTS_TOKEN == '' + run: echo "::notice::No PROJECTS_TOKEN secret in this repository, so the board is not synced from here. See CONTRIBUTING.md, section 'The board'." + - uses: actions/checkout@v4 + if: env.PROJECTS_TOKEN != '' + with: + repository: kaffeelisten/.github + ref: main + path: .org + persist-credentials: false + - uses: actions/github-script@v8 + if: env.PROJECTS_TOKEN != '' + with: + github-token: ${{ env.PROJECTS_TOKEN }} + retries: 3 + script: | + await require('./.org/scripts/conventions/project-sync.cjs')({ github, context, core }); diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3ecd8cb..c87cb63 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,6 +53,48 @@ For a change large enough to review in layers, use `gh stack` — `init`, `add`, `gh pr create --base`, and note that a stack has its own number, which is not a pull request number. +## Issues, labels and the board + +Every repository uses the same labels, milestones and board. The machinery lives in this repository +and each repository calls it with one short workflow, so the rules below are checked, not hoped for. + +**Labels.** Exactly one `type:*` on every issue and pull request, at least one `area:*`. + +| Label | Meaning | +|---|---| +| `type:epic` | One phase of the build order. Lives here in `kaffeelisten/.github`. | +| `type:story` | Something a user can do afterwards that they could not before. | +| `type:task` | Work with a clear finish line that is not a feature: docs, CI, refactors, operations. | +| `type:spike` | A time-boxed question whose answer decides an approach. | +| `type:bug` | Something behaves differently from how it should. | +| `area:*` | Where the change lands. Each repository has its own set, applied to pull requests from the changed paths by `.github/labeler.yml`. | +| `needs-triage` | New; nobody has looked at it yet. | +| `needs-decision` / `needs-design` | Waiting on a founder decision, or on a design. | +| `ready-for-acceptance` | Every sub-issue of an epic is closed. Check the outcome, then close the epic. | +| `parked` | Deliberately not now. `/take` refuses it. | +| `no-issue` | A pull request too small to need an issue. Use it rarely. | + +Priority and size are board fields, not labels. + +**Milestones** are the phases of the build order and carry the same names in every repository: +`P0 · Organisation hygiene`, `P1 · Move the product`, `P2 · The public face`, +`P3 · The demo and production readiness`, `P4 · Provider spaces and the first campus`. + +**Epics.** One per phase, here in `kaffeelisten/.github`, titled `[P2] The public face`. Stories, +tasks and spikes in any repository hang under it as native **sub-issues**, and an issue that cannot +start until another closes says so with a native **blocked by** link. When the last sub-issue closes, +the epic gets `ready-for-acceptance`; it is never closed automatically. + +**Taking an issue.** Comment `/take` on an open, unblocked issue to assign yourself and get the branch +name to use; `/drop` gives it back. Epics and `parked` issues cannot be taken. + +**The board** is the organisation project +[Kaffeelisten](https://github.com/orgs/kaffeelisten/projects/1): every issue and pull request from +every repository, with Status (Backlog · Ready · In progress · In review · Blocked · Done), Priority +(P0 blocks the phase · P1 needed · P2 nice to have), Size (XS < 2 h · S half a day · M 1–2 days · L 3–5 +days · XL split it) and Start, Target and Completed dates. Its views and automation are described in +[`docs/project-board.md`](docs/project-board.md). + ## Before you open a pull request From the repository root: @@ -74,12 +116,28 @@ CI tweaks do not need one. ## In the pull request +**Link the issue.** `Closes #12` for the issue the pull request completes, `Closes kaffeelisten/playbook#3` +for one in another repository, `Refs #12` for a stack layer or a partial step. The `PR conventions` +check fails without a link, a Conventional Commits title, or with more than one `type:*` label. It also +does the bookkeeping: it assigns the author to the pull request and to the issues it closes, adds the +`type:*` label the title implies (`feat` → story, `fix` → bug, anything else → task), copies the +milestone from the issue, and the labeler adds `area:*` from the changed paths. + +Inside a stack, title each layer `[n/N] type(scope): summary` and list the whole stack in every body. + Say **what changed and why**, and how you verified it. A screenshot for anything visual. If it touches the database, say what the migration does and whether it is `-- deploy: pre` or `-- deploy: post`. CI must pass. A green deployment-status comment from a bot is not a review. +## Merging + +**Merge commits only.** Squash and rebase merging are switched off in every repository, so the +history keeps each commit and each stack layer as it was reviewed. Branches are not deleted on merge, +because a stack's upper layers still point at them; delete them once the whole stack has landed. +Only the founders merge to `main`. + ## Secrets Never commit one. Never paste one into an issue, a pull request or a comment — including in a diff --git a/docs/project-board.md b/docs/project-board.md new file mode 100644 index 0000000..a3dc3b9 --- /dev/null +++ b/docs/project-board.md @@ -0,0 +1,62 @@ +# The board + +[Kaffeelisten](https://github.com/orgs/kaffeelisten/projects/1) is one organisation project for every +repository. Issues describe deliverables and pull requests are the review queue. Epics and blocked +work stay off the daily board. + +## Views + +| View | Layout | Filter | Purpose | +|---|---|---|---| +| [Open work](https://github.com/orgs/kaffeelisten/projects/1/views/1) | Board, Status columns | `is:open -label:"type:epic" -status:Blocked` | What is being worked on, across all repositories | +| [Phases](https://github.com/orgs/kaffeelisten/projects/1/views/2) | Table | `label:"type:epic"` | The build-order epics and their sub-issue progress | +| [Waiting](https://github.com/orgs/kaffeelisten/projects/1/views/3) | Table | `is:open status:Blocked` | Dependencies and decisions | +| [Pull requests](https://github.com/orgs/kaffeelisten/projects/1/views/4) | Table | `is:pr is:open` | Review and merge queue | +| [By repository](https://github.com/orgs/kaffeelisten/projects/1/views/5) | Table, grouped by Repository | `is:open -label:"type:epic"` | The same work, repository by repository | +| [Completed](https://github.com/orgs/kaffeelisten/projects/1/views/6) | Table | `is:closed` | History, including abandoned pull requests | + +Grouping and sorting are set in the web interface; the API cannot set them. + +## Fields + +| Field | Meaning | +|---|---| +| Status | Backlog · Ready · In progress · In review · Blocked · Done | +| Priority | P0 blocks the phase · P1 needed · P2 nice to have | +| Size | XS < 2 h · S half a day · M 1–2 days · L 3–5 days · XL split it | +| Start date | First seen In progress or In review; set once | +| Target date | A real deadline only, set by a founder | +| Completed date | Issue closed or pull request merged | +| Repository, Milestone, Labels, Assignees, Parent issue, Sub-issues progress, Linked pull requests, Reviewers | Native GitHub data | + +Priority and Size are triage decisions; nothing sets them automatically. Epics get no size. + +## Automation + +Every repository calls [`org-conventions.yml`](../.github/workflows/org-conventions.yml) through a +short `conventions.yml`. The scripts are in [`scripts/conventions/`](../scripts/conventions) and are +tested by `Checks` on every pull request here. + +| Trigger | Result | Where | +|---|---|---| +| Pull request opened, edited or pushed | Title, `type:*` and issue link checked; author assigned to the PR and the issues it closes; `type:*` from the title; milestone from the issue; `area:*` from `.github/labeler.yml` | PR conventions job | +| `/take`, `/drop` on an issue | Self-assign or unassign; refused for epics, `parked` and blocked issues | Issue command job | +| Sub-issue closed or reopened in the same repository | Parent gets or loses `ready-for-acceptance` | Roll-up job | +| Daily, in `kaffeelisten/.github` | Every open epic checked, whichever repository its children are in | Roll-up job, sweep | +| Issue or pull request event, daily, manual | Item added to the board; Status, Start and Completed dates set | Board sync job, needs `PROJECTS_TOKEN` | + +**`PROJECTS_TOKEN`.** `GITHUB_TOKEN` cannot write an organisation project, and on the Free plan +private repositories cannot read organisation secrets. So each repository that should sync the board +carries its own `PROJECTS_TOKEN` secret: a fine-grained token owned by a founder, resource owner +`kaffeelisten`, with **Projects: read and write** at organisation level and **Issues** and **Pull +requests: read** on all repositories, nothing else. Without it the board job prints a notice and +skips; nothing else depends on it. Rotate it before it expires. + +**Native workflows** (the project's Workflows page, web only): keep *Item closed* and *Pull request +merged* pointing at Done, *Item added* at Backlog, and turn on *Auto-add sub-issues*. Leave +*Auto-close issue* and *Auto-archive* off, so moving a card never closes an issue and finished work +stays visible. The Free plan allows one *Auto-add to project* workflow; point it at +`kaffeelisten/kaffeelisten` with `is:issue,pr is:open`, and let the token sync add the rest. + +Sync never closes issues, merges pull requests or deploys. Ready, Blocked, estimates and epic +acceptance remain founder decisions. diff --git a/scripts/conventions/conventions.test.cjs b/scripts/conventions/conventions.test.cjs new file mode 100644 index 0000000..daa30f5 --- /dev/null +++ b/scripts/conventions/conventions.test.cjs @@ -0,0 +1,76 @@ +// Unit tests for the convention scripts: node --test scripts/conventions/ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const pr = require('./pr-conventions.cjs'); +const cmd = require('./issue-commands.cjs'); +const rollup = require('./sub-issue-rollup.cjs'); +const sync = require('./project-sync.cjs'); + +test('titles', () => { + assert.deepEqual(pr.checkTitle('feat(web): link previews with the brand card'), []); + assert.deepEqual(pr.checkTitle('[2/3] fix: the hints were vanishing'), []); + assert.deepEqual(pr.checkTitle('docs(brand): the journey – references for the next round'), []); + assert.equal(pr.checkTitle('Add landing page').length, 1); + assert.equal(pr.checkTitle('feat: ends with a period.').length, 1); + assert.equal(pr.checkTitle(`feat: ${'x'.repeat(80)}`).length, 1); + assert.equal(pr.checkTitle('Feat: capital type').length, 1); +}); + +test('type label from title', () => { + assert.equal(pr.typeFromTitle('feat(ui): x'), 'type:story'); + assert.equal(pr.typeFromTitle('[1/2] fix: x'), 'type:bug'); + assert.equal(pr.typeFromTitle('ci: x'), 'type:task'); + assert.equal(pr.typeFromTitle('docs(brand): x'), 'type:task'); + assert.equal(pr.typeFromTitle('nonsense'), null); +}); + +test('issue references', () => { + const r = pr.issueReferences('Closes #12\nRefs kaffeelisten/.github#4\nFixes https://github.com/kaffeelisten/playbook/issues/7\n```\nCloses #99\n```\n', 'kaffeelisten', 'kaffeelisten'); + assert.deepEqual(r.closes, [{ repo: 'kaffeelisten/kaffeelisten', number: 12 }, { repo: 'kaffeelisten/playbook', number: 7 }]); + assert.deepEqual(r.refs, [{ repo: 'kaffeelisten/.github', number: 4 }]); + assert.deepEqual(pr.issueReferences('Closes #', 'o', 'r'), { closes: [], refs: [] }); +}); + +test('evaluate', () => { + const base = { title: 'feat: x', body: 'Closes #1', labels: [{ name: 'type:story' }], user: { login: 'arudaev' } }; + assert.deepEqual(pr.evaluate(base, 'o', 'r').problems, []); + assert.equal(pr.evaluate({ ...base, body: 'nothing' }, 'o', 'r').problems.length, 1); + assert.deepEqual(pr.evaluate({ ...base, body: '', labels: [{ name: 'no-issue' }] }, 'o', 'r').problems, []); + assert.deepEqual(pr.evaluate({ ...base, body: '', user: { login: 'dependabot[bot]' } }, 'o', 'r').problems, []); + assert.equal(pr.evaluate({ ...base, labels: [{ name: 'type:story' }, { name: 'type:bug' }] }, 'o', 'r').problems.length, 1); +}); + +test('issue commands', () => { + assert.equal(cmd.parseCommand('/take'), 'take'); + assert.equal(cmd.parseCommand(' /drop \nthanks'), 'drop'); + assert.equal(cmd.parseCommand('please /take'), null); + assert.equal(cmd.slug('[P2] Landing page für die Küche'), 'landing-page-fuer-die-kueche'); + assert.equal(cmd.branchPrefix(['type:bug']), 'fix'); + assert.equal(cmd.branchPrefix(['type:story']), 'feat'); + assert.equal(cmd.branchPrefix(['type:task', 'area:delivery']), 'ci'); + const issue = (over) => ({ number: 5, title: 'Thing', state: 'open', labels: [{ name: 'type:task' }], assignees: [], ...over }); + assert.equal(cmd.decideTake({ issue: issue(), login: 'a', openBlockers: [] }).ok, true); + assert.equal(cmd.decideTake({ issue: issue({ labels: [{ name: 'type:epic' }] }), login: 'a', openBlockers: [] }).ok, false); + assert.equal(cmd.decideTake({ issue: issue({ labels: [{ name: 'parked' }] }), login: 'a', openBlockers: [] }).ok, false); + assert.equal(cmd.decideTake({ issue: issue(), login: 'a', openBlockers: ['#2'] }).ok, false); + assert.equal(cmd.decideTake({ issue: issue({ assignees: [{ login: 'b' }] }), login: 'a', openBlockers: [] }).ok, false); + assert.match(cmd.decideTake({ issue: issue(), login: 'a', openBlockers: [] }).reply, /chore\/5-thing/); +}); + +test('sub-issue roll-up', () => { + const parent = (total, completed, labels = []) => ({ state: 'OPEN', subIssuesSummary: { total, completed }, labels: { nodes: labels.map((name) => ({ name })) } }); + assert.equal(rollup.decide({ action: 'closed', parent: parent(3, 3) }).kind, 'ready'); + assert.equal(rollup.decide({ action: 'closed', parent: parent(3, 2) }).kind, 'none'); + assert.equal(rollup.decide({ action: 'reopened', parent: parent(3, 2, ['ready-for-acceptance']) }).kind, 'unready'); + assert.equal(rollup.decide({ action: 'sweep', parent: parent(2, 2) }).kind, 'ready'); + assert.equal(rollup.decide({ action: 'sweep', parent: parent(2, 1, ['ready-for-acceptance']) }).kind, 'unready'); + assert.equal(rollup.decide({ action: 'sweep', parent: parent(0, 0) }).kind, 'none'); + assert.equal(rollup.decide({ action: 'closed', parent: null }).kind, 'none'); +}); + +test('board status from a pull request', () => { + assert.equal(sync.pullRequestStatus({ state: 'closed', merged: true }), 'Done'); + assert.equal(sync.pullRequestStatus({ state: 'closed', merged: false }), 'Backlog'); + assert.equal(sync.pullRequestStatus({ state: 'open', draft: true }), 'In progress'); + assert.equal(sync.pullRequestStatus({ state: 'open', draft: false }), 'In review'); +}); diff --git a/scripts/conventions/issue-commands.cjs b/scripts/conventions/issue-commands.cjs new file mode 100644 index 0000000..6f24f14 --- /dev/null +++ b/scripts/conventions/issue-commands.cjs @@ -0,0 +1,106 @@ +// Comment commands on issues: `/take` assigns the commenter, `/drop` unassigns them. +// Keeps self-assignment open to every contributor without granting repository access. + +const config = require('./project-config.json'); + +function parseCommand(body) { + const first = (body || '').trim().split(/\r?\n/)[0].trim().toLowerCase(); + if (first === '/take' || first === '/assign') return 'take'; + if (first === '/drop' || first === '/unassign') return 'drop'; + return null; +} + +function slug(title) { + return (title || '') + .replace(/^\[[^\]]*\]\s*/, '') + .toLowerCase() + .replace(/[äöüß]/g, (c) => ({ ä: 'ae', ö: 'oe', ü: 'ue', ß: 'ss' }[c])) + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + .split('-') + .slice(0, 5) + .join('-'); +} + +// Branch prefixes from CONTRIBUTING: feat, fix, docs, chore, ci, refactor, test. +function branchPrefix(labels) { + if (labels.includes('type:bug')) return 'fix'; + if (labels.includes('type:story')) return 'feat'; + if (labels.includes('area:docs')) return 'docs'; + if (labels.includes('area:delivery')) return 'ci'; + return 'chore'; +} + +// Decide what /take should do. `openBlockers` are issue references still open. +function decideTake({ issue, login, openBlockers }) { + const labels = (issue.labels || []).map((l) => (typeof l === 'string' ? l : l.name)); + const assignees = (issue.assignees || []).map((a) => a.login); + if (issue.state !== 'open') return { ok: false, reply: 'This issue is closed, so there is nothing to take.' }; + if (labels.includes('type:epic')) return { ok: false, reply: 'Epics are not taken directly. Pick one of the sub-issues listed above and comment `/take` there.' }; + if (labels.includes('parked')) return { ok: false, reply: 'This issue is parked on purpose. Ask in the thread before starting on it.' }; + if (assignees.includes(login)) return { ok: false, reply: `You already have this one, @${login}.` }; + if (assignees.length > 0) return { ok: false, reply: `This is already assigned to @${assignees.join(', @')}. Ask in the thread whether they still need help, or pick another issue in the **Ready** column of the [board](${config.projectUrl}).` }; + if (openBlockers.length > 0) { + return { ok: false, reply: `This issue is still blocked by ${openBlockers.join(', ')}. Pick one of those, or another issue in the **Ready** column of the [board](${config.projectUrl}).` }; + } + const branch = `${branchPrefix(labels)}/${issue.number}-${slug(issue.title)}`; + return { + ok: true, + reply: [ + `Assigned to @${login}.`, + '', + `1. Branch from an up-to-date \`main\`: \`git switch -c ${branch}\``, + `2. Open the pull request when it is ready for review, with \`Closes #${issue.number}\` in the description. The board moves the card to *In review*.`, + '3. Larger changes go up as a stack with `gh stack`, one layer per reviewable step.', + '', + `Changed your mind? Comment \`/drop\`. The full workflow: [CONTRIBUTING](${config.contributing}).`, + ].join('\n'), + }; +} + +async function openBlockersOf(github, owner, repo, number) { + try { + const result = await github.graphql( + 'query($o:String!,$r:String!,$n:Int!){repository(owner:$o,name:$r){issue(number:$n){blockedBy(first:20){nodes{number state repository{nameWithOwner}}}}}}', + { o: owner, r: repo, n: number }, + ); + return result.repository.issue.blockedBy.nodes + .filter((i) => i.state === 'OPEN') + .map((i) => (i.repository.nameWithOwner === `${owner}/${repo}` ? `#${i.number}` : `${i.repository.nameWithOwner}#${i.number}`)); + } catch { + return []; + } +} + +async function run({ github, context, core }) { + const { owner, repo } = context.repo; + const { issue, comment } = context.payload; + if (issue.pull_request) return; + const command = parseCommand(comment.body); + if (!command) return; + const login = comment.user.login; + const reply = (body) => github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body }); + await github.rest.reactions.createForIssueComment({ owner, repo, comment_id: comment.id, content: 'eyes' }); + + if (command === 'drop') { + const assigned = (issue.assignees || []).some((a) => a.login === login); + if (!assigned) return reply(`@${login}, you are not assigned to this issue.`); + await github.rest.issues.removeAssignees({ owner, repo, issue_number: issue.number, assignees: [login] }); + return reply(`Unassigned @${login}. The issue is free for someone else to \`/take\`.`); + } + + const decision = decideTake({ issue, login, openBlockers: await openBlockersOf(github, owner, repo, issue.number) }); + if (!decision.ok) return reply(decision.reply); + const { data: updated } = await github.rest.issues.addAssignees({ owner, repo, issue_number: issue.number, assignees: [login] }); + if (!(updated.assignees || []).some((a) => a.login === login)) { + core.warning(`GitHub did not accept ${login} as an assignee.`); + return reply(`@${login} wants to take this issue, but GitHub would not assign them automatically. A maintainer will assign it by hand.`); + } + return reply(decision.reply); +} + +module.exports = run; +module.exports.parseCommand = parseCommand; +module.exports.decideTake = decideTake; +module.exports.slug = slug; +module.exports.branchPrefix = branchPrefix; diff --git a/scripts/conventions/pr-conventions.cjs b/scripts/conventions/pr-conventions.cjs new file mode 100644 index 0000000..b1a7a31 --- /dev/null +++ b/scripts/conventions/pr-conventions.cjs @@ -0,0 +1,126 @@ +// Pull-request conventions for every kaffeelisten repository. +// +// Checks: a Conventional Commits title (optionally prefixed `[n/N] ` inside a stack), exactly one +// `type:*` label, and a linked issue. Fixes what it safely can: assigns the author to the PR and to +// the issues it closes, adds the `type:*` label the title implies, and copies the milestone from the +// closed issue. Runs from the default branch under pull_request_target and never executes PR code. + +const TYPES = ['feat', 'fix', 'docs', 'refactor', 'test', 'chore', 'ci', 'perf', 'build', 'style', 'revert']; +const TITLE = new RegExp(`^(\\[\\d+/\\d+\\] )?(${TYPES.join('|')})(\\([a-z0-9][a-z0-9/._-]*\\))?!?: \\S.*$`); +const MAX_TITLE = 72; +const BOTS = /\[bot\]$/; +const TYPE_LABELS = ['type:epic', 'type:story', 'type:task', 'type:spike', 'type:bug']; + +function checkTitle(title) { + const problems = []; + const t = title || ''; + if (!TITLE.test(t)) { + problems.push(`Title must look like \`type(scope): summary\` with type one of ${TYPES.join(', ')}. Inside a stack, prefix it with \`[n/N] \`.`); + } + const bare = t.replace(/^\[\d+\/\d+\] /, ''); + if (bare.length > MAX_TITLE) problems.push(`Title is ${bare.length} characters; keep it at most ${MAX_TITLE}.`); + if (/\.$/.test(t)) problems.push('Title must not end with a period.'); + return problems; +} + +// The type label a title implies: feat -> story, fix -> bug, anything else -> task. +function typeFromTitle(title) { + const m = TITLE.exec(title || ''); + if (!m) return null; + if (m[2] === 'feat') return 'type:story'; + if (m[2] === 'fix') return 'type:bug'; + return 'type:task'; +} + +// References outside code blocks and comments. Accepts `#n`, `owner/repo#n` and issue URLs. +// Returns { closes: [{repo, number}], refs: [{repo, number}] } with repo as `owner/name`. +function issueReferences(body, owner, repo) { + const text = (body || '').replace(/```[\s\S]*?```/g, '').replace(//g, ''); + const here = `${owner}/${repo}`; + const target = '(?:([A-Za-z0-9-]+\\/[A-Za-z0-9._-]+)?#(\\d+)|https:\\/\\/github\\.com\\/([A-Za-z0-9-]+\\/[A-Za-z0-9._-]+)\\/issues\\/(\\d+))\\b'; + const collect = (keywords) => { + const out = []; + for (const m of text.matchAll(new RegExp(`\\b(?:${keywords})\\s*:?\\s+${target}`, 'gi'))) { + const ref = { repo: m[1] || m[3] || here, number: Number(m[2] || m[4]) }; + if (!out.some((r) => r.repo === ref.repo && r.number === ref.number)) out.push(ref); + } + return out; + }; + const closes = collect('close[sd]?|fix(?:e[sd])?|resolve[sd]?'); + const refs = collect('refs?|part of|relates to|issue') + .filter((r) => !closes.some((c) => c.repo === r.repo && c.number === r.number)); + return { closes, refs }; +} + +function evaluate(pr, owner, repo) { + const problems = checkTitle(pr.title); + const labels = (pr.labels || []).map((l) => (typeof l === 'string' ? l : l.name)); + const exempt = BOTS.test(pr.user?.login || '') || labels.includes('no-issue'); + const refs = issueReferences(pr.body, owner, repo); + if (!exempt && refs.closes.length + refs.refs.length === 0) { + problems.push('Link an issue in the description: `Closes #n` for the issue this PR completes, or `Refs #n` for a stack layer or a partial step. Issues in other kaffeelisten repositories work too (`Closes kaffeelisten/playbook#n`). Add the `no-issue` label only for a trivial fix.'); + } + const types = labels.filter((l) => TYPE_LABELS.includes(l)); + if (types.length > 1) problems.push(`Use exactly one \`type:*\` label; this PR has ${types.join(', ')}.`); + return { problems, refs, exempt, labels }; +} + +async function run({ github, context, core }) { + const { owner, repo } = context.repo; + const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: context.payload.pull_request.number }); + const author = pr.user.login; + const notes = []; + + if (!BOTS.test(author) && pr.state === 'open') { + if ((pr.assignees || []).length === 0) { + await github.rest.issues.addAssignees({ owner, repo, issue_number: pr.number, assignees: [author] }); + notes.push(`Assigned the PR to @${author}.`); + } + const labels = (pr.labels || []).map((l) => l.name); + const implied = typeFromTitle(pr.title); + if (implied && !labels.some((l) => TYPE_LABELS.includes(l))) { + await github.rest.issues.addLabels({ owner, repo, issue_number: pr.number, labels: [implied] }); + pr.labels = [...(pr.labels || []), { name: implied }]; + notes.push(`Labelled \`${implied}\` from the title.`); + } + const { closes } = issueReferences(pr.body, owner, repo); + for (const ref of closes) { + const [o, r] = ref.repo.split('/'); + try { + const { data: issue } = await github.rest.issues.get({ owner: o, repo: r, issue_number: ref.number }); + if (issue.pull_request || issue.state !== 'open') continue; + if ((issue.assignees || []).length === 0) { + await github.rest.issues.addAssignees({ owner: o, repo: r, issue_number: ref.number, assignees: [author] }); + notes.push(`Assigned ${ref.repo}#${ref.number} to @${author}.`); + } + if (!pr.milestone && issue.milestone && ref.repo === `${owner}/${repo}`) { + await github.rest.issues.update({ owner, repo, issue_number: pr.number, milestone: issue.milestone.number }); + pr.milestone = issue.milestone; + notes.push(`Set the milestone to "${issue.milestone.title}" from #${ref.number}.`); + } + } catch (error) { + core.warning(`Could not update ${ref.repo}#${ref.number}: ${error.message}`); + } + } + } + + const { problems, labels } = evaluate(pr, owner, repo); + const warnings = []; + if (!labels.some((l) => l.startsWith('area:'))) warnings.push('No `area:*` label yet. The labeler adds one from the changed paths; add it by hand if none fits.'); + if (!pr.milestone) warnings.push('No milestone. Link an issue that has one, or set it by hand.'); + warnings.forEach((w) => core.warning(w)); + + await core.summary + .addHeading('PR conventions', 3) + .addList(problems.length ? problems : ['Title, type label and issue link look good.']) + .addList([...notes, ...warnings].length ? [...notes, ...warnings] : ['Nothing changed.']) + .write(); + if (problems.length) core.setFailed(problems.join('\n')); +} + +module.exports = run; +module.exports.checkTitle = checkTitle; +module.exports.typeFromTitle = typeFromTitle; +module.exports.issueReferences = issueReferences; +module.exports.evaluate = evaluate; +module.exports.TYPE_LABELS = TYPE_LABELS; diff --git a/scripts/conventions/project-config.json b/scripts/conventions/project-config.json new file mode 100644 index 0000000..e3769a1 --- /dev/null +++ b/scripts/conventions/project-config.json @@ -0,0 +1,19 @@ +{ + "owner": "kaffeelisten", + "projectNumber": 1, + "projectUrl": "https://github.com/orgs/kaffeelisten/projects/1", + "projectId": "PVT_kwDOFQiz884BqcH-", + "statusFieldId": "PVTSSF_lADOFQiz884BqcH-zhozQBk", + "statusOptions": { + "Backlog": "68718046", + "Ready": "9e3539ed", + "In progress": "03b0ee27", + "In review": "8785016f", + "Blocked": "c047cf6b", + "Done": "8cfa78d9" + }, + "startDateFieldId": "PVTF_lADOFQiz884BqcH-zhozQFQ", + "completedDateFieldId": "PVTF_lADOFQiz884BqcH-zhozQGY", + "epicRepository": "kaffeelisten/.github", + "contributing": "https://github.com/kaffeelisten/.github/blob/main/CONTRIBUTING.md" +} diff --git a/scripts/conventions/project-sync.cjs b/scripts/conventions/project-sync.cjs new file mode 100644 index 0000000..6a3c763 --- /dev/null +++ b/scripts/conventions/project-sync.cjs @@ -0,0 +1,124 @@ +// Keep the organisation board (config.projectUrl) in step with issues and pull requests in the +// calling repository. Needs PROJECTS_TOKEN: GITHUB_TOKEN cannot write an organisation project. +// Sets Status, Start date and Completed date only. Never closes issues, merges or deploys. + +const config = require('./project-config.json'); +const { issueReferences } = require('./pr-conventions.cjs'); + +// Same parser as the PR conventions check, so a reference that passes CI also moves the board. +function closingIssues(body, owner, repo) { + return issueReferences(body, owner, repo).closes; +} + +function pullRequestStatus(pr) { + if (pr.state === 'closed') return pr.merged ? 'Done' : 'Backlog'; + return pr.draft ? 'In progress' : 'In review'; +} + +async function syncProject({ github, context, core }) { + const { owner, repo } = context.repo; + if (owner !== config.owner) throw new Error(`Unexpected owner ${owner}`); + const here = `${owner}/${repo}`; + let openPulls; + const statuses = new Map(); + + async function currentPullStatus(pr) { + if (pr.state === 'closed' || pr.draft || !pr.node_id) return pullRequestStatus(pr); + if (!statuses.has(pr.node_id)) { + const result = await github.graphql('query($id:ID!){node(id:$id){... on PullRequest{reviewDecision}}}', { id: pr.node_id }); + statuses.set(pr.node_id, result.node?.reviewDecision === 'CHANGES_REQUESTED' ? 'In progress' : 'In review'); + } + return statuses.get(pr.node_id); + } + async function activePulls() { + if (!openPulls) openPulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100 }); + return openPulls; + } + const field = (item, fieldId, value) => github.graphql( + 'mutation($p:ID!,$i:ID!,$f:ID!,$v:ProjectV2FieldValue!){updateProjectV2ItemFieldValue(input:{projectId:$p,itemId:$i,fieldId:$f,value:$v}){projectV2Item{id}}}', + { p: config.projectId, i: item, f: fieldId, v: value }, + ); + + async function setItem(contentId, status, dates = {}) { + async function findItem() { + let after = null; + do { + const result = await github.graphql(`query($c:ID!,$a:String){node(id:$c){ + ... on Issue{projectItems(first:100,after:$a,includeArchived:true){nodes{id project{id}} pageInfo{hasNextPage endCursor}}} + ... on PullRequest{projectItems(first:100,after:$a,includeArchived:true){nodes{id project{id}} pageInfo{hasNextPage endCursor}}}}}`, { c: contentId, a: after }); + const page = result.node.projectItems; + const found = page.nodes.find((entry) => entry.project.id === config.projectId); + if (found) return found.id; + after = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null; + } while (after); + return null; + } + let item = await findItem(); + if (!item) { + try { + const added = await github.graphql('mutation($p:ID!,$c:ID!){addProjectV2ItemById(input:{projectId:$p,contentId:$c}){item{id}}}', { p: config.projectId, c: contentId }); + item = added.addProjectV2ItemById.item.id; + } catch (error) { + item = await findItem(); + if (!item) throw error; + } + } + await field(item, config.statusFieldId, { singleSelectOptionId: config.statusOptions[status] }); + if (dates.completed) { + await field(item, config.completedDateFieldId, { date: dates.completed }); + } else if (dates.clearCompleted) { + await github.graphql('mutation($p:ID!,$i:ID!,$f:ID!){clearProjectV2ItemFieldValue(input:{projectId:$p,itemId:$i,fieldId:$f}){projectV2Item{id}}}', { p: config.projectId, i: item, f: config.completedDateFieldId }); + } + if (status === 'In progress' || status === 'In review') { + const current = await github.graphql('query($id:ID!){node(id:$id){... on ProjectV2Item{fieldValueByName(name:"Start date"){... on ProjectV2ItemFieldDateValue{date}}}}}', { id: item }); + if (!current.node.fieldValueByName?.date) await field(item, config.startDateFieldId, { date: new Date().toISOString().slice(0, 10) }); + } + } + + async function syncIssue(issue, fallback) { + if (issue.pull_request) return; + if (issue.state === 'closed') return setItem(issue.node_id, 'Done', { completed: issue.closed_at.slice(0, 10) }); + const [o, r] = (issue.repository_url || '').split('/').slice(-2); + const active = (await activePulls()).filter((pr) => closingIssues(pr.body, owner, repo) + .some((ref) => ref.number === issue.number && ref.repo === `${o}/${r}`)); + if (active.length) { + const states = await Promise.all(active.map(currentPullStatus)); + return setItem(issue.node_id, states.includes('In progress') ? 'In progress' : 'In review', { clearCompleted: true }); + } + if (fallback) await setItem(issue.node_id, fallback, { clearCompleted: true }); + // Unlinked open issues keep their triaged Ready, Blocked or Backlog state. + } + + async function syncPullRequest(pr) { + await setItem(pr.node_id, await currentPullStatus(pr), pr.merged_at ? { completed: pr.merged_at.slice(0, 10) } : { clearCompleted: true }); + for (const ref of closingIssues(pr.body, owner, repo)) { + const [o, r] = ref.repo.split('/'); + if (o !== config.owner) continue; + try { + const { data: issue } = await github.rest.issues.get({ owner: o, repo: r, issue_number: ref.number }); + // A merge into another stack layer does not complete the issue. + await syncIssue(issue, pr.state === 'closed' && !pr.merged ? 'Ready' : pr.draft ? 'In progress' : 'In review'); + } catch (error) { + core.warning(`Could not sync ${ref.repo}#${ref.number}: ${error.message}`); + } + } + } + + if (context.payload.pull_request) { + const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: context.payload.pull_request.number }); + await syncPullRequest(pr); + } else if (context.payload.issue) { + const { data: issue } = await github.rest.issues.get({ owner, repo, issue_number: context.payload.issue.number }); + await syncIssue(issue, context.payload.action === 'reopened' ? 'Ready' : context.payload.action === 'opened' ? 'Backlog' : undefined); + } else { + for (const pr of await activePulls()) await syncPullRequest(pr); + for await (const response of github.paginate.iterator(github.rest.issues.listForRepo, { owner, repo, state: 'all', per_page: 100 })) { + for (const issue of response.data) await syncIssue(issue); + } + } + core.info(`${here}: board synchronized. No merge, deployment or issue-close action was performed.`); +} + +module.exports = syncProject; +module.exports.closingIssues = closingIssues; +module.exports.pullRequestStatus = pullRequestStatus; diff --git a/scripts/conventions/sub-issue-rollup.cjs b/scripts/conventions/sub-issue-rollup.cjs new file mode 100644 index 0000000..7b3b581 --- /dev/null +++ b/scripts/conventions/sub-issue-rollup.cjs @@ -0,0 +1,71 @@ +// When the last sub-issue of an epic closes, flag the epic for acceptance. +// The epic is never closed automatically: it closes after its outcome is checked. +// +// Epics live in kaffeelisten/.github and their children in any organisation repository, and a +// repository's GITHUB_TOKEN can only write to itself. So there are two entry points: +// - `run` handles an issue event in any repository whose parent lives in the same repository; +// - `sweep` runs in kaffeelisten/.github on a schedule and checks every open epic there, +// whatever repository its children are in. + +const LABEL = 'ready-for-acceptance'; +const MARKER = ''; + +function decide({ action, parent }) { + if (!parent || parent.state !== 'OPEN') return { kind: 'none' }; + const { total, completed } = parent.subIssuesSummary; + const labelled = parent.labels.nodes.some((l) => l.name === LABEL); + const done = total > 0 && completed === total; + if ((action === 'closed' || action === 'sweep') && done && !labelled) return { kind: 'ready', total }; + if ((action === 'reopened' || action === 'sweep') && !done && labelled) return { kind: 'unready' }; + return { kind: 'none' }; +} + +async function apply({ github, core, owner, repo, parent, decision, trigger }) { + if (decision.kind === 'ready') { + await github.rest.issues.addLabels({ owner, repo, issue_number: parent.number, labels: [LABEL] }); + const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: parent.number, per_page: 100 }); + if (!comments.some((c) => (c.body || '').includes(MARKER))) { + await github.rest.issues.createComment({ + owner, repo, issue_number: parent.number, + body: `${MARKER}\nAll ${decision.total} sub-issues are closed${trigger ? ` (last: ${trigger})` : ''}. Check the outcome above end to end, then close this epic.`, + }); + } + core.info(`#${parent.number} is ready for acceptance.`); + } else if (decision.kind === 'unready') { + await github.rest.issues.removeLabel({ owner, repo, issue_number: parent.number, name: LABEL }); + core.info(`A sub-issue of #${parent.number} reopened; removed ${LABEL}.`); + } +} + +async function run({ github, context, core }) { + const { owner, repo } = context.repo; + const number = context.payload.issue.number; + const result = await github.graphql( + `query($o:String!,$r:String!,$n:Int!){repository(owner:$o,name:$r){issue(number:$n){ + parent{number state repository{nameWithOwner} subIssuesSummary{total completed} labels(first:50){nodes{name}}}}}}`, + { o: owner, r: repo, n: number }, + ); + const parent = result.repository.issue.parent; + if (!parent) return; + if (parent.repository.nameWithOwner !== `${owner}/${repo}`) { + core.info(`Parent ${parent.repository.nameWithOwner}#${parent.number} is in another repository; its scheduled sweep handles it.`); + return; + } + await apply({ github, core, owner, repo, parent, decision: decide({ action: context.payload.action, parent }), trigger: `#${number}` }); +} + +async function sweep({ github, context, core }) { + const { owner, repo } = context.repo; + const result = await github.graphql( + `query($q:String!){search(type:ISSUE,query:$q,first:100){nodes{... on Issue{ + number state subIssuesSummary{total completed} labels(first:50){nodes{name}}}}}}`, + { q: `repo:${owner}/${repo} is:issue is:open label:type:epic` }, + ); + for (const parent of result.search.nodes) { + await apply({ github, core, owner, repo, parent, decision: decide({ action: 'sweep', parent }) }); + } +} + +module.exports = run; +module.exports.sweep = sweep; +module.exports.decide = decide; diff --git a/workflow-templates/conventions.properties.json b/workflow-templates/conventions.properties.json new file mode 100644 index 0000000..afe451c --- /dev/null +++ b/workflow-templates/conventions.properties.json @@ -0,0 +1,6 @@ +{ + "name": "Kaffeelisten conventions", + "description": "PR title, type label, linked issue, assignee and milestone checks, /take and /drop, sub-issue roll-up and board sync, shared from kaffeelisten/.github.", + "iconName": "octicon checklist", + "categories": ["Automation"] +} diff --git a/workflow-templates/conventions.yml b/workflow-templates/conventions.yml new file mode 100644 index 0000000..3eb6ad3 --- /dev/null +++ b/workflow-templates/conventions.yml @@ -0,0 +1,25 @@ +name: Conventions + +# Calls the organisation's shared conventions in kaffeelisten/.github. Pair it with a +# `.github/labeler.yml` that maps this repository's folders to its `area:*` labels. +on: + pull_request_target: + types: [opened, edited, reopened, synchronize, ready_for_review, converted_to_draft, labeled, unlabeled, closed] + issues: + types: [opened, reopened, closed, assigned, labeled] + issue_comment: + types: [created] + schedule: + - cron: '23 5 * * *' + workflow_dispatch: + +permissions: {} + +jobs: + conventions: + uses: kaffeelisten/.github/.github/workflows/org-conventions.yml@main + permissions: + contents: read + issues: write + pull-requests: write + secrets: inherit