Repository navigation
ci: propose the README's contributors from GitHub's list #983
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
a776a5d
docs: show every contributor's avatar in the README
M4n0x 6a02de1
ci: propose the README's contributors from GitHub's list
M4n0x 6fb00a1
docs: add axl-devhub to the README's contributors
M4n0x 40a66af
ci: keep the README contributors branch to its own pull request
M4n0x ba59bd2
ci: touch only the README contributors pull request the workflow opened
M4n0x 9d67884
ci: leave the README contributors branch alone when someone else comm…
M4n0x 9de6604
ci: count an amended README contributors commit as someone else's
M4n0x f8ef063
ci: keep a README contributors pull request open when someone added t…
M4n0x b6eb7d5
ci: leave a README contributors pull request open when its head moved
M4n0x 5c037d6
ci: respect a closed README contributors pull request and run its job…
M4n0x feea23f
ci: tell the workflow's own closures from a maintainer's
M4n0x c750598
ci: stop when the closed README contributors pull request lookup fails
M4n0x 5fd3aa4
ci: decide the README contributors veto by who closed the pull request
M4n0x 88f8291
ci: tie a maintainer's no to the README contributors list, not one co…
M4n0x File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| // Keeps the contributors' avatars in README.md in step with GitHub's contributors list. | ||
| // .github/workflows/readme-contributors.yml runs the default branch's copy of this module. | ||
| import { readFileSync, writeFileSync } from "node:fs"; | ||
|
|
||
| export const START = "<!-- contributors:start -->"; | ||
| export const END = "<!-- contributors:end -->"; | ||
|
|
||
| /** Automation that GitHub lists as a user rather than a bot. */ | ||
| export const EXCLUDED = new Set(["semantic-release-bot"]); | ||
|
|
||
| /** A second account of someone already listed, counted under their first. Keys are lowercase. */ | ||
| export const ALIASES = new Map([["alexandrebucci", "albucci"]]); | ||
|
|
||
| const LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/; | ||
|
|
||
| /** Logins to show, most contributions first; ties keep GitHub's order. */ | ||
| export function pickContributors(contributors) { | ||
| const people = new Map(); | ||
| for (const contributor of contributors ?? []) { | ||
| const login = contributor?.login; | ||
| if (contributor?.type !== "User" || typeof login !== "string" || !LOGIN.test(login)) continue; | ||
| const lower = login.toLowerCase(); | ||
| if (EXCLUDED.has(lower)) continue; | ||
| const key = ALIASES.get(lower) ?? lower; | ||
| const person = people.get(key) ?? { login: ALIASES.has(lower) ? ALIASES.get(lower) : login, contributions: 0 }; | ||
| if (lower === key) person.login = login; | ||
| person.contributions += Number(contributor.contributions) || 0; | ||
| people.set(key, person); | ||
| } | ||
| return [...people.values()].sort((a, b) => b.contributions - a.contributions).map((person) => person.login); | ||
| } | ||
|
|
||
| export function renderAvatars(logins) { | ||
| const links = logins.map( | ||
| (login) => | ||
| ` <a href="https://github.com/${login}"><img src="https://github.com/${login}.png?size=96" width="48" height="48" alt="${login}"></a>`, | ||
| ); | ||
| return ["<p>", ...links, "</p>"].join("\n"); | ||
| } | ||
|
|
||
| /** The README with the avatars between the markers replaced. */ | ||
| export function replaceAvatars(readme, logins) { | ||
| const start = readme.indexOf(START); | ||
| const end = readme.indexOf(END); | ||
| if (start === -1 || end < start) throw new Error(`README.md needs ${START} and ${END} around the avatars.`); | ||
| // An empty list means GitHub's answer went wrong, not that everyone left. | ||
| if (logins.length === 0) throw new Error("GitHub listed no contributors; leaving README.md as it is."); | ||
| return `${readme.slice(0, start + START.length)}\n${renderAvatars(logins)}\n${readme.slice(end)}`; | ||
| } | ||
|
|
||
| /** Rewrites README.md from GitHub's list and returns whether it changed. */ | ||
| export async function updateReadme({ github, context, core, path = "README.md" }) { | ||
| const { owner, repo } = context.repo; | ||
| const contributors = await github.paginate(github.rest.repos.listContributors, { owner, repo, per_page: 100 }); | ||
| const logins = pickContributors(contributors); | ||
| const before = readFileSync(path, "utf8"); | ||
| const after = replaceAvatars(before, logins); | ||
| const changed = after !== before; | ||
| if (changed) writeFileSync(path, after); | ||
| core.info(`${logins.length} contributors: ${logins.join(", ")}. README.md ${changed ? "updated" : "unchanged"}.`); | ||
| return changed; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import { test } from "node:test"; | ||
| import assert from "node:assert/strict"; | ||
| import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; | ||
| import { tmpdir } from "node:os"; | ||
| import { join } from "node:path"; | ||
| import { END, START, pickContributors, renderAvatars, replaceAvatars, updateReadme } from "./readme-contributors.mjs"; | ||
|
|
||
| const user = (login, contributions) => ({ login, type: "User", contributions }); | ||
|
|
||
| test("orders people by contributions and keeps GitHub's order for ties", () => { | ||
| const logins = pickContributors([user("a", 5), user("b", 1), user("c", 9), user("d", 1)]); | ||
| assert.deepEqual(logins, ["c", "a", "b", "d"]); | ||
| }); | ||
|
|
||
| test("leaves out bots, release automation and malformed logins", () => { | ||
| const logins = pickContributors([ | ||
| user("M4n0x", 10), | ||
| { login: "dependabot[bot]", type: "Bot", contributions: 4 }, | ||
| user("semantic-release-bot", 20), | ||
| user('x"><script>', 3), | ||
| { type: "Anonymous", contributions: 2 }, | ||
| ]); | ||
| assert.deepEqual(logins, ["M4n0x"]); | ||
| }); | ||
|
|
||
| test("counts a second account under the first one", () => { | ||
| const logins = pickContributors([user("albucci", 4), user("MaHofseth", 3), user("alexandrebucci", 1)]); | ||
| assert.deepEqual(logins, ["albucci", "MaHofseth"]); | ||
| }); | ||
|
|
||
| test("shows the main account even when only the second one is listed", () => { | ||
| assert.deepEqual(pickContributors([user("alexandrebucci", 1)]), ["albucci"]); | ||
| }); | ||
|
|
||
| test("replaces only what is between the markers", () => { | ||
| const readme = `# Title\n\n${START}\n<p>\n old\n</p>\n${END}\n\nAfter.\n`; | ||
| const updated = replaceAvatars(readme, ["a", "b"]); | ||
| assert.equal(updated, `# Title\n\n${START}\n${renderAvatars(["a", "b"])}\n${END}\n\nAfter.\n`); | ||
| assert.equal(replaceAvatars(updated, ["a", "b"]), updated); | ||
| }); | ||
|
|
||
| test("refuses a README without markers or an empty list", () => { | ||
| assert.throws(() => replaceAvatars("# Title\n", ["a"]), /needs/); | ||
| assert.throws(() => replaceAvatars(`${END}\n${START}\n`, ["a"]), /needs/); | ||
| assert.throws(() => replaceAvatars(`${START}\n${END}\n`, []), /no contributors/); | ||
| }); | ||
|
|
||
| test("draws each avatar as a linked 48-point image", () => { | ||
| assert.equal( | ||
| renderAvatars(["Seb-GRAF"]), | ||
| '<p>\n <a href="https://github.com/Seb-GRAF"><img src="https://github.com/Seb-GRAF.png?size=96" width="48" height="48" alt="Seb-GRAF"></a>\n</p>', | ||
| ); | ||
| }); | ||
|
|
||
| test("the README in the repository matches what the workflow writes for its own list", () => { | ||
| const readme = readFileSync(new URL("../../README.md", import.meta.url), "utf8"); | ||
| const block = readme.slice(readme.indexOf(START) + START.length, readme.indexOf(END)); | ||
| const logins = [...block.matchAll(/alt="([^"]+)"/g)].map((match) => match[1]); | ||
| assert.ok(logins.length > 0); | ||
| assert.equal(replaceAvatars(readme, logins), readme); | ||
| }); | ||
|
|
||
| test("updateReadme writes the file only when the list changed", async () => { | ||
| const path = join(mkdtempSync(join(tmpdir(), "readme-contributors-")), "README.md"); | ||
| writeFileSync(path, `${START}\n${END}\n`); | ||
| const listed = [user("a", 2), user("b", 1)]; | ||
| const github = { | ||
| rest: { repos: { listContributors: "listContributors" } }, | ||
| paginate: async (method, params) => { | ||
| assert.equal(method, "listContributors"); | ||
| assert.deepEqual(params, { owner: "stablebox", repo: "StableBar", per_page: 100 }); | ||
| return listed; | ||
| }, | ||
| }; | ||
| const context = { repo: { owner: "stablebox", repo: "StableBar" } }; | ||
| const core = { info() {} }; | ||
|
|
||
| assert.equal(await updateReadme({ github, context, core, path }), true); | ||
| assert.equal(readFileSync(path, "utf8"), `${START}\n${renderAvatars(["a", "b"])}\n${END}\n`); | ||
| assert.equal(await updateReadme({ github, context, core, path }), false); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,200 @@ | ||
| name: README contributors | ||
|
|
||
| # Keeps the contributors' avatars in README.md in step with GitHub's contributors list. When the | ||
| # list changes, it opens or updates a pull request from the readme-contributors branch; it never | ||
| # pushes to main. The logic and its tests are in .github/scripts/readme-contributors.mjs. | ||
| on: | ||
| schedule: | ||
| - cron: "41 6 * * 1" | ||
| workflow_dispatch: | ||
|
|
||
| permissions: {} | ||
|
|
||
| concurrency: | ||
| group: readme-contributors | ||
| cancel-in-progress: false | ||
|
|
||
| jobs: | ||
| check: | ||
| name: Compare the contributors | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 5 | ||
| permissions: | ||
| contents: read | ||
| pull-requests: write | ||
| outputs: | ||
| changed: ${{ steps.compare.outputs.result }} | ||
| steps: | ||
| - uses: actions/checkout@v7 | ||
| with: | ||
| ref: ${{ github.event.repository.default_branch }} | ||
| sparse-checkout: .github/scripts | ||
| persist-credentials: false | ||
| - id: compare | ||
| uses: actions/github-script@v9 | ||
| with: | ||
| result-encoding: string | ||
| script: | | ||
| const { updateReadme } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/readme-contributors.mjs`); | ||
| return String(await updateReadme({ github, context, core })); | ||
| - name: Close a pull request the README no longer needs | ||
| if: steps.compare.outputs.result == 'false' | ||
| env: | ||
| GH_TOKEN: ${{ github.token }} | ||
| BASE: ${{ github.event.repository.default_branch }} | ||
| BRANCH: readme-contributors | ||
| run: | | ||
| # Only pull requests this workflow opened carry the marker; --head also matches forks. | ||
| gh pr list --repo "$GITHUB_REPOSITORY" --head "$BRANCH" --base "$BASE" --state open \ | ||
| --json number,headRefOid,isCrossRepository,body --jq '.[] | select((.isCrossRepository | not) | ||
| and (.body // "" | contains("<!-- readme-contributors-workflow -->"))) | "\(.number) \(.headRefOid)"' \ | ||
| > "$RUNNER_TEMP/prs" | ||
| note="The README already shows GitHub's contributors list, so this pull request is no longer needed." | ||
| while read -r -u 3 number head; do | ||
| # Commits someone else wrote or committed, as in the pull-request job. | ||
| others=$(gh api "repos/$GITHUB_REPOSITORY/compare/$BASE...$head" --jq '[.commits[] | ||
| | select([.commit.author.email, .commit.committer.email] | ||
| | any(. != "41898282+github-actions[bot]@users.noreply.github.com"))] | length') | ||
| if [[ "$others" != 0 ]]; then | ||
| echo "::warning::#$number has commits this workflow didn't make; leaving it open." | ||
| continue | ||
| fi | ||
|
M4n0x marked this conversation as resolved.
Resolved
|
||
| # Narrows the window for a push made since the check; gh pr close can't require a head. | ||
| current=$(gh pr view "$number" --repo "$GITHUB_REPOSITORY" --json headRefOid --jq .headRefOid) | ||
| if [[ "$current" != "$head" ]]; then | ||
| echo "::warning::#$number changed during the check; leaving it open." | ||
| continue | ||
| fi | ||
| gh pr close "$number" --repo "$GITHUB_REPOSITORY" \ | ||
| --comment "$note" | ||
| done 3< "$RUNNER_TEMP/prs" | ||
|
|
||
| pull-request: | ||
| name: Open the pull request | ||
| needs: check | ||
| if: >- | ||
| needs.check.outputs.changed == 'true' && vars.RELEASE_APP_CLIENT_ID != '' | ||
| && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) | ||
| # The release app's key lives in this environment. A pull request opened with GITHUB_TOKEN | ||
| # starts no workflows, so its required checks would never run. | ||
| environment: release | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 5 | ||
| permissions: | ||
| contents: read | ||
| steps: | ||
| - name: Create release app token | ||
| id: app-token | ||
| uses: actions/create-github-app-token@v3 | ||
| with: | ||
| client-id: ${{ vars.RELEASE_APP_CLIENT_ID }} | ||
| private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} | ||
| permission-contents: write | ||
| permission-pull-requests: write | ||
| - uses: actions/checkout@v7 | ||
| with: | ||
| ref: ${{ github.event.repository.default_branch }} | ||
| sparse-checkout: .github/scripts | ||
| persist-credentials: false | ||
| - uses: actions/github-script@v9 | ||
| with: | ||
| script: | | ||
| const { updateReadme } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/readme-contributors.mjs`); | ||
| await updateReadme({ github, context, core }); | ||
| - name: Push the branch and open its pull request | ||
| env: | ||
| GH_TOKEN: ${{ steps.app-token.outputs.token }} | ||
| BASE: ${{ github.event.repository.default_branch }} | ||
| BRANCH: readme-contributors | ||
| TITLE: "docs: update the contributors' avatars in the README" | ||
| run: | | ||
| if git diff --quiet -- README.md; then | ||
| echo "$BASE caught up since the comparison." | ||
| exit 0 | ||
| fi | ||
| # Counts this repository's open pull requests from the branch, and those this workflow opened, | ||
| # which carry the marker; --head also matches forks. | ||
| read -r ours all < <(gh pr list --repo "$GITHUB_REPOSITORY" --head "$BRANCH" --state open \ | ||
| --json isCrossRepository,baseRefName,body --jq '[.[] | select(.isCrossRepository | not)] | ||
| | "\(map(select(.baseRefName == env.BASE | ||
| and (.body // "" | contains("<!-- readme-contributors-workflow -->")))) | length) \(length)"') | ||
| if (( all > ours )); then | ||
| echo "::error::A pull request this workflow didn't open uses the $BRANCH branch; leaving it alone." | ||
| exit 1 | ||
| fi | ||
| # A maintainer who closed a pull request proposing these avatars said no to them, even if the | ||
| # branch was rebuilt since; a different list asks again. The check job closes with | ||
| # GITHUB_TOKEN, which GitHub records as the github-actions bot, so the latest closer decides. | ||
| avatars() { sed -n '/<!-- contributors:start -->/,/<!-- contributors:end -->/p'; } | ||
| proposed=$(avatars < README.md) | ||
| # Assignments, so a failed lookup stops the job instead of reading as a veto or its absence. | ||
| closed=$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$BRANCH" --base "$BASE" --state closed \ | ||
| --limit 100 --json number,headRefOid,isCrossRepository,mergedAt,body \ | ||
|
M4n0x marked this conversation as resolved.
Resolved
|
||
| --jq '.[] | select((.isCrossRepository | not) and .mergedAt == null | ||
| and (.body // "" | contains("<!-- readme-contributors-workflow -->"))) | "\(.number) \(.headRefOid)"') | ||
| while read -r -u 3 number head; do | ||
| [[ -n "$number" ]] || continue | ||
| readme=$(gh api "repos/$GITHUB_REPOSITORY/contents/README.md?ref=$head" -H "Accept: application/vnd.github.raw") | ||
| [[ "$(avatars <<< "$readme")" == "$proposed" ]] || continue | ||
| # shellcheck disable=SC2016 # GraphQL variables, not shell ones. | ||
| closer=$(gh api graphql -F owner="${GITHUB_REPOSITORY%/*}" -F name="${GITHUB_REPOSITORY#*/}" \ | ||
| -F number="$number" -f query='query($owner: String!, $name: String!, $number: Int!) { | ||
| repository(owner: $owner, name: $name) { pullRequest(number: $number) { | ||
| timelineItems(itemTypes: CLOSED_EVENT, last: 1) { | ||
| nodes { ... on ClosedEvent { actor { __typename login } } } } } } }' \ | ||
| --jq '.data.repository.pullRequest.timelineItems.nodes[0].actor | ||
| | if .__typename == "Bot" and (.login == "github-actions" or .login == "github-actions[bot]") | ||
| then "workflow" else "someone" end') | ||
| if [[ "$closer" != workflow ]]; then | ||
| echo "#$number, which proposed this list, was closed by a maintainer; not proposing it again." | ||
| exit 0 | ||
| fi | ||
| done 3<<< "$closed" | ||
| remote="" | ||
| files="" | ||
| if git fetch --depth 1 origin "refs/heads/$BRANCH" 2>/dev/null; then | ||
| remote=$(git rev-parse FETCH_HEAD) | ||
| # The files the branch changes from the base, then how many of its commits someone else | ||
| # wrote or committed: an amended commit keeps its author but not its committer. | ||
| compare=$(gh api "repos/$GITHUB_REPOSITORY/compare/$BASE...$remote" --jq '([.files[].filename] | join(" ")), | ||
| ([.commits[] | select([.commit.author.email, .commit.committer.email] | ||
| | any(. != "41898282+github-actions[bot]@users.noreply.github.com"))] | length)') | ||
| files=$(sed -n 1p <<< "$compare") | ||
| others=$(sed -n 2p <<< "$compare") | ||
| if [[ "$others" != 0 ]]; then | ||
| echo "::error::$BRANCH has commits this workflow didn't make; leaving it alone." | ||
| exit 1 | ||
| fi | ||
| fi | ||
| # A branch whose whole change from the base is this README keeps its commit and its checks. | ||
| # Anything else is rebuilt, and the lease keeps a push made meanwhile. | ||
| if [[ -n "$remote" && "$files" == README.md ]] && git diff --quiet FETCH_HEAD -- README.md; then | ||
| echo "$BRANCH already has this list." | ||
| else | ||
| git add README.md | ||
| git -c user.name='github-actions[bot]' \ | ||
| -c user.email='41898282+github-actions[bot]@users.noreply.github.com' commit -m "$TITLE" | ||
| git push --force-with-lease="refs/heads/$BRANCH:$remote" \ | ||
| "https://x-access-token:$GH_TOKEN@github.com/$GITHUB_REPOSITORY.git" "HEAD:refs/heads/$BRANCH" | ||
| fi | ||
| if (( ours == 0 )); then | ||
| gh pr create --repo "$GITHUB_REPOSITORY" --base "$BASE" --head "$BRANCH" --title "$TITLE" --body-file - <<'EOF' | ||
| <!-- readme-contributors-workflow --> | ||
| ## Problem | ||
|
|
||
| GitHub lists contributors that the avatars in the README don't show yet, or no longer lists some it shows. | ||
|
|
||
| ## Changes | ||
|
|
||
| Rewrites the avatars between the `contributors` markers in README.md from GitHub's contributors list: | ||
| most contributions first, without bots, with second accounts counted under their first | ||
| (`.github/scripts/readme-contributors.mjs`). | ||
|
|
||
| ## Testing | ||
|
|
||
| Opened by the README contributors workflow (`.github/workflows/readme-contributors.yml`), whose logic | ||
| `node --test .github/scripts/*.test.mjs` covers. | ||
|
|
||
| No agent | ||
| EOF | ||
| fi | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.