diff --git a/.bumpy/fix-version-pr-ci-triggers.md b/.bumpy/fix-version-pr-ci-triggers.md index 24e99e4..40ac948 100644 --- a/.bumpy/fix-version-pr-ci-triggers.md +++ b/.bumpy/fix-version-pr-ci-triggers.md @@ -2,6 +2,8 @@ '@varlock/bumpy': patch --- -Fix version PR not triggering CI workflow runs +Support custom token for triggering CI on version PRs -After pushing the version branch, recreate the tip commit via the GitHub REST API so that pull_request workflows fire automatically. Commits pushed with GITHUB_TOKEN don't trigger workflows due to GitHub's anti-recursion guard, but API-created commits bypass this — no PATs, GitHub Apps, or user CI config changes needed. +- Add `BUMPY_GH_TOKEN` env var support — when set, bumpy pushes the version branch using the custom token, bypassing GitHub's anti-recursion guard so PR workflows fire automatically +- Add `bumpy ci setup` interactive command to help create a fine-grained PAT or GitHub App and store it as a repo secret +- When no custom token is set, log a warning with setup instructions diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index b639e84..897ec0a 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -25,4 +25,4 @@ jobs: - run: bun install - run: bunx @varlock/bumpy ci release env: - GH_TOKEN: ${{ github.token }} + BUMPY_GH_TOKEN: ${{ secrets.BUMPY_GH_TOKEN }} diff --git a/packages/bumpy/src/cli.ts b/packages/bumpy/src/cli.ts index fe19daa..421de66 100644 --- a/packages/bumpy/src/cli.ts +++ b/packages/bumpy/src/cli.ts @@ -114,8 +114,11 @@ async function main() { tag: ciFlags.tag as string | undefined, branch: ciFlags.branch as string | undefined, }); + } else if (subcommand === 'setup') { + const { ciSetupCommand } = await import('./commands/ci-setup.ts'); + await ciSetupCommand(rootDir); } else { - log.error(`Unknown ci subcommand: ${subcommand}. Use "ci check" or "ci release".`); + log.error(`Unknown ci subcommand: ${subcommand}. Use "ci check", "ci release", or "ci setup".`); process.exit(1); } break; @@ -189,6 +192,7 @@ function printHelp() { publish Publish versioned packages ci check PR check — report pending releases, comment on PR ci release Release — create version PR or auto-publish + ci setup Set up a token for triggering CI on version PRs migrate Migrate from .changeset/ to .bumpy/ ai setup Install AI skill for creating changesets diff --git a/packages/bumpy/src/commands/ci-setup.ts b/packages/bumpy/src/commands/ci-setup.ts new file mode 100644 index 0000000..bee77d2 --- /dev/null +++ b/packages/bumpy/src/commands/ci-setup.ts @@ -0,0 +1,289 @@ +import pc from 'picocolors'; +import { log } from '../utils/logger.ts'; +import { p, unwrap } from '../utils/clack.ts'; +import { tryRunArgs } from '../utils/shell.ts'; +import { detectPackageManager } from '../utils/package-manager.ts'; +import type { PackageManager } from '../types.ts'; + +const PAT_PERMISSIONS = [ + 'contents: read & write', + 'pull requests: read & write', + 'metadata: read (selected automatically)', +]; + +export async function ciSetupCommand(rootDir: string): Promise { + p.intro(pc.bgCyan(pc.black(' bumpy ci setup '))); + + // Detect repo and package manager context + const repo = detectRepo(rootDir); + if (!repo) { + log.error( + 'Could not detect a GitHub repository.\n' + + ' This command currently only supports GitHub-hosted repos.\n' + + ' Make sure you have a GitHub remote (git remote -v).', + ); + process.exit(1); + } + const pm = await detectPackageManager(rootDir); + + p.log.info(`Detected repository: ${pc.cyan(repo)}`); + p.log.info(''); + p.log.info( + 'To trigger CI checks on the version PR, bumpy needs a token\n' + + "that bypasses GitHub's default anti-recursion guard.\n" + + 'You can use a fine-grained PAT or a GitHub App installation token.', + ); + + const method = unwrap( + await p.select({ + message: 'How would you like to authenticate?', + options: [ + { + label: 'Fine-grained Personal Access Token (PAT)', + value: 'pat' as const, + hint: 'recommended — quick and simple', + }, + { + label: 'GitHub App installation token', + value: 'app' as const, + hint: 'advanced — not tied to a personal account', + }, + ], + }), + ); + + if (method === 'pat') { + await setupPat(rootDir, repo, pm); + } else { + await setupApp(rootDir, repo, pm); + } +} + +// ---- PAT flow ---- + +async function setupPat(rootDir: string, repo: string, pm: PackageManager): Promise { + const patUrl = 'https://github.com/settings/personal-access-tokens/new'; + + p.log.info(''); + p.note( + [ + `1. Open: ${pc.cyan(patUrl)}`, + '', + `2. Set a name, e.g. ${pc.dim('"bumpy-ci"')}`, + '', + `3. Under ${pc.bold('Resource owner')}, select the org or account that owns ${pc.cyan(repo)}`, + '', + `4. Set ${pc.bold('Expiration')} — choose a longer duration to avoid frequent rotation`, + ` (you'll need to regenerate and update the secret when it expires)`, + '', + `5. Under ${pc.bold('Repository access')}, select ${pc.bold('"Only select repositories"')}`, + ` and choose ${pc.cyan(repo)}`, + '', + `6. Under ${pc.bold('Permissions → Repository permissions')}, grant:`, + ...PAT_PERMISSIONS.map((perm) => ` • ${pc.bold(perm)}`), + '', + '7. Click "Generate token" and copy the value', + '', + pc.dim('Tip: enable branch protection rules on your main branch to prevent'), + pc.dim('direct pushes — the PAT will only be used to push the version branch.'), + ].join('\n'), + 'Create a fine-grained PAT', + ); + + // Try to open browser + const shouldOpen = unwrap(await p.confirm({ message: 'Open the token creation page in your browser?' })); + if (shouldOpen) { + openBrowser(patUrl); + } + + // Prompt for the token + const token = unwrap( + await p.text({ + message: 'Paste your token:', + placeholder: 'github_pat_...', + validate: (value) => { + if (!value?.trim()) return 'Token is required'; + if (!value?.startsWith('github_pat_')) return 'Expected a fine-grained PAT (starts with github_pat_)'; + }, + }), + ); + + await storeSecret(rootDir, repo, token, pm); +} + +// ---- GitHub App flow ---- + +async function setupApp(rootDir: string, repo: string, pm: PackageManager): Promise { + const owner = repo.split('/')[0]!; + const appUrl = `https://github.com/organizations/${owner}/settings/apps/new`; + const personalAppUrl = `https://github.com/settings/apps/new`; + + const isOrg = unwrap(await p.confirm({ message: `Is ${pc.cyan(owner)} a GitHub organization?`, initialValue: true })); + + const createUrl = isOrg ? appUrl : personalAppUrl; + + p.log.info(''); + p.note( + [ + 'If you already have a GitHub App, skip to step 2.', + '', + pc.bold('Step 1: Create a GitHub App'), + '', + `1. Open: ${pc.cyan(createUrl)}`, + `2. Set the name, e.g. ${pc.dim(`"${owner}-bumpy-ci"`)}`, + '3. Uncheck "Active" under Webhooks (not needed)', + '4. Under Permissions → Repository permissions, grant:', + ...PAT_PERMISSIONS.map((perm) => ` • ${pc.bold(perm)}`), + '5. Under "Where can this app be installed?" select "Only on this account"', + '6. Click "Create GitHub App"', + '7. Note the App ID shown on the settings page', + '8. Generate a private key and download the .pem file', + '', + pc.bold('Step 2: Install the App'), + '', + `Install the app on ${pc.cyan(repo)} from the app's "Install App" tab.`, + '', + pc.bold('Step 3: Add secrets'), + '', + "You'll need to add two repository secrets:", + ` • ${pc.bold('BUMPY_APP_ID')} — the App ID`, + ` • ${pc.bold('BUMPY_APP_PRIVATE_KEY')} — contents of the .pem file`, + ].join('\n'), + 'GitHub App setup', + ); + + const shouldOpen = unwrap(await p.confirm({ message: 'Open the app creation page in your browser?' })); + if (shouldOpen) { + openBrowser(createUrl); + } + + const hasSecrets = unwrap( + await p.confirm({ message: 'Have you added the BUMPY_APP_ID and BUMPY_APP_PRIVATE_KEY secrets?' }), + ); + + if (hasSecrets) { + printAppWorkflowSnippet(pm); + } else { + p.log.info('You can add them later. Once ready, update your release workflow:'); + printAppWorkflowSnippet(pm); + } + + p.outro(pc.green('GitHub App setup complete!')); +} + +// ---- Shared helpers ---- + +async function storeSecret(rootDir: string, repo: string, token: string, pm: PackageManager): Promise { + const hasGh = tryRunArgs(['gh', '--version']); + if (!hasGh) { + p.log.warn("`gh` CLI not found — you'll need to add the secret manually."); + p.note( + `Go to: https://github.com/${repo}/settings/secrets/actions/new\n` + + `Name: ${pc.bold('BUMPY_GH_TOKEN')}\nValue: (the token you just created)`, + 'Add repository secret manually', + ); + printPatWorkflowSnippet(pm); + p.outro(pc.green('Setup complete!')); + return; + } + + // Check if the secret already exists + const existingSecrets = tryRunArgs(['gh', 'secret', 'list', '--repo', repo], { cwd: rootDir }); + const isReplacing = existingSecrets?.includes('BUMPY_GH_TOKEN') ?? false; + + const spin = p.spinner(); + spin.start( + isReplacing ? 'Replacing BUMPY_GH_TOKEN repository secret...' : 'Storing BUMPY_GH_TOKEN as a repository secret...', + ); + try { + // gh secret set reads from stdin and overwrites if the secret already exists + tryRunArgs(['gh', 'secret', 'set', 'BUMPY_GH_TOKEN', '--repo', repo], { + cwd: rootDir, + input: token, + } as any); + spin.stop(isReplacing ? 'Secret replaced!' : 'Secret stored!'); + } catch { + spin.stop('Failed to store secret'); + p.log.warn('Could not store the secret automatically.'); + p.note( + `Go to: https://github.com/${repo}/settings/secrets/actions/new\n` + + `Name: ${pc.bold('BUMPY_GH_TOKEN')}\nValue: (the token you just created)`, + 'Add repository secret manually', + ); + } + + printPatWorkflowSnippet(pm); + p.outro(pc.green('Setup complete!')); +} + +function printPatWorkflowSnippet(pm: PackageManager): void { + const runCmd = pmxCommand(pm); + p.note( + [ + 'In your release workflow, pass the token to bumpy:', + '', + pc.dim('# .github/workflows/release.yaml'), + pc.dim(`- run: ${runCmd} ci release`), + pc.dim(' env:'), + pc.green(' BUMPY_GH_TOKEN: ${{ secrets.BUMPY_GH_TOKEN }}'), + ].join('\n'), + 'Update your workflow', + ); +} + +function printAppWorkflowSnippet(pm: PackageManager): void { + const runCmd = pmxCommand(pm); + p.note( + [ + 'In your release workflow, generate a token and pass it to bumpy:', + '', + pc.dim('# .github/workflows/release.yaml'), + pc.green('- uses: actions/create-github-app-token@v2'), + pc.green(' id: app-token'), + pc.green(' with:'), + pc.green(' app-id: ${{ secrets.BUMPY_APP_ID }}'), + pc.green(' private-key: ${{ secrets.BUMPY_APP_PRIVATE_KEY }}'), + '', + pc.dim(`- run: ${runCmd} ci release`), + pc.dim(' env:'), + pc.green(' BUMPY_GH_TOKEN: ${{ steps.app-token.outputs.token }}'), + ].join('\n'), + 'Update your workflow', + ); +} + +/** Package-manager-appropriate command for running bumpy in CI workflows */ +function pmxCommand(pm: PackageManager): string { + if (pm === 'bun') return 'bunx @varlock/bumpy'; + if (pm === 'pnpm') return 'pnpm exec bumpy'; + if (pm === 'yarn') return 'yarn bumpy'; + return 'npx @varlock/bumpy'; +} + +function detectRepo(rootDir: string): string | null { + // Check GitHub Actions env first + if (process.env.GITHUB_REPOSITORY) return process.env.GITHUB_REPOSITORY; + + // Try to extract from git remote + const remote = tryRunArgs(['git', 'remote', 'get-url', 'origin'], { cwd: rootDir }); + if (!remote) return null; + + // SSH: git@github.com:owner/repo.git + const sshMatch = remote.match(/github\.com[:/](.+?)(?:\.git)?$/); + if (sshMatch) return sshMatch[1]!; + + // HTTPS: https://github.com/owner/repo.git + const httpsMatch = remote.match(/github\.com\/(.+?)(?:\.git)?$/); + if (httpsMatch) return httpsMatch[1]!; + + return null; +} + +function openBrowser(url: string): void { + try { + const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'; + tryRunArgs([cmd, url]); + } catch { + // Silent fail — user can open manually + } +} diff --git a/packages/bumpy/src/commands/ci.ts b/packages/bumpy/src/commands/ci.ts index d3cf629..4fd28cf 100644 --- a/packages/bumpy/src/commands/ci.ts +++ b/packages/bumpy/src/commands/ci.ts @@ -164,47 +164,58 @@ async function autoPublish(rootDir: string, config: BumpyConfig, tag?: string): await publishCommand(rootDir, { tag }); } -// ---- GitHub API push helper ---- +// ---- Token-aware push ---- /** - * After a normal `git push`, recreate the tip commit via the GitHub REST API - * and force-update the branch ref to point at the API-created commit. + * Push a branch to origin, optionally using a custom GitHub token. * - * Why: commits pushed with GITHUB_TOKEN don't trigger workflow runs (GitHub's - * anti-recursion guard), but commits created through the REST API *do*. - * The API commit has the same tree and parent so the PR diff is identical. + * When `BUMPY_GH_TOKEN` is set, the remote URL is temporarily rewritten to + * include the token. Pushes made with a PAT or GitHub App token bypass + * GitHub's anti-recursion guard, allowing `pull_request` workflows to fire + * on the version PR — no extra CI configuration required. + * + * When only the default `GITHUB_TOKEN` is available the push still succeeds, + * but PR workflows won't be triggered automatically. */ -async function rerouteCommitViaApi( - rootDir: string, - branch: string, - commitMsg: string, - config: BumpyConfig, -): Promise { - const treeSha = runArgs(['git', 'rev-parse', 'HEAD^{tree}'], { cwd: rootDir }); - const parentSha = runArgs(['git', 'rev-parse', 'HEAD~1'], { cwd: rootDir }); - - const commitBody = JSON.stringify({ - message: commitMsg, - tree: treeSha, - parents: [parentSha], - author: { - name: config.gitUser.name, - email: config.gitUser.email, - }, - }); - - const apiCommitSha = await runArgsAsync( - ['gh', 'api', 'repos/{owner}/{repo}/git/commits', '--input', '-', '--jq', '.sha'], - { cwd: rootDir, input: commitBody }, - ); - - const refBody = JSON.stringify({ sha: apiCommitSha, force: true }); - await runArgsAsync(['gh', 'api', `repos/{owner}/{repo}/git/refs/heads/${branch}`, '-X', 'PATCH', '--input', '-'], { - cwd: rootDir, - input: refBody, - }); - - log.dim(' Re-pushed commit via GitHub API to trigger workflow runs'); +function pushWithToken(rootDir: string, branch: string): void { + const token = process.env.BUMPY_GH_TOKEN; + const repo = process.env.GITHUB_REPOSITORY; // e.g. "owner/repo" + const server = process.env.GITHUB_SERVER_URL || 'https://github.com'; + + if (token && repo) { + const authedUrl = `${server.replace('://', `://x-access-token:${token}@`)}/${repo}.git`; + const originalUrl = tryRunArgs(['git', 'remote', 'get-url', 'origin'], { cwd: rootDir }); + + // `actions/checkout` sets an http.extraheader with the default GITHUB_TOKEN. + // That header takes precedence over URL-embedded credentials, so we need to + // clear it temporarily for our custom token to be used. + const extraHeaderKey = `http.${server}/.extraheader`; + const savedHeader = tryRunArgs(['git', 'config', '--local', extraHeaderKey], { cwd: rootDir }); + try { + if (savedHeader) { + runArgs(['git', 'config', '--local', '--unset-all', extraHeaderKey], { cwd: rootDir }); + } + runArgs(['git', 'remote', 'set-url', 'origin', authedUrl], { cwd: rootDir }); + runArgs(['git', 'push', '-u', 'origin', branch, '--force'], { cwd: rootDir }); + } finally { + // Restore original URL and extraheader (avoid leaking the token in git config) + if (originalUrl) { + runArgs(['git', 'remote', 'set-url', 'origin', originalUrl], { cwd: rootDir }); + } + if (savedHeader) { + runArgs(['git', 'config', '--local', extraHeaderKey, savedHeader], { cwd: rootDir }); + } + } + log.dim(' Pushed with custom token — PR workflows will be triggered'); + } else { + runArgs(['git', 'push', '-u', 'origin', branch, '--force'], { cwd: rootDir }); + if (!token && repo) { + // Only warn on GitHub Actions — other CI providers don't have this limitation + log.warn( + 'BUMPY_GH_TOKEN is not set — PR checks will not trigger automatically.\n' + ' Run `bumpy ci setup` for help.', + ); + } + } } // ---- version-pr mode ---- @@ -253,11 +264,7 @@ async function createVersionPr( const commitMsg = ['Version packages', '', ...plan.releases.map((r) => `${r.name}@${r.newVersion}`)].join('\n'); runArgs(['git', 'commit', '-F', '-'], { cwd: rootDir, input: commitMsg }); - // Push via git first to upload objects, then recreate the commit via the - // GitHub API and force-update the ref. Commits created through the REST API - // *do* trigger workflow runs, whereas commits pushed with GITHUB_TOKEN do not. - runArgs(['git', 'push', '-u', 'origin', branch, '--force'], { cwd: rootDir }); - await rerouteCommitViaApi(rootDir, branch, commitMsg, config); + pushWithToken(rootDir, branch); // Create or update PR const prBody = formatVersionPrBody(plan, config.versionPr.preamble);