Skip to content
Open
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
143 changes: 143 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

### Node Patch ###
# Serverless Webpack directories
.webpack/

# Optional stylelint cache

# SvelteKit build / generate output
.svelte-kit

# End of https://www.toptal.com/developers/gitignore/api/node
49 changes: 48 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,49 @@
# all-contributors-image
Generates an image of the icons of all users in all-contributors list

Generates a contributors image (`contributors.png`) from the `.all-contributorsrc` file and opens a pull request with the updated image.

## What it does

Comment thread
skyash-dev marked this conversation as resolved.
- Fetches `.all-contributorsrc` from the repository
- Extracts contributor avatars
- Generates a grid image (`contributors.png`)
- Creates/updates a branch
- Commits the image
- Opens a pull request

## Usage

```yaml
name: Generate Contributors Image

on:
push:
paths:
- .all-contributorsrc

jobs:
generate:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
token: ${{ secrets.GITHUB_TOKEN }}
base-branch: my-branch
```

## Inputs

| name | type | required | description |
|---|---|---:|---|
| `token` | `string` | yes | token used for api calls |
| `base-branch` | `string` | no | branch used as the base/reference branch (default: main) |

PRs opened with the default `GITHUB_TOKEN` won't trigger other workflows (e.g. CI checks) on that PR. If you want checks to run on the generated PR, pass a personal access token instead (e.g. `secrets.ACCESS_TOKEN`) with the same permissions.

## Requirements

Repository must have:

- A valid `.all-contributorsrc` file
- The workflow must grant `contents: write` and `pull-requests: write` permissions (see usage example above)
- "Allow GitHub Actions to create and approve pull requests" must be enabled in repo settings.
24 changes: 24 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Generate Contributors PNG
description: Github action to generate an image of the icons of all users in all-contributors list
author: p5.js contributors & The Processing Foundation

inputs:
token:
description: GitHub token
base-branch:
description: Base/Reference branch
default: main

runs:
using: composite
steps:
- run: npm ci
shell: bash
working-directory: ${{ github.action_path }}

- run: node index.js
shell: bash
working-directory: ${{ github.action_path }}
env:
INPUT_TOKEN: ${{ inputs.token }}
Comment thread
skyash-dev marked this conversation as resolved.
INPUT_BASE-BRANCH: ${{ inputs.base-branch }}
55 changes: 55 additions & 0 deletions generateImage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { createCanvas, loadImage } from "canvas";

export async function generateImage(contributors) {
const AVATAR_SIZE = 50;
const GAP = 4;
const COLS = 40;
const ROWS = Math.ceil(contributors.length / COLS);

const width = COLS * AVATAR_SIZE + (COLS - 1) * GAP;
const height = ROWS * AVATAR_SIZE + (ROWS - 1) * GAP;

const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");

for (let i = 0; i < contributors.length; i++) {
const c = contributors[i];

const col = i % COLS;
const row = Math.floor(i / COLS);

const x = col * (AVATAR_SIZE + GAP);
const y = row * (AVATAR_SIZE + GAP);

const img = await loadAvatar(c.avatar_url);
Comment thread
skyash-dev marked this conversation as resolved.

ctx.save();
ctx.beginPath();
ctx.arc(
x + AVATAR_SIZE / 2,
y + AVATAR_SIZE / 2,
AVATAR_SIZE / 2,
0,
Math.PI * 2,
);
ctx.clip();

if (img) {
ctx.drawImage(img, x, y, AVATAR_SIZE, AVATAR_SIZE);
}
ctx.restore();
}
return canvas.toBuffer("image/png");
}

async function loadAvatar(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);

const buffer = Buffer.from(await res.arrayBuffer());
return await loadImage(buffer);
} catch (err) {
return null;
Comment thread
skyash-dev marked this conversation as resolved.
}
}
117 changes: 117 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import core from "@actions/core";
import github from "@actions/github";
import { generateImage } from "./generateImage.js";

async function run() {
const context = github.context;
const owner = context.repo.owner;
const repo = context.repo.repo;

const token = core.getInput("token", { required: true });
const baseBranch = core.getInput("base-branch") || "main";

const octokit = github.getOctokit(token);
const newBranch = "update-contributors-png";
const filePath = "contributors.png";

const res = await fetch(
`https://raw.githubusercontent.com/${owner}/${repo}/${baseBranch}/.all-contributorsrc`,
);
if (!res.ok) {
throw new Error("failed to fetch .all-contributorsrc");
}
const data = await res.json();
const contributors = data.contributors;

const contentBuffer = await generateImage(contributors);
let existingBuffer = null;

const existing = await fetch(
`https://raw.githubusercontent.com/${owner}/${repo}/${baseBranch}/contributors.png`,
);

if (existing.ok) {
const arrayBuffer = await existing.arrayBuffer();
existingBuffer = Buffer.from(arrayBuffer);
}

if (existingBuffer && contentBuffer.equals(existingBuffer)) return;

const content = contentBuffer.toString("base64");
// get base branch sha
const { data: baseRef } = await octokit.rest.git.getRef({
owner,
repo,
ref: `heads/${baseBranch}`,
});
const baseSha = baseRef.object.sha;

// create branch (or reuse if exists)
try {
await octokit.rest.git.createRef({
owner,
repo,
ref: `refs/heads/${newBranch}`,
sha: baseSha,
});
} catch (e) {
if (e.status !== 422) throw e;
// update branch, if already exists
await octokit.rest.git.updateRef({
owner,
repo,
ref: `heads/${newBranch}`,
sha: baseSha,
force: true,
});
}

// check if file already exists on branch
let existingSha;
try {
const { data } = await octokit.rest.repos.getContent({
owner,
repo,
path: filePath,
ref: newBranch,
});

if (!Array.isArray(data) && data.sha) {
existingSha = data.sha;
}
} catch (e) {
if (e.status !== 404) throw e; // anything other than "doesn't exist"
}

// create/update file and commit
await octokit.rest.repos.createOrUpdateFileContents({
Comment thread
skyash-dev marked this conversation as resolved.
owner,
repo,
path: filePath,
message: "Update contributors.png from .all-contributorsrc",
content,
branch: newBranch,
...(existingSha && { sha: existingSha }),
});

// create pull request if not exists
const { data: prs } = await octokit.rest.pulls.list({
owner,
repo,
head: `${owner}:${newBranch}`,
base: baseBranch,
state: "open",
});
if (prs.length === 0) {
await octokit.rest.pulls.create({
owner,
repo,
title: "chore: update contributors.png from .all-contributorsrc",
head: newBranch,
base: baseBranch,
body: "This PR updates the contributors.png to reflect changes in .all-contributorsrc",
});
}
}

run().catch((e) => core.setFailed(e.message));
Loading