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
1 change: 1 addition & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
version: 2
updates:
# dependabot-bundle.yml commits rebuilt dist/index.js after npm PR checks.
- package-ecosystem: npm
directory: "/"
schedule:
Expand Down
92 changes: 92 additions & 0 deletions .github/scripts/dependabot-bundle.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
const fs = require('node:fs');
const path = require('node:path');

async function validate(github, context) {
const run = context.payload.workflow_run;
if (
run.event !== 'pull_request' ||
run.head_repository.full_name !== `${context.repo.owner}/${context.repo.repo}`
)
return;
if (!run.head_branch.startsWith('dependabot/npm_and_yarn/')) return;
if (run.pull_requests.length !== 1) return;
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number: run.pull_requests[0].number,
});
if (
pr.state !== 'open' ||
pr.user.login !== 'dependabot[bot]' ||
pr.head.repo.full_name !== run.head_repository.full_name ||
pr.head.ref !== run.head_branch ||
pr.head.sha !== run.head_sha ||
pr.base.ref !== 'master'
)
return;
const files = await github.paginate(github.rest.pulls.listFiles, {
...context.repo,
pull_number: pr.number,
per_page: 100,
});
// Never write to PRs that change source, workflows, or automation scripts.
const allowed = new Set(['package.json', 'package-lock.json', 'dist/index.js']);
if (
!files.length ||
files.some((file) => !allowed.has(file.filename) || file.status !== 'modified')
)
return;
const artifacts = await github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
...context.repo,
run_id: run.id,
per_page: 100,
});
if (
!artifacts.some(
(artifact) => artifact.name === `dependabot-bundle-${run.head_sha}` && !artifact.expired,
)
)
return;
return pr;
}

async function update(github, context) {
// Recheck the live head after downloading; the commit API also rejects races.
const pr = await validate(github, context);
if (!pr) return;
const bundlePath = path.join(process.env.RUNNER_TEMP, 'dependabot-bundle', 'index.js');
if (!fs.lstatSync(bundlePath).isFile()) throw new Error('Expected a regular bundle file');
const contents = fs.readFileSync(bundlePath).toString('base64');
const { data: current } = await github.rest.repos.getContent({
...context.repo,
path: 'dist/index.js',
ref: pr.head.sha,
});
if (current.content && current.content.replace(/\s/g, '') === contents) return;
await github.graphql(
`mutation($input: CreateCommitOnBranchInput!) {
createCommitOnBranch(input: $input) { commit { oid } }
}`,
{
input: {
branch: {
repositoryNameWithOwner: `${context.repo.owner}/${context.repo.repo}`,
branchName: pr.head.ref,
},
expectedHeadOid: pr.head.sha,
message: {
headline: 'chore(deps): rebuild action bundle',
body: 'Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>',
},
fileChanges: { additions: [{ path: 'dist/index.js', contents }] },
},
},
);
// GITHUB_TOKEN commits do not trigger pull_request CI automatically.
await github.rest.actions.createWorkflowDispatch({
...context.repo,
workflow_id: 'main.yml',
ref: pr.head.ref,
});
}

module.exports = { validate, update };
170 changes: 170 additions & 0 deletions .github/scripts/dependabot-bundle.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { validate, update } = require('./dependabot-bundle.cjs');

function fixture() {
const run = {
id: 1,
event: 'pull_request',
head_repository: { full_name: 'softprops/turnstyle' },
head_branch: 'dependabot/npm_and_yarn/npm-group',
head_sha: 'abc',
pull_requests: [{ number: 161 }],
};
const pr = {
number: 161,
state: 'open',
user: { login: 'dependabot[bot]' },
head: { repo: { full_name: 'softprops/turnstyle' }, ref: run.head_branch, sha: run.head_sha },
base: { ref: 'master' },
};
const files = [{ filename: 'package-lock.json', status: 'modified' }];
const artifacts = [{ name: 'dependabot-bundle-abc', expired: false }];
const calls = [];
const github = {
rest: {
pulls: { get: async () => ({ data: pr }), listFiles: 'files' },
repos: {
getContent: async () => ({ data: { content: Buffer.from('old').toString('base64') } }),
},
actions: {
listWorkflowRunArtifacts: 'artifacts',
createWorkflowDispatch: async (input) => calls.push(['dispatch', input]),
},
},
paginate: async (endpoint) => (endpoint === 'files' ? files : artifacts),
graphql: async (query, input) => calls.push(['commit', input.input]),
};
return {
run,
pr,
files,
artifacts,
github,
calls,
context: { repo: { owner: 'softprops', repo: 'turnstyle' }, payload: { workflow_run: run } },
};
}

test('accepts an open same-repository Dependabot dependency update', async () => {
const f = fixture();
assert.equal(await validate(f.github, f.context), f.pr);
});

