Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions .github/scripts/readme-contributors.mjs
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;
}
81 changes: 81 additions & 0 deletions .github/scripts/readme-contributors.test.mjs
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);
});
200 changes: 200 additions & 0 deletions .github/workflows/readme-contributors.yml
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')
Comment thread
M4n0x marked this conversation as resolved.
Resolved
if [[ "$others" != 0 ]]; then
echo "::warning::#$number has commits this workflow didn't make; leaving it open."
continue
fi
Comment thread
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 \
Comment thread
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
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ Reviews are requested automatically from the people listed in [CODEOWNERS](.gith

Open community pull requests are followed up on daily by [Community PR follow-up](.github/workflows/community-pr-followup.yml). A pull request waiting on its author (failing checks, merge conflicts, requested changes or unresolved threads) gets `waiting-for-author` and a check-in after 7 days, and closes automatically 7 days later without an update (drafts get 14 days before a check-in and 14 days after). A ready pull request waiting on maintainers (review, `visual-ok` or first-time CI approval) never closes automatically; after 4 days it gets `needs-review` and reminds maintainers. Add `keep-open` to pause follow-ups on a pull request.

The contributors' avatars in the [README](README.md#contributing) come from GitHub's contributors list. Every Monday, [README contributors](.github/workflows/readme-contributors.yml) compares them and, when the list changed, opens a pull request from the `readme-contributors` branch. To count a second account under someone's first, or leave out an automation account, edit `ALIASES` or `EXCLUDED` in [readme-contributors.mjs](.github/scripts/readme-contributors.mjs) rather than the README.

[DECISIONS.md](DECISIONS.md) lists the lasting decisions about releases, reviews and code. A pull request that sets a new rule or policy adds an entry there.

## Commits and releases
Expand Down
Loading
Loading