From f6dc843e7159f4c8612763af1acdecdc973269a2 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 1 Jul 2026 15:09:28 +0800 Subject: [PATCH 1/2] feat(cli): add `void github update` to change an existing connection's branch/executor There was no CLI way to change an already-connected GitHub deploy connection: `void github connect` returns 409 when a project is already connected, so flipping the build executor (container <-> github_actions) or moving the deploy branch required a raw authenticated PATCH /projects/:id/github. This is the real blocker for a monorepo whose Void app lives in a subdirectory and must use the github_actions executor. `void github update [project] [--branch ] [--executor ]`: - resolves the project the same way `connect` does (positional / --project / VOID_PROJECT / linked .void/project.json) - fetches the current connection (GET); a missing connection maps to a friendly "run `void github connect` first" message - TTY: shows current branch + executor and prompts for new values, defaulting each to the current setting - non-TTY: requires at least one of --branch / --executor, else fails closed - sends only the changed fields to PATCH /projects/:id/github, and skips the API entirely when nothing changed Adds PlatformClient.getGithubConnection + updateGithubConnection, help/hint/docs entries, and unit tests (args parsing, client wire format, error mapping, and command behavior for all paths). Co-Authored-By: Claude Opus 4.8 --- docs/reference/cli.md | 24 ++ packages/void/src/cli/cli.ts | 2 +- packages/void/src/cli/client.ts | 37 +++ packages/void/src/cli/github-args.ts | 65 ++++- packages/void/src/cli/github-cmd.ts | 189 ++++++++++++++ packages/void/src/cli/help.ts | 26 ++ packages/void/test/unit/github-args.test.ts | 132 +++++++++- packages/void/test/unit/github-client.test.ts | 109 ++++++++ packages/void/test/unit/github-cmd.test.ts | 24 ++ .../void/test/unit/github-update-cmd.test.ts | 237 ++++++++++++++++++ 10 files changed, 841 insertions(+), 4 deletions(-) create mode 100644 packages/void/test/unit/github-update-cmd.test.ts diff --git a/docs/reference/cli.md b/docs/reference/cli.md index a9246e4e5..34c5dbeab 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -627,6 +627,30 @@ void github connect my-app \ **Project resolution** follows the same order as deploy: positional / `--project`, `VOID_PROJECT`, linked project (`.void/project.json`). +### `void github update` + +``` +void github update [project] [options] +``` + +Update an existing connection's deploy **branch** and/or **build executor**. Use this to change settings on a project that is already connected — for example, flipping the executor from `container` to `github_actions` for a monorepo whose Void app lives in a subdirectory, or moving the deploy branch. The project must already be connected (run `void github connect` first); the repository and installation are not changed. + +**Options** + +| Flag | Description | +| ------------------- | --------------------------------------------------- | +| `--project ` | Project name (alias for the positional argument) | +| `--branch ` | New branch to deploy from | +| `--executor ` | New build executor: `container` or `github_actions` | + +Interactively (TTY), `void github update` shows the current branch and executor and prompts for new values, defaulting each to the current setting. When stdin is not a TTY, it never prompts: pass at least one of `--branch` / `--executor`, or it fails closed. If nothing actually changes, the command reports "no changes" and does not call the API. + +``` +void github update my-app --executor github_actions +``` + +**Project resolution** follows the same order as deploy: positional / `--project`, `VOID_PROJECT`, linked project (`.void/project.json`). + ## Custom Domains ### `void domain add` diff --git a/packages/void/src/cli/cli.ts b/packages/void/src/cli/cli.ts index 6c702b1ce..637d0465b 100644 --- a/packages/void/src/cli/cli.ts +++ b/packages/void/src/cli/cli.ts @@ -201,7 +201,7 @@ if (helpPath) { }, { name: 'github', - hint: 'install | installations | connect | link', + hint: 'install | installations | connect | update | link', description: 'Connect a GitHub repository for automatic deploys', }, { diff --git a/packages/void/src/cli/client.ts b/packages/void/src/cli/client.ts index 5600e7945..1d5b53fd9 100644 --- a/packages/void/src/cli/client.ts +++ b/packages/void/src/cli/client.ts @@ -930,6 +930,43 @@ export class PlatformClient { return res.json(); } + async getGithubConnection(projectId: string): Promise { + const res = await fetch(`${this.baseUrl}/projects/${projectId}/github`, { + headers: { + ...this.authHeaders, + }, + }); + + if (!res.ok) { + await throwPlatformApiError('Failed to get GitHub connection', res); + } + + return res.json(); + } + + async updateGithubConnection( + projectId: string, + body: { + branch?: string; + buildExecutor?: 'container' | 'github_actions'; + }, + ): Promise { + const res = await fetch(`${this.baseUrl}/projects/${projectId}/github`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + ...this.authHeaders, + }, + body: JSON.stringify(body), + }); + + if (!res.ok) { + await throwPlatformApiError('Failed to update GitHub connection', res); + } + + return res.json(); + } + async getGithubLinkUrl(redirect: string, codeChallenge: string): Promise<{ url: string }> { const params = new URLSearchParams({ redirect, diff --git a/packages/void/src/cli/github-args.ts b/packages/void/src/cli/github-args.ts index 90729f39f..9f9042c60 100644 --- a/packages/void/src/cli/github-args.ts +++ b/packages/void/src/cli/github-args.ts @@ -8,6 +8,11 @@ export const githubSubcommands: Array = [ arg: '[project]', description: 'Connect a repository to a project for auto-deploy', }, + { + name: 'update', + arg: '[project]', + description: "Update an existing connection's branch or build executor", + }, { name: 'link', description: 'Link your GitHub account to Void' }, ]; @@ -22,6 +27,12 @@ export type GithubArgs = repo?: string; branch?: string; executor?: 'container' | 'github_actions'; + } + | { + subcommand: 'update'; + projectName: string; + branch?: string; + executor?: 'container' | 'github_actions'; }; export function parseGithubArgs(args: Array): GithubArgs { @@ -120,5 +131,57 @@ export function parseGithubArgs(args: Array): GithubArgs { return { subcommand, projectName, installationId, repo, branch, executor }; } - throw new Error('github: Usage: void github .'); + if (subcommand === 'update') { + let projectName = ''; + let branch: string | undefined; + let executor: 'container' | 'github_actions' | undefined; + + for (let i = 0; i < rest.length; i++) { + const arg = rest[i]; + if (arg === '--branch') { + if (i + 1 >= rest.length) { + throw new Error('github: --branch requires a value.'); + } + const value = rest[++i]!; + if (value.trim() === '') { + throw new Error('github: --branch requires a value.'); + } + branch = value; + } else if (arg === '--project') { + if (i + 1 >= rest.length) { + throw new Error('github: --project requires a value.'); + } + const value = rest[++i]!; + if (value.trim() === '') { + throw new Error('github: --project requires a value.'); + } + if (projectName) { + throw new Error(`github: Unexpected argument '${value}'.`); + } + projectName = value; + } else if (arg === '--executor') { + if (i + 1 >= rest.length) { + throw new Error('github: --executor requires a value.'); + } + const value = rest[++i]!; + if (value.trim() === '') { + throw new Error('github: --executor requires a value.'); + } + if (value !== 'container' && value !== 'github_actions') { + throw new Error('github: invalid --executor (expected container|github_actions).'); + } + executor = value; + } else if (arg.startsWith('-')) { + throw new Error(`github: Unexpected argument '${arg}'.`); + } else if (projectName) { + throw new Error(`github: Unexpected argument '${arg}'.`); + } else { + projectName = arg; + } + } + + return { subcommand, projectName, branch, executor }; + } + + throw new Error('github: Usage: void github .'); } diff --git a/packages/void/src/cli/github-cmd.ts b/packages/void/src/cli/github-cmd.ts index 53b66f713..34fed4dbc 100644 --- a/packages/void/src/cli/github-cmd.ts +++ b/packages/void/src/cli/github-cmd.ts @@ -11,6 +11,7 @@ import { PlatformApiError, PlatformClient, parsePlatformErrorBody, + type GithubConnection, type GithubInstallation, } from './client.ts'; import { collectGitDeployMetadata } from './git-metadata.ts'; @@ -49,6 +50,21 @@ export function describeConnectError(status: number, errorCode: string | undefin return null; } +/** + * Like {@link describeConnectError}, but for `void github update`. The update + * flow starts from an EXISTING connection, so a 404 "connection not found" + * (the project has no GitHub connection, or it was disconnected between the + * read and the write) is the common case and gets a "connect first" message. + * Everything else defers to the shared connect mapping. + */ +export function describeUpdateError(status: number, errorCode: string | undefined): string | null { + const code = errorCode ?? ''; + if (status === 404 && code.includes('connection not found')) { + return 'This project is not connected to a GitHub repository. Run `void github connect` first.'; + } + return describeConnectError(status, code); +} + /** * Extract `owner/repo` from a `https://github.com/owner/repo(.git)?` URL. * Returns null for non-GitHub URLs or null input. @@ -114,6 +130,8 @@ export async function runGithubCommand(root: string, args: GithubArgs): Promise< return runInstallations(client); case 'connect': return runConnect(root, client, args); + case 'update': + return runGithubUpdate(root, client, args); case 'link': return runGithubLink(root, client); } @@ -463,3 +481,174 @@ async function runConnect( log.success(`Connected ${repoFullName} (${branch}) → project. Push to ${branch} to deploy.`); } + +// --------------------------------------------------------------------------- +// update +// --------------------------------------------------------------------------- + +export async function runGithubUpdate( + root: string, + client: PlatformClient, + args: Extract, +): Promise { + const isTTY = process.stdin.isTTY === true; + + // ------------------------------------------------------------------------- + // 1. Resolve project (identical resolution order to `connect`). + // ------------------------------------------------------------------------- + let projectId: string; + + const requestedSlug = getRequestedProjectSlug({ projectSlug: args.projectName || undefined }); + + if (requestedSlug) { + const projects = await client.listProjects(); + const resolved = resolveProjectBySlug(projects, requestedSlug); + if (!resolved) { + log.error(`update: No project found with slug '${requestedSlug}'.`); + process.exit(1); + } + projectId = resolved.projectId; + } else { + const linked = readProjectConfig(root); + if (linked) { + projectId = linked.projectId; + } else if (!isTTY) { + log.error( + 'update: No project specified. Pass a project name or --project , set VOID_PROJECT, or link one with `void project link`.', + ); + process.exit(1); + } else { + const projects = await client.listProjects(); + if (projects.length === 0) { + log.error('No projects found. Create one first with `void deploy`.'); + process.exit(1); + } + const picked = await select({ + message: 'Select a project:', + options: projects.map((p) => ({ value: p.id, label: p.slug })), + }); + if (isCancel(picked)) { + cancel('Cancelled.'); + process.exit(0); + } + projectId = picked as string; + } + } + + // ------------------------------------------------------------------------- + // 2. Fetch the current connection. A missing connection (404) means the + // project was never connected — mirror the API's 404 semantics and point + // the user at `connect` instead of a raw error. + // ------------------------------------------------------------------------- + let current: GithubConnection; + try { + current = await client.getGithubConnection(projectId); + } catch (err) { + if (err instanceof PlatformApiError) { + const body = parsePlatformErrorBody(err.body); + const code = body?.error ?? body?.message ?? ''; + const message = describeUpdateError(err.status, code); + if (message !== null) { + log.error(`update: ${message}`); + process.exit(1); + } + } + throw err; + } + + // ------------------------------------------------------------------------- + // 3. Resolve the new branch + executor. TTY defaults to the current value; + // non-TTY requires at least one flag (nothing to prompt for). + // ------------------------------------------------------------------------- + let branch: string; + let executor: 'container' | 'github_actions'; + + if (isTTY) { + if (args.branch !== undefined) { + branch = args.branch; + } else { + const input = await text({ + message: 'Branch to deploy from:', + placeholder: current.branch, + initialValue: current.branch, + }); + if (isCancel(input)) { + cancel('Cancelled.'); + process.exit(0); + } + branch = (input as string).trim() || current.branch; + } + + if (args.executor !== undefined) { + executor = args.executor; + } else { + const picked = await select({ + message: 'Build executor:', + options: [ + { value: 'container', label: 'container' }, + { value: 'github_actions', label: 'github_actions' }, + ], + initialValue: current.build_executor, + }); + if (isCancel(picked)) { + cancel('Cancelled.'); + process.exit(0); + } + executor = picked as 'container' | 'github_actions'; + } + } else { + if (args.branch === undefined && args.executor === undefined) { + log.error( + 'update: Nothing to update. Pass --branch and/or --executor .', + ); + process.exit(1); + } + branch = args.branch ?? current.branch; + executor = args.executor ?? current.build_executor; + } + + // ------------------------------------------------------------------------- + // 4. Build a patch carrying ONLY the fields that actually changed. + // ------------------------------------------------------------------------- + const patch: { branch?: string; buildExecutor?: 'container' | 'github_actions' } = {}; + if (branch !== current.branch) { + patch.branch = branch; + } + if (executor !== current.build_executor) { + patch.buildExecutor = executor; + } + + // ------------------------------------------------------------------------- + // 5. No-op guard — never hit the API when nothing changed. + // ------------------------------------------------------------------------- + if (patch.branch === undefined && patch.buildExecutor === undefined) { + log.info( + `No changes. ${current.repo_full_name} already deploys from ${current.branch} via ${current.build_executor}.`, + ); + return; + } + + // ------------------------------------------------------------------------- + // 6. Update. + // ------------------------------------------------------------------------- + let updated: GithubConnection; + try { + updated = await client.updateGithubConnection(projectId, patch); + } catch (err) { + if (err instanceof PlatformApiError) { + const body = parsePlatformErrorBody(err.body); + const code = body?.error ?? body?.message ?? ''; + const message = describeUpdateError(err.status, code); + if (message !== null) { + log.error(`update: ${message}`); + process.exit(1); + } + throw err; + } + throw err; + } + + log.success( + `Updated ${updated.repo_full_name} → branch ${updated.branch}, executor ${updated.build_executor}.`, + ); +} diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index 79487c6c6..fa5490141 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -200,6 +200,10 @@ const HELP_TREE: HelpTree = { command: 'connect [project]', description: 'Connect a repository to a project for auto-deploy', }, + { + command: 'update [project]', + description: "Update an existing connection's branch or build executor", + }, { command: 'link', description: 'Link your GitHub account to Void' }, ], children: { @@ -239,6 +243,28 @@ const HELP_TREE: HelpTree = { }, ], }, + update: { + summary: "Update an existing connection's branch or build executor.", + usage: ['void github update [project] [options]'], + options: [ + { command: '--project ', description: 'Project name (alias for positional)' }, + { command: '--branch ', description: 'New branch to deploy from' }, + { + command: '--executor ', + description: 'New build executor: container | github_actions', + }, + ], + examples: [ + { + command: 'void github update my-app --executor github_actions', + description: 'Switch an existing connection to the GitHub Actions executor', + }, + { + command: 'void github update my-app --branch release', + description: 'Change the deploy branch', + }, + ], + }, }, }, db: { diff --git a/packages/void/test/unit/github-args.test.ts b/packages/void/test/unit/github-args.test.ts index 15522124e..08796e7b5 100644 --- a/packages/void/test/unit/github-args.test.ts +++ b/packages/void/test/unit/github-args.test.ts @@ -285,6 +285,134 @@ describe('parseGithubArgs', () => { }); }); + describe('update', () => { + it('parses update with no args', () => { + expect(parseGithubArgs(['update'])).toEqual({ + subcommand: 'update', + projectName: '', + branch: undefined, + executor: undefined, + }); + }); + + it('parses update with a project name', () => { + expect(parseGithubArgs(['update', 'my-project'])).toEqual({ + subcommand: 'update', + projectName: 'my-project', + branch: undefined, + executor: undefined, + }); + }); + + it('parses --project flag', () => { + expect(parseGithubArgs(['update', '--project', 'my-project'])).toEqual({ + subcommand: 'update', + projectName: 'my-project', + branch: undefined, + executor: undefined, + }); + }); + + it('--project flag is an alias for the positional', () => { + const positional = parseGithubArgs(['update', 'my-project']); + const flag = parseGithubArgs(['update', '--project', 'my-project']); + expect(flag).toEqual(positional); + }); + + it('parses --branch flag', () => { + expect(parseGithubArgs(['update', '--branch', 'release'])).toEqual({ + subcommand: 'update', + projectName: '', + branch: 'release', + executor: undefined, + }); + }); + + it('parses --executor container', () => { + expect(parseGithubArgs(['update', '--executor', 'container'])).toEqual({ + subcommand: 'update', + projectName: '', + branch: undefined, + executor: 'container', + }); + }); + + it('parses --executor github_actions', () => { + expect(parseGithubArgs(['update', '--executor', 'github_actions'])).toEqual({ + subcommand: 'update', + projectName: '', + branch: undefined, + executor: 'github_actions', + }); + }); + + it('parses project name with both flags together', () => { + expect( + parseGithubArgs([ + 'update', + 'my-project', + '--branch', + 'main', + '--executor', + 'github_actions', + ]), + ).toEqual({ + subcommand: 'update', + projectName: 'my-project', + branch: 'main', + executor: 'github_actions', + }); + }); + + it('rejects --branch with no value', () => { + expect(() => parseGithubArgs(['update', '--branch'])).toThrow( + 'github: --branch requires a value.', + ); + }); + + it('rejects --branch with empty value', () => { + expect(() => parseGithubArgs(['update', '--branch', ''])).toThrow( + 'github: --branch requires a value.', + ); + }); + + it('rejects --project with no value', () => { + expect(() => parseGithubArgs(['update', '--project'])).toThrow( + 'github: --project requires a value.', + ); + }); + + it('rejects --project when positional already set', () => { + expect(() => parseGithubArgs(['update', 'my-project', '--project', 'other'])).toThrow( + "github: Unexpected argument 'other'.", + ); + }); + + it('rejects --executor with no value', () => { + expect(() => parseGithubArgs(['update', '--executor'])).toThrow( + 'github: --executor requires a value.', + ); + }); + + it('rejects invalid --executor value', () => { + expect(() => parseGithubArgs(['update', '--executor', 'docker'])).toThrow( + 'github: invalid --executor (expected container|github_actions).', + ); + }); + + it('rejects unknown flag', () => { + expect(() => parseGithubArgs(['update', '--unknown'])).toThrow( + "github: Unexpected argument '--unknown'.", + ); + }); + + it('rejects extra positional after project name', () => { + expect(() => parseGithubArgs(['update', 'my-project', 'extra'])).toThrow( + "github: Unexpected argument 'extra'.", + ); + }); + }); + describe('link', () => { it('parses link with no args', () => { expect(parseGithubArgs(['link'])).toEqual({ subcommand: 'link' }); @@ -306,13 +434,13 @@ describe('parseGithubArgs', () => { describe('unknown subcommand', () => { it('throws on empty args', () => { expect(() => parseGithubArgs([])).toThrow( - 'github: Usage: void github .', + 'github: Usage: void github .', ); }); it('throws on unknown subcommand', () => { expect(() => parseGithubArgs(['unknown'])).toThrow( - 'github: Usage: void github .', + 'github: Usage: void github .', ); }); }); diff --git a/packages/void/test/unit/github-client.test.ts b/packages/void/test/unit/github-client.test.ts index de25cc6e4..1b22d64a5 100644 --- a/packages/void/test/unit/github-client.test.ts +++ b/packages/void/test/unit/github-client.test.ts @@ -178,6 +178,115 @@ describe('PlatformClient.connectGithub', () => { }); }); +describe('PlatformClient.getGithubConnection', () => { + it('GETs the right URL, sends auth headers, returns the parsed connection', async () => { + const connection: GithubConnection = { + id: 'conn_1', + project_id: projectId, + installation_id: '123456', + repo_full_name: 'octocat/hello-world', + repository_id: '9876', + branch: 'main', + build_executor: 'container', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', + }; + + fetchMock.mockResolvedValueOnce(jsonResponse(connection)); + + const client = makeClient(); + const result = await client.getGithubConnection(projectId); + + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe(`${apiUrl}/projects/${projectId}/github`); + expect(init.method).toBeUndefined(); + const headers = init.headers as Record; + expect(headers.Authorization).toBe(`Bearer ${token}`); + expect(result).toEqual(connection); + }); + + it('throws PlatformApiError on non-2xx (e.g. 404 connection not found)', async () => { + fetchMock.mockResolvedValueOnce(jsonResponse({ error: 'connection not found' }, 404)); + const client = makeClient(); + await expect(client.getGithubConnection(projectId)).rejects.toMatchObject({ + name: 'PlatformApiError', + status: 404, + code: 'connection not found', + }); + }); +}); + +describe('PlatformClient.updateGithubConnection', () => { + it('PATCHes the right URL with Content-Type and exact JSON body, returns parsed connection', async () => { + const connection: GithubConnection = { + id: 'conn_1', + project_id: projectId, + installation_id: '123456', + repo_full_name: 'octocat/hello-world', + repository_id: '9876', + branch: 'release', + build_executor: 'github_actions', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-02T00:00:00Z', + }; + + fetchMock.mockResolvedValueOnce(jsonResponse(connection)); + + const client = makeClient(); + const result = await client.updateGithubConnection(projectId, { + branch: 'release', + buildExecutor: 'github_actions', + }); + + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe(`${apiUrl}/projects/${projectId}/github`); + expect(init.method).toBe('PATCH'); + const headers = init.headers as Record; + expect(headers['Content-Type']).toBe('application/json'); + expect(headers.Authorization).toBe(`Bearer ${token}`); + expect(JSON.parse(init.body as string)).toEqual({ + branch: 'release', + buildExecutor: 'github_actions', + }); + expect(result).toEqual(connection); + }); + + it('sends only the fields provided (executor only)', async () => { + const connection: GithubConnection = { + id: 'conn_2', + project_id: projectId, + installation_id: '123456', + repo_full_name: 'octocat/hello-world', + repository_id: null, + branch: 'main', + build_executor: 'github_actions', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-02T00:00:00Z', + }; + + fetchMock.mockResolvedValueOnce(jsonResponse(connection)); + + const client = makeClient(); + await client.updateGithubConnection(projectId, { buildExecutor: 'github_actions' }); + + const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(JSON.parse(init.body as string)).toEqual({ buildExecutor: 'github_actions' }); + }); + + it('throws PlatformApiError on non-2xx', async () => { + fetchMock.mockResolvedValueOnce(new Response('not found', { status: 404 })); + const client = makeClient(); + await expect( + client.updateGithubConnection(projectId, { branch: 'main' }), + ).rejects.toMatchObject({ + name: 'PlatformApiError', + status: 404, + }); + }); +}); + describe('PlatformClient.getGithubLinkUrl', () => { it('GETs link-url with redirect + S256 challenge query, auth headers, returns { url }', async () => { fetchMock.mockResolvedValueOnce( diff --git a/packages/void/test/unit/github-cmd.test.ts b/packages/void/test/unit/github-cmd.test.ts index 126283181..c8e6ed5de 100644 --- a/packages/void/test/unit/github-cmd.test.ts +++ b/packages/void/test/unit/github-cmd.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vite-plus/test'; import type { GithubInstallation } from '../../src/cli/client.ts'; import { describeConnectError, + describeUpdateError, formatInstallations, parseGithubRepoFullName, } from '../../src/cli/github-cmd.ts'; @@ -48,6 +49,29 @@ describe('describeConnectError', () => { }); }); +describe('describeUpdateError', () => { + it('returns a connect-first message for 404 / "connection not found"', () => { + const msg = describeUpdateError(404, 'connection not found'); + expect(msg).toBe( + 'This project is not connected to a GitHub repository. Run `void github connect` first.', + ); + }); + + it('falls back to the connect mapping for other 404 codes', () => { + expect(describeUpdateError(404, 'project not found')).toBe( + 'Project or installation not found.', + ); + }); + + it('falls back to the connect mapping for 403', () => { + expect(describeUpdateError(403, 'forbidden')).toBe("You don't have access to this project."); + }); + + it('returns null for an unrecognised status / code', () => { + expect(describeUpdateError(500, undefined)).toBeNull(); + }); +}); + describe('parseGithubRepoFullName', () => { it('extracts owner/repo from a plain https GitHub URL', () => { expect(parseGithubRepoFullName('https://github.com/acme/my-app')).toBe('acme/my-app'); diff --git a/packages/void/test/unit/github-update-cmd.test.ts b/packages/void/test/unit/github-update-cmd.test.ts new file mode 100644 index 000000000..7696f4611 --- /dev/null +++ b/packages/void/test/unit/github-update-cmd.test.ts @@ -0,0 +1,237 @@ +import { log } from '@clack/prompts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; +import { + PlatformApiError, + type GithubConnection, + type PlatformClient, + type ProjectResponse, +} from '../../src/cli/client.ts'; +import { runGithubUpdate } from '../../src/cli/github-cmd.ts'; + +const projectId = 'proj_test'; +const slug = 'my-app'; + +function makeProject(): ProjectResponse { + return { + id: projectId, + user_id: 'user_1', + slug, + type: 'void', + created_at: '2024-01-01T00:00:00Z', + custom_domain: null, + }; +} + +function makeConnection(overrides: Partial = {}): GithubConnection { + return { + id: 'conn_1', + project_id: projectId, + installation_id: '123456', + repo_full_name: 'octocat/hello-world', + repository_id: '9876', + branch: 'main', + build_executor: 'container', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', + ...overrides, + }; +} + +type FakeClient = Pick< + PlatformClient, + 'listProjects' | 'getGithubConnection' | 'updateGithubConnection' +>; + +function makeClient(over: Partial = {}): { + client: PlatformClient; + listProjects: ReturnType; + getGithubConnection: ReturnType; + updateGithubConnection: ReturnType; +} { + const listProjects = vi.fn(async () => [makeProject()]); + const getGithubConnection = vi.fn(async () => makeConnection()); + const updateGithubConnection = vi.fn(async () => makeConnection()); + const client = { + listProjects, + getGithubConnection, + updateGithubConnection, + ...over, + } as unknown as PlatformClient; + return { + client, + listProjects: (over.listProjects as ReturnType) ?? listProjects, + getGithubConnection: + (over.getGithubConnection as ReturnType) ?? getGithubConnection, + updateGithubConnection: + (over.updateGithubConnection as ReturnType) ?? updateGithubConnection, + }; +} + +let exitSpy: ReturnType; +let successSpy: ReturnType; +let infoSpy: ReturnType; +let errorSpy: ReturnType; +const originalIsTTY = process.stdin.isTTY; + +beforeEach(() => { + // Force the non-interactive (non-TTY) path so tests never hit clack prompts. + (process.stdin as { isTTY?: boolean }).isTTY = false; + // process.exit -> throw so we can assert the error-path exit without killing + // the test runner. + exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code})`); + }) as never); + successSpy = vi.spyOn(log, 'success').mockImplementation(() => {}); + infoSpy = vi.spyOn(log, 'info').mockImplementation(() => {}); + errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {}); +}); + +afterEach(() => { + (process.stdin as { isTTY?: boolean }).isTTY = originalIsTTY; + exitSpy.mockRestore(); + successSpy.mockRestore(); + infoSpy.mockRestore(); + errorSpy.mockRestore(); +}); + +describe('runGithubUpdate (non-TTY)', () => { + it('updates the executor only, sending just buildExecutor', async () => { + const { client, updateGithubConnection } = makeClient({ + getGithubConnection: vi.fn(async () => makeConnection({ build_executor: 'container' })), + updateGithubConnection: vi.fn(async () => + makeConnection({ build_executor: 'github_actions' }), + ), + }); + + await runGithubUpdate('/project', client, { + subcommand: 'update', + projectName: slug, + executor: 'github_actions', + }); + + expect(updateGithubConnection).toHaveBeenCalledTimes(1); + expect(updateGithubConnection).toHaveBeenCalledWith(projectId, { + buildExecutor: 'github_actions', + }); + expect(successSpy).toHaveBeenCalledTimes(1); + expect(exitSpy).not.toHaveBeenCalled(); + }); + + it('updates the branch only, sending just branch', async () => { + const { client, updateGithubConnection } = makeClient({ + updateGithubConnection: vi.fn(async () => makeConnection({ branch: 'release' })), + }); + + await runGithubUpdate('/project', client, { + subcommand: 'update', + projectName: slug, + branch: 'release', + }); + + expect(updateGithubConnection).toHaveBeenCalledWith(projectId, { branch: 'release' }); + expect(successSpy).toHaveBeenCalledTimes(1); + expect(exitSpy).not.toHaveBeenCalled(); + }); + + it('updates both branch and executor', async () => { + const { client, updateGithubConnection } = makeClient({ + updateGithubConnection: vi.fn(async () => + makeConnection({ branch: 'release', build_executor: 'github_actions' }), + ), + }); + + await runGithubUpdate('/project', client, { + subcommand: 'update', + projectName: slug, + branch: 'release', + executor: 'github_actions', + }); + + expect(updateGithubConnection).toHaveBeenCalledWith(projectId, { + branch: 'release', + buildExecutor: 'github_actions', + }); + expect(successSpy).toHaveBeenCalledTimes(1); + }); + + it('exits(1) with a connect-first message when the project is not connected', async () => { + const notConnected = new PlatformApiError( + 'Failed to get GitHub connection', + 404, + JSON.stringify({ error: 'connection not found' }), + ); + const { client, updateGithubConnection } = makeClient({ + getGithubConnection: vi.fn(async () => { + throw notConnected; + }), + }); + + await expect( + runGithubUpdate('/project', client, { + subcommand: 'update', + projectName: slug, + executor: 'github_actions', + }), + ).rejects.toThrow('process.exit(1)'); + + expect(exitSpy).toHaveBeenCalledWith(1); + expect(errorSpy).toHaveBeenCalledWith( + 'update: This project is not connected to a GitHub repository. Run `void github connect` first.', + ); + expect(updateGithubConnection).not.toHaveBeenCalled(); + }); + + it('exits(1) when no flags are passed (nothing to update)', async () => { + const { client, updateGithubConnection } = makeClient(); + + await expect( + runGithubUpdate('/project', client, { + subcommand: 'update', + projectName: slug, + }), + ).rejects.toThrow('process.exit(1)'); + + expect(exitSpy).toHaveBeenCalledWith(1); + expect(errorSpy).toHaveBeenCalledWith( + 'update: Nothing to update. Pass --branch and/or --executor .', + ); + expect(updateGithubConnection).not.toHaveBeenCalled(); + }); + + it('does not call the API when the requested values equal the current ones', async () => { + const { client, updateGithubConnection } = makeClient({ + getGithubConnection: vi.fn(async () => + makeConnection({ branch: 'main', build_executor: 'container' }), + ), + }); + + await runGithubUpdate('/project', client, { + subcommand: 'update', + projectName: slug, + branch: 'main', + executor: 'container', + }); + + expect(updateGithubConnection).not.toHaveBeenCalled(); + expect(infoSpy).toHaveBeenCalledTimes(1); + expect(successSpy).not.toHaveBeenCalled(); + expect(exitSpy).not.toHaveBeenCalled(); + }); + + it('exits(1) when the project slug cannot be resolved', async () => { + const { client, getGithubConnection } = makeClient({ + listProjects: vi.fn(async () => []), + }); + + await expect( + runGithubUpdate('/project', client, { + subcommand: 'update', + projectName: 'nope', + executor: 'github_actions', + }), + ).rejects.toThrow('process.exit(1)'); + + expect(exitSpy).toHaveBeenCalledWith(1); + expect(getGithubConnection).not.toHaveBeenCalled(); + }); +}); From 1cc1cc71ed7c3d615254f657d21f8aed11d35cf8 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 1 Jul 2026 15:29:39 +0800 Subject: [PATCH 2/2] fix(cli): trim branch + move non-TTY guard before API reads in github update (review) Trim the --branch value in the `update` arg parser so a padded value like 'main ' can no longer be persisted (it would never match refs/heads/main at OIDC exchange time and would cancel in-flight builds for the old branch). The no-op check and PATCH now both use the canonical branch name. `connect` is left unchanged. Move the non-TTY missing-flags guard to the top of runGithubUpdate, before project resolution and getGithubConnection, so `void github update ` with no flags reports the usage error regardless of API state (a disconnected project no longer surfaces the 404 "connect first" message in its place). Co-Authored-By: Claude Opus 4.8 --- packages/void/src/cli/github-args.ts | 6 ++- packages/void/src/cli/github-cmd.ts | 19 +++++++--- packages/void/test/unit/github-args.test.ts | 15 ++++++++ .../void/test/unit/github-update-cmd.test.ts | 37 ++++++++++++++++++- 4 files changed, 68 insertions(+), 9 deletions(-) diff --git a/packages/void/src/cli/github-args.ts b/packages/void/src/cli/github-args.ts index 9f9042c60..5a621a71f 100644 --- a/packages/void/src/cli/github-args.ts +++ b/packages/void/src/cli/github-args.ts @@ -146,7 +146,11 @@ export function parseGithubArgs(args: Array): GithubArgs { if (value.trim() === '') { throw new Error('github: --branch requires a value.'); } - branch = value; + // Store the trimmed branch so the no-op check and the PATCH both use the + // canonical name — a padded value like 'main ' would never match + // refs/heads/main at OIDC exchange time and would cancel in-flight builds + // for the old branch. + branch = value.trim(); } else if (arg === '--project') { if (i + 1 >= rest.length) { throw new Error('github: --project requires a value.'); diff --git a/packages/void/src/cli/github-cmd.ts b/packages/void/src/cli/github-cmd.ts index 34fed4dbc..df0902f52 100644 --- a/packages/void/src/cli/github-cmd.ts +++ b/packages/void/src/cli/github-cmd.ts @@ -493,6 +493,17 @@ export async function runGithubUpdate( ): Promise { const isTTY = process.stdin.isTTY === true; + // Non-TTY needs at least one flag to act on — there is nothing to prompt for. + // Guard BEFORE any project resolution or connection read so this usage error + // never depends on API state (e.g. a disconnected project must not surface the + // "connect first" 404 message in place of the missing-flags error). + if (!isTTY && args.branch === undefined && args.executor === undefined) { + log.error( + 'update: Nothing to update. Pass --branch and/or --executor .', + ); + process.exit(1); + } + // ------------------------------------------------------------------------- // 1. Resolve project (identical resolution order to `connect`). // ------------------------------------------------------------------------- @@ -597,12 +608,8 @@ export async function runGithubUpdate( executor = picked as 'container' | 'github_actions'; } } else { - if (args.branch === undefined && args.executor === undefined) { - log.error( - 'update: Nothing to update. Pass --branch and/or --executor .', - ); - process.exit(1); - } + // The missing-flags guard at the top of this function already guaranteed at + // least one of --branch / --executor is present in non-TTY mode. branch = args.branch ?? current.branch; executor = args.executor ?? current.build_executor; } diff --git a/packages/void/test/unit/github-args.test.ts b/packages/void/test/unit/github-args.test.ts index 08796e7b5..c5def5e52 100644 --- a/packages/void/test/unit/github-args.test.ts +++ b/packages/void/test/unit/github-args.test.ts @@ -328,6 +328,21 @@ describe('parseGithubArgs', () => { }); }); + it('trims a whitespace-padded --branch value', () => { + expect(parseGithubArgs(['update', '--branch', ' main '])).toEqual({ + subcommand: 'update', + projectName: '', + branch: 'main', + executor: undefined, + }); + }); + + it('rejects --branch with whitespace-only value', () => { + expect(() => parseGithubArgs(['update', '--branch', ' '])).toThrow( + 'github: --branch requires a value.', + ); + }); + it('parses --executor container', () => { expect(parseGithubArgs(['update', '--executor', 'container'])).toEqual({ subcommand: 'update', diff --git a/packages/void/test/unit/github-update-cmd.test.ts b/packages/void/test/unit/github-update-cmd.test.ts index 7696f4611..dc88c9246 100644 --- a/packages/void/test/unit/github-update-cmd.test.ts +++ b/packages/void/test/unit/github-update-cmd.test.ts @@ -181,8 +181,8 @@ describe('runGithubUpdate (non-TTY)', () => { expect(updateGithubConnection).not.toHaveBeenCalled(); }); - it('exits(1) when no flags are passed (nothing to update)', async () => { - const { client, updateGithubConnection } = makeClient(); + it('exits(1) when no flags are passed (nothing to update) before any API read', async () => { + const { client, listProjects, getGithubConnection, updateGithubConnection } = makeClient(); await expect( runGithubUpdate('/project', client, { @@ -195,6 +195,39 @@ describe('runGithubUpdate (non-TTY)', () => { expect(errorSpy).toHaveBeenCalledWith( 'update: Nothing to update. Pass --branch and/or --executor .', ); + // The missing-flags guard must run BEFORE project resolution / connection + // reads, so this usage error never depends on API state. + expect(listProjects).not.toHaveBeenCalled(); + expect(getGithubConnection).not.toHaveBeenCalled(); + expect(updateGithubConnection).not.toHaveBeenCalled(); + }); + + it('reports missing flags (not "connect first") for a disconnected project', async () => { + // If the guard ran AFTER getGithubConnection, this 404 would surface the + // "connect first" message instead of the missing-flags usage error. + const { client, listProjects, getGithubConnection, updateGithubConnection } = makeClient({ + getGithubConnection: vi.fn(async () => { + throw new PlatformApiError( + 'Failed to get GitHub connection', + 404, + JSON.stringify({ error: 'connection not found' }), + ); + }), + }); + + await expect( + runGithubUpdate('/project', client, { + subcommand: 'update', + projectName: slug, + }), + ).rejects.toThrow('process.exit(1)'); + + expect(exitSpy).toHaveBeenCalledWith(1); + expect(errorSpy).toHaveBeenCalledWith( + 'update: Nothing to update. Pass --branch and/or --executor .', + ); + expect(listProjects).not.toHaveBeenCalled(); + expect(getGithubConnection).not.toHaveBeenCalled(); expect(updateGithubConnection).not.toHaveBeenCalled(); });