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
2 changes: 2 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ npx patchlane verify-auth

This dispatches `sync-upstream.yml` with `no_push=true`, finds the newly created run, and waits for it to finish. A successful run validates the uploaded App key, installation, requested permissions, API access, authenticated checkout, and Patchlane rebuild without changing a branch. Use `--timeout <seconds>` and `--poll-interval <seconds>` to override the 60-second discovery timeout and 2-second polling interval. The equivalent environment variables are `PATCHLANE_AUTH_TIMEOUT_SECONDS` and `PATCHLANE_AUTH_POLL_INTERVAL_SECONDS`.

GitHub operations resolve the fork from the configured `origin` push URL, independently of `gh repo set-default`. Use `--origin-remote-name <name>` for a differently named push remote or `--repository <owner/repo>` to override repository detection.

### Validate or publish a sync

```bash
Expand Down
24 changes: 12 additions & 12 deletions src/bootstrap.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { loadPatchlaneConfig } from './config.js';
import { runDoctor } from './doctor.js';
import { resolveForkRepository } from './github-repository.js';
import { runIntegrationSync } from './integration-sync.js';
import { runPromoteSync } from './promote-sync.js';
import { git, run } from './subprocess.js';
Expand All @@ -11,6 +12,8 @@ const CI_PROGRESS_INTERVAL_MS = 60_000;
type BootstrapOptions = {
publish?: boolean;
wait?: boolean;
repository?: string;
originRemoteName?: string;
ciTimeoutSeconds?: number;
ciPollIntervalSeconds?: number;
cwd?: string;
Expand Down Expand Up @@ -136,7 +139,7 @@ export async function bootstrapPatchlane(options: BootstrapOptions = {}) {
const report = runDoctor({ cwd });
if (!report.ok) throw new Error('Fix the Patchlane doctor errors before bootstrapping.');

const originRemoteName = process.env.ORIGIN_REMOTE_NAME ?? 'origin';
const originRemoteName = options.originRemoteName ?? process.env.ORIGIN_REMOTE_NAME ?? 'origin';
const syncOptions = {
upstreamOwner: config.upstreamOwner,
upstreamRepo: config.upstreamRepo,
Expand All @@ -157,7 +160,12 @@ export async function bootstrapPatchlane(options: BootstrapOptions = {}) {
return { status: 'validated' as const };
}

process.stdout.write(`Publishing ${config.syncBranch} for CI.\n`);
const repository = resolveForkRepository({
cwd,
repository: options.repository,
originRemoteName,
});
process.stdout.write(`Publishing ${config.syncBranch} to ${repository} for CI.\n`);
runIntegrationSync(syncOptions);
const syncSha = publishedSyncSha(originRemoteName, config.syncBranch, cwd);
if (!options.wait) {
Expand All @@ -179,15 +187,7 @@ export async function bootstrapPatchlane(options: BootstrapOptions = {}) {
DEFAULT_CI_POLL_INTERVAL_SECONDS,
'CI poll interval',
);
const repositoryResult = run('gh', ['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner'], cwd);
if (repositoryResult.status !== 0 || !repositoryResult.stdout) {
throw new Error(
`Could not determine the GitHub repository: ${repositoryResult.stderr || repositoryResult.stdout || 'unknown error'}`,
);
}
const repository = repositoryResult.stdout;

process.stdout.write(`Waiting for '${ciWorkflow}' to test ${syncSha}.\n`);
process.stdout.write(`Waiting for '${ciWorkflow}' to test ${syncSha} in ${repository}.\n`);
const runId = await waitForCiRun(
repository,
ciWorkflow,
Expand All @@ -197,7 +197,7 @@ export async function bootstrapPatchlane(options: BootstrapOptions = {}) {
timeoutSeconds,
pollIntervalSeconds,
);
const watch = run('gh', ['run', 'watch', runId, '--exit-status'], cwd);
const watch = run('gh', ['run', 'watch', runId, '--repo', repository, '--exit-status'], cwd);
if (watch.stdout) process.stdout.write(`${watch.stdout}\n`);
if (watch.stderr) process.stderr.write(`${watch.stderr}\n`);
if (watch.status !== 0) throw new Error(`CI run ${runId} did not succeed; refusing to promote.`);
Expand Down
18 changes: 16 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ cli.command('init', 'Create Patchlane config and workflow files')
cli.command('bootstrap', 'Validate and publish the first generated sync branch')
.option('--publish', 'Publish the generated sync branch after validation')
.option('--wait', 'Publish, wait for CI, and perform the initial promotion')
.option('--repository <owner/repo>', 'Fork GitHub repository; inferred from the origin push target')
.option('--origin-remote-name <name>', 'Name of the origin remote', {
default: env('ORIGIN_REMOTE_NAME', 'origin'),
})
.option('--ci-timeout <seconds>', 'Maximum time to wait for the CI run to appear', {
default: env('PATCHLANE_CI_TIMEOUT_SECONDS'),
})
Expand All @@ -86,6 +90,8 @@ cli.command('bootstrap', 'Validate and publish the first generated sync branch')
void bootstrapPatchlane({
publish: args.publish === true,
wait: args.wait === true,
repository: args.repository,
originRemoteName: args.originRemoteName,
ciTimeoutSeconds: args.ciTimeout === undefined ? undefined : Number(args.ciTimeout),
ciPollIntervalSeconds: args.ciPollInterval === undefined ? undefined : Number(args.ciPollInterval),
}).catch((error: unknown) => {
Expand All @@ -102,6 +108,10 @@ cli.command('doctor', 'Check Patchlane configuration without changing repository
});

cli.command('verify-auth', 'Dispatch a no-push sync to verify GitHub App authentication')
.option('--repository <owner/repo>', 'Fork GitHub repository; inferred from the origin push target')
.option('--origin-remote-name <name>', 'Name of the origin remote', {
default: env('ORIGIN_REMOTE_NAME', 'origin'),
})
.option('--timeout <seconds>', 'Maximum time to wait for the workflow run to appear', {
default: env('PATCHLANE_AUTH_TIMEOUT_SECONDS'),
})
Expand All @@ -110,6 +120,8 @@ cli.command('verify-auth', 'Dispatch a no-push sync to verify GitHub App authent
})
.action((args) => {
void verifyGitHubAuth({
repository: args.repository,
originRemoteName: args.originRemoteName,
timeoutSeconds: args.timeout === undefined ? undefined : Number(args.timeout),
pollIntervalSeconds: args.pollInterval === undefined ? undefined : Number(args.pollInterval),
}).catch((error: unknown) => {
Expand Down Expand Up @@ -212,8 +224,9 @@ cli.command('sync', 'Rebuild integration branch from upstream and patches')
cli.command('notify', 'Create, update, or close an automation failure issue')
.option('--event <event>', 'Notification event: sync-failed, ci-failed, or promotion-failed')
.option('--recovered', 'Close the open notification after recovery')
.option('--repository <owner/repo>', 'GitHub repository; defaults to the current fork', {
default: env('GITHUB_REPOSITORY'),
.option('--repository <owner/repo>', 'Fork GitHub repository; inferred from the origin push target')
.option('--origin-remote-name <name>', 'Name of the origin remote', {
default: env('ORIGIN_REMOTE_NAME', 'origin'),
})
.option('--status <status>', 'Failure status', { default: env('PATCHLANE_STATUS') })
.option('--run-url <url>', 'Workflow run URL', {
Expand Down Expand Up @@ -259,6 +272,7 @@ cli.command('notify', 'Create, update, or close an automation failure issue')
event: args.event as NotificationEvent,
recovered: args.recovered === true,
repository: args.repository,
originRemoteName: args.originRemoteName,
status: args.status,
runUrl: args.runUrl,
upstreamSource: args.upstreamSource,
Expand Down
49 changes: 49 additions & 0 deletions src/github-repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { run } from './subprocess.js';

type ForkRepositoryOptions = {
cwd: string;
repository?: string;
originRemoteName?: string;
};

function repositoryName(value: string | undefined) {
const normalized = value?.trim().replace(/\.git$/, '');
return normalized && /^[^\s/]+\/[^\s/]+$/.test(normalized) ? normalized : undefined;
}

export function githubRepositoryFromRemote(remoteUrl: string | undefined) {
const normalized = remoteUrl?.trim();
if (!normalized) return undefined;

try {
const url = new URL(normalized);
if (!['github.com', 'www.github.com'].includes(url.hostname.toLowerCase())) return undefined;
return repositoryName(url.pathname.replace(/^\//, ''));
} catch {
const scpMatch = normalized.match(/^(?:[^@\s]+@)?github\.com:([^/\s:]+)\/([^/\s]+?)(?:\.git)?\/?$/i);
return scpMatch ? `${scpMatch[1]}/${scpMatch[2]}` : undefined;
}
}

export function resolveForkRepository(options: ForkRepositoryOptions) {
if (options.repository !== undefined) {
const explicit = repositoryName(options.repository);
if (!explicit) throw new Error(`Invalid GitHub repository '${options.repository}'; expected owner/repo.`);
return explicit;
}

const originRemoteName = options.originRemoteName ?? 'origin';
const remote = run('git', ['remote', 'get-url', '--push', originRemoteName], options.cwd);
if (remote.status === 0) {
const repository = githubRepositoryFromRemote(remote.stdout);
if (repository) return repository;
}

const environmentRepository = repositoryName(process.env.GITHUB_REPOSITORY);
if (environmentRepository) return environmentRepository;

throw new Error(
`Could not determine the fork GitHub repository from the '${originRemoteName}' push target. ` +
`Configure that remote to point at GitHub or pass --repository=owner/repo.`,
);
}
30 changes: 14 additions & 16 deletions src/notify.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { spawnSync } from 'node:child_process';
import type { NotificationEvent, PatchlaneConfig } from './config.js';
import { resolveForkRepository } from './github-repository.js';

type GithubIssue = {
number: number;
Expand All @@ -22,6 +23,8 @@ export type NotificationOptions = {
repository?: string;
status?: string;
runUrl?: string;
cwd?: string;
originRemoteName?: string;
upstreamSource?: string;
upstreamSha?: string;
syncSha?: string;
Expand Down Expand Up @@ -50,17 +53,6 @@ function runGithub(args: string[]) {
return result.stdout;
}

function parseRepositoryFromOrigin() {
const result = spawnSync('git', ['remote', 'get-url', 'origin'], { encoding: 'utf8' });
if (result.status !== 0) return undefined;
const match = result.stdout.trim().match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/);
return match ? `${match[1]}/${match[2]}` : undefined;
}

function currentRepository(explicit?: string) {
return explicit || process.env.GITHUB_REPOSITORY || parseRepositoryFromOrigin();
}

function eventName(event: NotificationEvent) {
return {
'sync-failed': 'Sync failed',
Expand Down Expand Up @@ -146,11 +138,17 @@ export function runNotification(
if (!provider.events.includes(options.event)) return { status: 'disabled' };
if (options.recovered && !provider.closeOnRecovery) return { status: 'closed-without-notification' };

const repository = currentRepository(options.repository);
if (!repository) {
const error = 'Could not determine the current GitHub repository.';
warn(error);
return { status: 'failed', error };
let repository: string;
try {
repository = resolveForkRepository({
cwd: options.cwd ?? process.cwd(),
repository: options.repository,
originRemoteName: options.originRemoteName ?? process.env.ORIGIN_REMOTE_NAME,
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
warn(message);
return { status: 'failed', error: message };
}

const github = dependencies.github ?? runGithub;
Expand Down
16 changes: 9 additions & 7 deletions src/verify-auth.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { randomUUID } from 'node:crypto';
import { loadPatchlaneConfig } from './config.js';
import { resolveForkRepository } from './github-repository.js';
import { run } from './subprocess.js';

const DEFAULT_TIMEOUT_SECONDS = 60;
const DEFAULT_POLL_INTERVAL_SECONDS = 2;

type VerifyAuthOptions = {
cwd?: string;
repository?: string;
originRemoteName?: string;
timeoutSeconds?: number;
pollIntervalSeconds?: number;
verificationId?: string;
Expand Down Expand Up @@ -83,13 +86,11 @@ export async function verifyGitHubAuth(options: VerifyAuthOptions = {}) {
const config = loadPatchlaneConfig(cwd);
if (!config) throw new Error('Missing .patchlane.yml. Run `npx patchlane init` first.');

const repositoryResult = run('gh', ['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner'], cwd);
if (repositoryResult.status !== 0 || !repositoryResult.stdout) {
throw new Error(
`Could not determine the GitHub repository: ${repositoryResult.stderr || repositoryResult.stdout || 'unknown error'}`,
);
}
const repository = repositoryResult.stdout;
const repository = resolveForkRepository({
cwd,
repository: options.repository,
originRemoteName: options.originRemoteName ?? process.env.ORIGIN_REMOTE_NAME,
});
const timeoutSeconds = positiveSeconds(options.timeoutSeconds, DEFAULT_TIMEOUT_SECONDS, 'Auth timeout');
const pollIntervalSeconds = positiveSeconds(
options.pollIntervalSeconds,
Expand All @@ -98,6 +99,7 @@ export async function verifyGitHubAuth(options: VerifyAuthOptions = {}) {
);
const verificationId = options.verificationId ?? randomUUID();
const expectedTitle = `Verify Patchlane authentication (${verificationId})`;
process.stdout.write(`Dispatching the Patchlane authentication check in ${repository}.\n`);
const dispatch = run(
'gh',
[
Expand Down
Loading