From 2191a8cd5762008c90d5a35cbfd42f04871fbb5e Mon Sep 17 00:00:00 2001 From: Oleh Martsokha Date: Sat, 28 Nov 2026 09:11:57 +0100 Subject: [PATCH 1/6] feat: instant project add, TypeScript scripts, named steps GitHub runs the 15-minute project sync hours apart, so new issues and pull requests waited that long for the project. A reusable project-add workflow, called by each public repository on open, now adds them at once; the sync stays as the backfill. The scripts are TypeScript, run directly by Node 24 with no build step, and checked by Biome and tsc in a new Build workflow. The label sync paginates repositories and labels instead of stopping at 100. Workflow steps are named as in the other repositories, the actions are on their current majors (checkout v7, setup-node v7, create-github-app-token v3), and the app is identified by its public client ID, replacing the deprecated app-id input and the PROJECT_APP_ID variable. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 54 ++++ .github/workflows/labels.yml | 33 ++- .github/workflows/project-add.yml | 49 ++++ .github/workflows/project-sync.yml | 32 ++- .gitignore | 2 + README.md | 55 +++- biome.json | 32 +++ package-lock.json | 260 ++++++++++++++++++ package.json | 21 ++ scripts/labels-sync.mjs | 75 ----- scripts/labels-sync.ts | 130 +++++++++ scripts/{project-sync.mjs => project-sync.ts} | 95 +++++-- tsconfig.json | 23 ++ 13 files changed, 731 insertions(+), 130 deletions(-) create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/project-add.yml create mode 100644 .gitignore create mode 100644 biome.json create mode 100644 package-lock.json create mode 100644 package.json delete mode 100644 scripts/labels-sync.mjs create mode 100644 scripts/labels-sync.ts rename scripts/{project-sync.mjs => project-sync.ts} (65%) create mode 100644 tsconfig.json diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..bf35335 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,54 @@ +name: Build + +env: + NODE_VERSION: "24" + +on: + push: + branches: + - "main" + paths: + - "scripts/**" + - "package.json" + - "package-lock.json" + - "tsconfig.json" + - "biome.json" + - ".github/workflows/build.yml" + pull_request: + paths: + - "scripts/**" + - "package.json" + - "package-lock.json" + - "tsconfig.json" + - "biome.json" + - ".github/workflows/build.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + lint: + name: Lint & Format + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@v7 + with: + node-version: ${{ env.NODE_VERSION }} + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Run Biome check + run: npm run check + + - name: Check TypeScript + run: npm run typecheck diff --git a/.github/workflows/labels.yml b/.github/workflows/labels.yml index 0536b19..a793596 100644 --- a/.github/workflows/labels.yml +++ b/.github/workflows/labels.yml @@ -1,12 +1,19 @@ name: Labels +env: + NODE_VERSION: "24" + # Brings the shared labels in labels.yml to every public repository: creates # the missing ones and corrects colour and description. Labels a repository # keeps for its own areas are never touched or deleted. on: push: - branches: [main] - paths: [labels.yml, scripts/labels-sync.mjs] + branches: + - "main" + paths: + - "labels.yml" + - "scripts/labels-sync.ts" + - ".github/workflows/labels.yml" workflow_dispatch: permissions: @@ -14,23 +21,31 @@ permissions: jobs: sync: + name: Sync labels runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - name: Checkout + uses: actions/checkout@v7 + with: + persist-credentials: false - - uses: actions/setup-node@v4 + - name: Setup Node.js + uses: actions/setup-node@v7 with: - node-version: 24 + node-version: ${{ env.NODE_VERSION }} - - id: app - uses: actions/create-github-app-token@v2 + - name: Create app token + id: app + uses: actions/create-github-app-token@v3 with: - app-id: ${{ vars.PROJECT_APP_ID }} + # nvisy-bot. A client ID is public; only the private key is a secret. + client-id: Iv23li4OFiUQmJcoK9mo private-key: ${{ secrets.PROJECT_APP_PRIVATE_KEY }} owner: ${{ github.repository_owner }} - - run: node scripts/labels-sync.mjs + - name: Sync labels + run: node scripts/labels-sync.ts env: GH_TOKEN: ${{ steps.app.outputs.token }} ORG: ${{ github.repository_owner }} diff --git a/.github/workflows/project-add.yml b/.github/workflows/project-add.yml new file mode 100644 index 0000000..36f664d --- /dev/null +++ b/.github/workflows/project-add.yml @@ -0,0 +1,49 @@ +name: Project add + +# Reusable: every public repository calls this when an issue or pull request +# opens, so the item reaches the "Nvisy OSS" project at once instead of at the +# next project-sync backfill. Bot pull requests are left out, as in the sync. +# +# The caller passes `secrets: inherit`; it sees PROJECT_APP_PRIVATE_KEY only +# when that secret is set at the organization level. +# See the README for the caller workflow. +on: + workflow_call: + +permissions: + contents: read + +jobs: + add: + name: Add to project + runs-on: ubuntu-latest + timeout-minutes: 5 + if: github.event.pull_request.user.type != 'Bot' + steps: + - name: Create app token + id: app + uses: actions/create-github-app-token@v3 + with: + # nvisy-bot. A client ID is public; only the private key is a secret. + client-id: Iv23li4OFiUQmJcoK9mo + private-key: ${{ secrets.PROJECT_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + + # Adding an item already on the project changes nothing, so reopened and + # transferred items are safe to send again. + - name: Add to project + env: + GH_TOKEN: ${{ steps.app.outputs.token }} + ORG: ${{ github.repository_owner }} + PROJECT_NUMBER: "7" + CONTENT_ID: ${{ github.event.issue.node_id || github.event.pull_request.node_id }} + ITEM: ${{ github.repository }}#${{ github.event.issue.number || github.event.pull_request.number }} + run: | + project=$(gh api graphql \ + -f query='query($org: String!, $number: Int!) { organization(login: $org) { projectV2(number: $number) { id } } }' \ + -f org="$ORG" -F number="$PROJECT_NUMBER" \ + -q .data.organization.projectV2.id) + gh api graphql --silent \ + -f query='mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }' \ + -f project="$project" -f content="$CONTENT_ID" + echo "Added $ITEM" diff --git a/.github/workflows/project-sync.yml b/.github/workflows/project-sync.yml index a10b4bb..1ddc31c 100644 --- a/.github/workflows/project-sync.yml +++ b/.github/workflows/project-sync.yml @@ -1,7 +1,13 @@ name: Project sync -# Adds every open issue and human pull request in the organization's public -# repositories to the "Nvisy OSS" project. Safe to run any number of times. +env: + NODE_VERSION: "24" + +# Backfill for the "Nvisy OSS" project: adds every open issue and human pull +# request in the organization's public repositories that is not on it yet. +# New items normally arrive the moment they open, through project-add.yml; +# this catches what that missed. GitHub runs schedules late and drops some +# under load, so the cron is a ceiling on frequency, not a promise. on: schedule: - cron: "*/15 * * * *" @@ -21,25 +27,33 @@ concurrency: jobs: sync: + name: Sync project runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - name: Checkout + uses: actions/checkout@v7 + with: + persist-credentials: false - - uses: actions/setup-node@v4 + - name: Setup Node.js + uses: actions/setup-node@v7 with: - node-version: 24 + node-version: ${{ env.NODE_VERSION }} # The default GITHUB_TOKEN cannot write to organization projects, so the # sync runs as the organization's project app. - - id: app - uses: actions/create-github-app-token@v2 + - name: Create app token + id: app + uses: actions/create-github-app-token@v3 with: - app-id: ${{ vars.PROJECT_APP_ID }} + # nvisy-bot. A client ID is public; only the private key is a secret. + client-id: Iv23li4OFiUQmJcoK9mo private-key: ${{ secrets.PROJECT_APP_PRIVATE_KEY }} owner: ${{ github.repository_owner }} - - run: node scripts/project-sync.mjs + - name: Sync project + run: node scripts/project-sync.ts env: GH_TOKEN: ${{ steps.app.outputs.token }} ORG: ${{ github.repository_owner }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2752eb9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.DS_Store diff --git a/README.md b/README.md index 9ca1b76..6b874f9 100644 --- a/README.md +++ b/README.md @@ -5,14 +5,53 @@ Organization-wide defaults and automation for Nvisy's open-source repositories. - **Issue forms and pull request template** (`.github/`): used by every repository that has none of its own. The forms set the organization's issue types (Bug, Feature, Task). -- **Project sync** (`scripts/project-sync.mjs`, every 15 minutes): adds every - open issue and human pull request in a public repository to the - [Nvisy OSS](https://github.com/orgs/nvisycom/projects/7) project. Status - after that is kept by the project's built-in workflows. +- **Project add** (`.github/workflows/project-add.yml`): a reusable workflow + that adds an issue or human pull request to the + [Nvisy OSS](https://github.com/orgs/nvisycom/projects/7) project the moment + it opens. Each public repository calls it (see below). +- **Project sync** (`scripts/project-sync.ts`): the backfill. On a 15-minute + schedule, which GitHub runs late and sometimes hours apart, it adds any open + issue or human pull request the project is missing, so a repository without + the caller is still covered. Status after that is kept by the project's + built-in workflows. - **Labels** (`labels.yml`): the labels every public repository shares, synced on change. Repositories keep their own area labels alongside. -Both workflows authenticate as the organization's project app: its id in the -`PROJECT_APP_ID` variable and its key in the `PROJECT_APP_PRIVATE_KEY` secret. -Run either script locally with `GH_TOKEN=$(gh auth token)`; set `DRY_RUN=1` on -the project sync to see what it would add. +## Calling project add + +Each public repository carries this as `.github/workflows/project.yml`: + +```yaml +name: Project + +on: + issues: + types: [opened, reopened, transferred] + pull_request_target: + types: [opened, reopened] + +permissions: {} + +jobs: + add: + name: Add to project + uses: nvisycom/.github/.github/workflows/project-add.yml@main + secrets: inherit +``` + +`pull_request_target` lets pull requests from forks through too. It is safe +here because the workflow never checks out or runs the pull request's code. + +## Authentication + +All three workflows run as the organization's `nvisy-bot` app. Its client ID +is in the workflows; its private key is the `PROJECT_APP_PRIVATE_KEY` secret, +which must be set at the organization level for the callers in other +repositories to see it. + +## Development + +The scripts are TypeScript that Node 24 runs directly, so there is no build +step. `npm ci` installs Biome and the type checker for `npm run check` and +`npm run typecheck`. Run either script locally with +`GH_TOKEN=$(gh auth token)`; set `DRY_RUN=1` to see what it would change. diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..dc2d742 --- /dev/null +++ b/biome.json @@ -0,0 +1,32 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.6.9/schema.json", + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, + "files": { + "ignoreUnknown": false, + "includes": ["**", "!node_modules", "!.claude"] + }, + "formatter": { + "enabled": true, + "indentStyle": "tab" + }, + "assist": { "actions": { "source": { "preset": "recommended" } } }, + "linter": { + "enabled": true, + "rules": { + "preset": "recommended", + "style": { + "preset": "recommended", + "noNonNullAssertion": "off" + } + } + }, + "javascript": { + "formatter": { + "quoteStyle": "double" + } + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..efe0466 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,260 @@ +{ + "name": "@nvisy/github", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@nvisy/github", + "devDependencies": { + "@biomejs/biome": "^2.5.11", + "@types/node": "^26.4.0", + "typescript": "^5.9.3" + }, + "engines": { + "node": ">=24.0.0" + } + }, + "node_modules/@biomejs/biome": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.6.9.tgz", + "integrity": "sha512-RelCBDzTXu4DBU8c35P4iMrDO80SUjW0OgjDA7CT1z3UcCU5IclWTZ2XnMelI4frQL//xg2K2BQxAhcOKxdPQA==", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-android-arm64": "2.6.9", + "@biomejs/cli-android-x64": "2.6.9", + "@biomejs/cli-darwin-arm64": "2.6.9", + "@biomejs/cli-darwin-x64": "2.6.9", + "@biomejs/cli-linux-arm64": "2.6.9", + "@biomejs/cli-linux-arm64-musl": "2.6.9", + "@biomejs/cli-linux-x64": "2.6.9", + "@biomejs/cli-linux-x64-musl": "2.6.9", + "@biomejs/cli-win32-arm64": "2.6.9", + "@biomejs/cli-win32-x64": "2.6.9" + } + }, + "node_modules/@biomejs/cli-android-arm64": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-arm64/-/cli-android-arm64-2.6.9.tgz", + "integrity": "sha512-/3Aj5aiG+Iz8yDBJJb/GFDsptr9ONk3n1wZUIERuU+pVXMIslBaOnrTYJI5QVVXZ9jE494myQHiIvFrjQCBYeQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-android-x64": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-x64/-/cli-android-x64-2.6.9.tgz", + "integrity": "sha512-erjbUpD9KJhzTsGHY9oStJ1bSiUJ1ikUXgdr0iOFoIAMiKqW+GdVdEqAlEyqiZA6CBiFqf2fV+g0AVl3hYOuYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.6.9.tgz", + "integrity": "sha512-fO67s0SF+lKGhNPQ7jUXiz0yXGl/1Qm3XTIn/4Hd2Z2z3ewQMrotWIMVdIPxZAgLJdQtRLBOzgsTRzTl981yWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.6.9.tgz", + "integrity": "sha512-RdjT3Z6dLlii0x6EroncTp9jg38FMx2R1aeaaU4BbZ4//3TJ2mA2R39KMIrZYxHdHXcfv9X2V5hwKkXhg08w/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.6.9.tgz", + "integrity": "sha512-x73OpQSuQLuvNfzXWEjf0mK95NxlJQX4eG/jmuSrGWOz+/jcLUE4N/21yBu3n0X+wa8bJ3NsWNvmNacLnyc2CQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.6.9.tgz", + "integrity": "sha512-qoG0R5MhJ8VFozVFZQC42V3qCI1TInDhL/YcPPg0oTzfv3vuh0ZDXj+2nNahq8gboHUMv7MWpGjRDLhpQatJ+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.6.9.tgz", + "integrity": "sha512-uVrqS0HDjRzFlx88ZpfmlZvJ+xIwTU+110vunzrYvZQ5OqXl/1ugMTNvAs61hejH7jh7iequKJwagRVarrYcSQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.6.9.tgz", + "integrity": "sha512-o73Sk1hCbGOFOrDlxtpHGIubnLwMXscT32+ujMwUyq9o0f4onxO7OznzkFgcZGbwKy1R3ohroOkqZDXqj1u29g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.6.9.tgz", + "integrity": "sha512-4yvNG4nQGJsJA/PTVAt8IBFXvY6hXk4UdjtPlTf4QTMIjH7ysOwBew78bKThkRv1eyRwH2mGLIk4lAZp8tfAdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.6.9.tgz", + "integrity": "sha512-mwarNc4GEg5JknsRaJDyJDFr4kICD7snsGM8yYFOoIHimSU1ekWNbcZ44QDa6/30fUZC9077wbBpXE8fp03aug==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@types/node": { + "version": "26.6.11", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz", + "integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..fd1204a --- /dev/null +++ b/package.json @@ -0,0 +1,21 @@ +{ + "name": "@nvisy/github", + "private": true, + "description": "Organization-wide defaults and automation for Nvisy's open-source repositories", + "type": "module", + "scripts": { + "check": "biome check .", + "check:fix": "biome check --write .", + "typecheck": "tsc", + "labels": "node scripts/labels-sync.ts", + "project-sync": "node scripts/project-sync.ts" + }, + "devDependencies": { + "@biomejs/biome": "^2.5.11", + "@types/node": "^26.4.0", + "typescript": "^5.9.3" + }, + "engines": { + "node": ">=24.0.0" + } +} diff --git a/scripts/labels-sync.mjs b/scripts/labels-sync.mjs deleted file mode 100644 index 9dc1e62..0000000 --- a/scripts/labels-sync.mjs +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env node -/** - * Create or correct the labels in labels.yml in every public, unarchived - * repository of the organization. Never deletes a label. - * - * Environment: GH_TOKEN (issues read/write on the repositories), ORG, and - * DRY_RUN="1" to report the changes without making them. - */ -import { readFile } from "node:fs/promises"; - -const ORG = process.env.ORG ?? "nvisycom"; -const TOKEN = process.env.GH_TOKEN; -const DRY_RUN = process.env.DRY_RUN === "1"; -if (!TOKEN) { - console.error("GH_TOKEN is not set"); - process.exit(1); -} - -async function api(path, init = {}) { - const response = await fetch(`https://api.github.com${path}`, { - ...init, - headers: { - authorization: `Bearer ${TOKEN}`, - accept: "application/vnd.github+json", - "content-type": "application/json", - "user-agent": "nvisycom-labels-sync", - }, - }); - if (!response.ok && response.status !== 404) { - throw new Error(`${init.method ?? "GET"} ${path}: ${response.status} ${await response.text()}`); - } - return response.status === 404 ? null : response.json(); -} - -/** labels.yml is a flat list of name/color/description, so parse it by hand. */ -function parse(text) { - const labels = []; - for (const line of text.split("\n")) { - const m = line.match(/^\s*-?\s*(name|color|description):\s*(.*)$/); - if (!m) continue; - if (m[1] === "name") labels.push({}); - labels[labels.length - 1][m[1]] = m[2].trim(); - } - return labels; -} - -const wanted = parse(await readFile("labels.yml", "utf8")); -const repos = (await api(`/orgs/${ORG}/repos?type=public&per_page=100`)).filter( - (repo) => !repo.archived, -); - -for (const repo of repos) { - const have = new Map( - (await api(`/repos/${ORG}/${repo.name}/labels?per_page=100`)).map((l) => [ - l.name.toLowerCase(), - l, - ]), - ); - for (const label of wanted) { - const current = have.get(label.name.toLowerCase()); - if (!current) { - if (!DRY_RUN) await api(`/repos/${ORG}/${repo.name}/labels`, { - method: "POST", - body: JSON.stringify(label), - }); - console.log(`${repo.name}: ${DRY_RUN ? "would create" : "created"} ${label.name}`); - } else if (current.color !== label.color || (current.description ?? "") !== label.description) { - if (!DRY_RUN) await api(`/repos/${ORG}/${repo.name}/labels/${encodeURIComponent(current.name)}`, { - method: "PATCH", - body: JSON.stringify({ color: label.color, description: label.description }), - }); - console.log(`${repo.name}: ${DRY_RUN ? "would update" : "updated"} ${label.name}`); - } - } -} diff --git a/scripts/labels-sync.ts b/scripts/labels-sync.ts new file mode 100644 index 0000000..b197e6d --- /dev/null +++ b/scripts/labels-sync.ts @@ -0,0 +1,130 @@ +#!/usr/bin/env node +/** + * Create or correct the labels in labels.yml in every public, unarchived + * repository of the organization. Never deletes a label. + * + * Environment: GH_TOKEN (issues read/write on the repositories), ORG, and + * DRY_RUN="1" to report the changes without making them. + */ +import { readFile } from "node:fs/promises"; + +const ORG = process.env.ORG ?? "nvisycom"; +const TOKEN = process.env.GH_TOKEN; +const DRY_RUN = process.env.DRY_RUN === "1"; +if (!TOKEN) { + console.error("GH_TOKEN is not set"); + process.exit(1); +} + +interface Label { + name: string; + color: string; + description: string; +} + +interface Repository { + name: string; + archived: boolean; +} + +async function api(path: string, init: RequestInit = {}): Promise { + const response = await fetch(`https://api.github.com${path}`, { + ...init, + headers: { + authorization: `Bearer ${TOKEN}`, + accept: "application/vnd.github+json", + "content-type": "application/json", + "user-agent": "nvisycom-labels-sync", + }, + }); + if (!response.ok) { + throw new Error( + `${init.method ?? "GET"} ${path}: ${response.status} ${await response.text()}`, + ); + } + return (await response.json()) as T; +} + +/** Every item of a paginated list endpoint, 100 per page. */ +async function all(path: string): Promise { + const items: T[] = []; + const separator = path.includes("?") ? "&" : "?"; + for (let page = 1; ; page++) { + const batch = await api( + `${path}${separator}per_page=100&page=${page}`, + ); + items.push(...batch); + if (batch.length < 100) return items; + } +} + +/** labels.yml is a flat list of name/color/description, so parse it by hand. */ +function parse(text: string): Label[] { + const labels: Partial