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
24 changes: 24 additions & 0 deletions docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <name>` | Project name (alias for the positional argument) |
| `--branch <name>` | New branch to deploy from |
| `--executor <type>` | 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`
Expand Down
2 changes: 1 addition & 1 deletion packages/void/src/cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
},
{
Expand Down
37 changes: 37 additions & 0 deletions packages/void/src/cli/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,43 @@ export class PlatformClient {
return res.json();
}

async getGithubConnection(projectId: string): Promise<GithubConnection> {
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<GithubConnection> {
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,
Expand Down
69 changes: 68 additions & 1 deletion packages/void/src/cli/github-args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ export const githubSubcommands: Array<SubcommandDef> = [
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' },
];

Expand All @@ -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<string>): GithubArgs {
Expand Down Expand Up @@ -120,5 +131,61 @@ export function parseGithubArgs(args: Array<string>): GithubArgs {
return { subcommand, projectName, installationId, repo, branch, executor };
}

throw new Error('github: Usage: void github <install|installations|connect|link>.');
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.');
}
// 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.');
}
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 <install|installations|connect|update|link>.');
}
196 changes: 196 additions & 0 deletions packages/void/src/cli/github-cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
PlatformApiError,
PlatformClient,
parsePlatformErrorBody,
type GithubConnection,
type GithubInstallation,
} from './client.ts';
import { collectGitDeployMetadata } from './git-metadata.ts';
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -463,3 +481,181 @@ 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<GithubArgs, { subcommand: 'update' }>,
): Promise<void> {
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 <name> and/or --executor <container|github_actions>.',
);
process.exit(1);
}

// -------------------------------------------------------------------------
// 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 <name>, 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 {
// 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;
}

// -------------------------------------------------------------------------
// 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}.`,
);
}
Loading