for (const [name, change] of Object.entries({
'non-PR run': (f) => {
f.run.event = 'push';
},
'fork run': (f) => {
f.run.head_repository.full_name = 'other/turnstyle';
},
'non-npm branch': (f) => {
f.run.head_branch = 'feature';
},
'missing PR': (f) => {
f.run.pull_requests = [];
},
'closed PR': (f) => {
f.pr.state = 'closed';
},
'human author': (f) => {
f.pr.user.login = 'human';
},
'fork PR': (f) => {
f.pr.head.repo.full_name = 'other/turnstyle';
},
'changed branch': (f) => {
f.pr.head.ref = 'master';
},
'stale head': (f) => {
f.pr.head.sha = 'new';
},
'different base': (f) => {
f.pr.base.ref = 'release';
},
'source changes': (f) => {
f.files.push({ filename: 'src/main.ts', status: 'modified' });
},
'workflow changes': (f) => {
f.files.push({ filename: '.github/workflows/main.yml', status: 'modified' });
},
'renamed manifest': (f) => {
f.files[0].status = 'renamed';
},
'empty diff': (f) => {
f.files.length = 0;
},
'missing artifact': (f) => {
f.artifacts.length = 0;
},
'wrong artifact SHA': (f) => {
f.artifacts[0].name = 'dependabot-bundle-old';
},
'expired artifact': (f) => {
f.artifacts[0].expired = true;
},
})) {
test(`rejects ${name}`, async () => {
const f = fixture();
change(f);
assert.equal(await validate(f.github, f.context), undefined);
await update(f.github, f.context);
assert.deepEqual(f.calls, []);
});
}

async function withBundle(contents, fn) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bundle-test-'));
const previous = process.env.RUNNER_TEMP;
process.env.RUNNER_TEMP = dir;
fs.mkdirSync(path.join(dir, 'dependabot-bundle'));
fs.writeFileSync(path.join(dir, 'dependabot-bundle/index.js'), contents);
try {
await fn();
} finally {
if (previous === undefined) delete process.env.RUNNER_TEMP;
else process.env.RUNNER_TEMP = previous;
fs.rmSync(dir, { recursive: true, force: true });
}
}

test('unchanged bundle does not create a commit or dispatch', async () => {
await withBundle('old', async () => {
const f = fixture();
await update(f.github, f.context);
assert.deepEqual(f.calls, []);
});
});

test('commits only the bundle with expected head and sign-off, then dispatches CI', async () => {
await withBundle('new', async () => {
const f = fixture();
await update(f.github, f.context);
assert.equal(f.calls[0][0], 'commit');
const commit = f.calls[0][1];
assert.equal(commit.expectedHeadOid, 'abc');
assert.equal(commit.branch.branchName, f.pr.head.ref);
assert.match(commit.message.body, /^Signed-off-by:/);
assert.deepEqual(commit.fileChanges, {
additions: [{ path: 'dist/index.js', contents: Buffer.from('new').toString('base64') }],
});
assert.deepEqual(f.calls[1], [
'dispatch',
{ owner: 'softprops', repo: 'turnstyle', workflow_id: 'main.yml', ref: f.pr.head.ref },
]);
});
});

test('a concurrent head update fails without dispatching CI', async () => {
await withBundle('new', async () => {
const f = fixture();
f.github.graphql = async () => {
throw new Error('expectedHeadOid mismatch');
};
await assert.rejects(update(f.github, f.context), /expectedHeadOid/);
assert.deepEqual(f.calls, []);
});
});
60 changes: 60 additions & 0 deletions .github/workflows/dependabot-bundle.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
name: Update Dependabot bundle

on:
# PR code runs only in read-only CI; this job reads the bundle as data and
# validates the live PR and expected head before committing one fixed path.
workflow_run: # zizmor: ignore[dangerous-triggers]
workflows: [main]
types: [completed]
branches: ["dependabot/npm_and_yarn/**"]

permissions: {}

concurrency:
group: dependabot-bundle-${{ github.event.workflow_run.head_branch }}
cancel-in-progress: false

jobs:
update-bundle:
if: >-
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.head_repository.full_name == github.repository
runs-on: ubuntu-24.04
permissions:
actions: write
contents: write
pull-requests: read
steps:
# Only trusted default-branch code runs in this job. The artifact is data.
- name: Checkout automation
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
with:
ref: ${{ github.sha }}
persist-credentials: false

- name: Validate pull request and artifact
id: validate
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
with:
script: |
const { validate } = require('./.github/scripts/dependabot-bundle.cjs');
const pr = await validate(github, context);
core.setOutput('eligible', Boolean(pr));

- name: Download bundle
if: steps.validate.outputs.eligible == 'true'
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RUN_ID: ${{ github.event.workflow_run.id }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
gh run download "$RUN_ID" --name "dependabot-bundle-$HEAD_SHA" --dir "$RUNNER_TEMP/dependabot-bundle"

- name: Commit bundle and run CI
if: steps.validate.outputs.eligible == 'true'
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
with:
script: |
const { update } = require('./.github/scripts/dependabot-bundle.cjs');
await update(github, context);
24 changes: 22 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ jobs:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
with:
# Build the exact head that the bundle updater will commit onto.
ref: ${{ github.event.pull_request.user.login == 'dependabot[bot]' && github.event.pull_request.head.sha || github.sha }}
persist-credentials: false

- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v6
with:
Expand All @@ -34,13 +38,29 @@ jobs:
run: npm run typecheck
- name: Build
run: npm run build
- name: Check bundled action
run: git diff --exit-code -- dist/index.js
- name: Test
run: npm run test
- name: Test bundle automation
run: node --test .github/scripts/dependabot-bundle.test.cjs
- name: Format
run: npm run fmtcheck

- name: Upload Dependabot bundle
if: >-
github.event_name == 'pull_request' &&
github.event.pull_request.user.login == 'dependabot[bot]' &&
github.event.pull_request.head.repo.full_name == github.repository &&
startsWith(github.head_ref, 'dependabot/npm_and_yarn/')
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: dependabot-bundle-${{ github.event.pull_request.head.sha }}
path: dist/index.js
if-no-files-found: error
retention-days: 1
overwrite: true
- name: Check bundled action
run: git diff --exit-code -- dist/index.js

integration:
if: github.event_name == 'push'
runs-on: ubuntu-24.04
Expand Down