From 93d625eda5f5eea3ff83014bfcd09a7d4ee603d4 Mon Sep 17 00:00:00 2001 From: Sebastian <5648131+polyrainbow@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:00:32 +0100 Subject: [PATCH] pr create opens a pull request from a fork into the repository -R selects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tangled.org opens a pull request from a fork the way it opens one within a repository: a ticket in the target repository's store, then submitPatch on the target's knot, with sourceRepo naming the fork's DID, the repository the knot fetches the head from (PullCompose.svelte and org.tangled.review.submitPatch in tangled.org/core). tang only ever named the target there. When --repo/-R or TANG_REPO selects the target and the clone's own remote is another repository, pr create now takes the clone as the fork: it checks the head branch on the clone's remote, fetches the target's base branch into FETCH_HEAD, and compares the head with that rather than with a local branch of the same name, for the behind check, the diff and the merge base. The patch names the fork as its sourceRepo, and the result shows fork:branch → target:branch. A target without a store is refused before anything is fetched or written, since the legacy pull record's fork form is no longer in tangled.org's lexicons. PullData gains sourceRepo, which pr create --json now gives. Seen red first: the four fork cases in pr.test.ts. Co-Authored-By: Claude Opus 5.5 --- src/commands/pr.ts | 135 ++++++++++++++++++++++++----- src/lib/pulls-api.ts | 2 + tests/commands/pr.test.ts | 175 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 292 insertions(+), 20 deletions(-) diff --git a/src/commands/pr.ts b/src/commands/pr.ts index f3bde02..b39c0b1 100644 --- a/src/commands/pr.ts +++ b/src/commands/pr.ts @@ -5,7 +5,11 @@ import { Command } from 'commander'; import { simpleGit } from 'simple-git'; import { listAllPulls, resolveEntityAddress, sortPulls } from '../lib/addressing.js'; import { createApiClient } from '../lib/api-client.js'; -import { getCurrentRepoContext, type RepositoryContext } from '../lib/context.js'; +import { + getCurrentRepoContext, + getGitRepoContext, + type RepositoryContext, +} from '../lib/context.js'; import { type KnotStore, resolveKnotStore } from '../lib/knot-store.js'; import type { PullData } from '../lib/pulls-api.js'; import { @@ -72,42 +76,110 @@ async function resolvePullUri( }; } +/** Where a pull request's head branch was pushed: its repository and that repository's remote. */ +interface HeadRepository { + context: RepositoryContext; + repoDid: string; +} + +/** `owner/name`, or a bare repository DID, as a repository selector names it. */ +function repositoryLabel(context: RepositoryContext): string { + return context.owner === context.name ? context.name : `${context.owner}/${context.name}`; +} + +/** + * The repository the head branch is pushed to. That is the target, unless + * --repo/-R or TANG_REPO selected the target and this clone's own remote is + * another repository: then the clone is a fork, and the pull request is + * opened from it. + */ +async function headRepository( + client: ReturnType, + target: RepositoryContext, + targetDid: string +): Promise { + if (target.selectionSource !== 'flag' && target.selectionSource !== 'environment') { + return { context: target, repoDid: targetDid }; + } + const local = await getGitRepoContext(); + if (!local) return { context: target, repoDid: targetDid }; + return { context: local, repoDid: await resolveRepositoryDid(local, client) }; +} + +/** + * The commit a target branch of another repository is at, fetched into this + * clone so it can be compared with the head; only FETCH_HEAD changes. + */ +async function fetchTargetBranch( + git: ReturnType, + target: RepositoryContext, + targetDid: string, + branch: string +): Promise { + const url = target.publicUrl ?? `https://tangled.org/${targetDid}`; + try { + await git.raw(['fetch', '--no-tags', url, `refs/heads/${branch}`]); + } catch (error) { + throw new Error( + `could not fetch '${branch}' from ${url}: ${error instanceof Error ? error.message : error}` + ); + } + return (await git.revparse(['FETCH_HEAD'])).trim(); +} + /** * Open a pull request in a repository's own store: a ticket and a patch naming - * the base and head commits, which the knot reads from what was pushed to it. - * So the head must be on the remote, at the commit it is here. + * the base and head commits, which the knot reads from what was pushed to the + * head's repository, the target's or a fork's. So the head must be on that + * repository's remote, at the commit it is here. */ async function createInStore(params: { client: ReturnType; store: KnotStore; git: ReturnType; context: RepositoryContext; + source: HeadRepository; title: string; body: string | undefined; baseBranch: string; + baseRef: string; headBranch: string; json: string | true | undefined; }): Promise { - const { client, store, git, context, title, body, baseBranch, headBranch, json } = params; + const { + client, + store, + git, + context, + source, + title, + body, + baseBranch, + baseRef, + headBranch, + json, + } = params; + const remoteName = source.context.remoteName; const head = (await git.revparse([headBranch])).trim(); - const remote = await git.raw(['ls-remote', context.remoteName, `refs/heads/${headBranch}`]); + const remote = await git.raw(['ls-remote', remoteName, `refs/heads/${headBranch}`]); const pushed = remote.split('\t')[0]?.trim(); if (pushed !== head) { const where = pushed ? `at ${pushed.slice(0, 7)}, not ${head.slice(0, 7)}` : 'not there'; console.error( - `✗ '${headBranch}' on ${context.remoteName} is ${where}; the knot reads the commits from it.` + `✗ '${headBranch}' on ${remoteName} is ${where}; the knot reads the commits from it.` ); - console.error(` git push ${context.remoteName} ${headBranch}`); + console.error(` git push ${remoteName} ${headBranch}`); process.exit(1); } - const base = (await git.raw(['merge-base', baseBranch, headBranch])).trim(); + const base = (await git.raw(['merge-base', baseRef, headBranch])).trim(); + const fromFork = source.repoDid !== store.repoDid; if (!wantsJson(json)) console.log('Creating pull request...'); const pull = await createPullTicket(client, store, { title, body, targetBranch: baseBranch, - source: { branch: headBranch, repo: store.repoDid }, + source: { branch: headBranch, repo: source.repoDid }, base, head, }); @@ -125,6 +197,7 @@ async function createInStore(params: { uri: pull.uri, cid: pull.cid, sourceBranch: headBranch, + sourceRepo: source.repoDid, targetBranch: baseBranch, }; outputJson(pullData, requestedFields(json)); @@ -132,7 +205,11 @@ async function createInStore(params: { } console.log(`\n✓ Pull request #${pull.id} created`); console.log(` Title: ${pull.title}`); - console.log(` ${headBranch} → ${baseBranch}`); + console.log( + fromFork + ? ` ${repositoryLabel(source.context)}:${headBranch} → ${repositoryLabel(context)}:${baseBranch}` + : ` ${headBranch} → ${baseBranch}` + ); console.log(` URI: ${pull.uri}`); if (pull.attestationError || pull.patch.attestationError) { console.warn( @@ -195,12 +272,31 @@ function createCreateCommand(): Command { // 3. Determine head branch const headBranch = options.head ?? (await git.revparse(['--abbrev-ref', 'HEAD'])).trim(); - // 4. Behind-base check + // 4. Resolve the repo DID, the store a repository of the new kind + // keeps, and the repository the head is pushed to: a fork's, when + // -R selects another. Its target branch is then compared as the + // target has it, not as a local branch of the same name has it. + const repoDid = await resolveRepositoryDid(context, client); + const store = await resolveKnotStore(repoDid); + const source = await headRepository(client, context, repoDid); + const fromFork = source.repoDid !== repoDid; + if (fromFork && !store) { + console.error( + `✗ ${repositoryLabel(context)} has no store of its own on its knot; tang opens a pull request from a fork only into a repository that keeps one.` + ); + process.exit(1); + } + const baseRef = fromFork + ? await fetchTargetBranch(git, context, repoDid, baseBranch) + : baseBranch; + const baseLabel = fromFork ? `${repositoryLabel(context)}:${baseBranch}` : baseBranch; + + // 5. Behind-base check if (!options.skipBehindCheck) { - const behindLog = await git.log([`${headBranch}..${baseBranch}`]); + const behindLog = await git.log([`${headBranch}..${baseRef}`]); const behindCount = behindLog.total; if (behindCount > 0) { - const msg = `Head branch '${headBranch}' is ${behindCount} commit(s) behind '${baseBranch}'.`; + const msg = `Head branch '${headBranch}' is ${behindCount} commit(s) behind '${baseLabel}'.`; if (wantsJson(options.json) || !inputAllowed()) { if (confirmationGranted()) { console.warn(`⚠ ${msg} Proceeding because --yes was provided.`); @@ -226,30 +322,29 @@ function createCreateCommand(): Command { } } - // 5. Generate patch - const patchContent = await git.diff([`${baseBranch}..${headBranch}`]); + // 6. Generate patch + const patchContent = await git.diff([`${baseRef}..${headBranch}`]); if (!patchContent) { console.error( - `✗ No diff found between '${baseBranch}' and '${headBranch}'. Branches may be identical.` + `✗ No diff found between '${baseLabel}' and '${headBranch}'. Branches may be identical.` ); process.exit(1); } - // 6. Handle body input + // 7. Handle body input const body = await readBodyInput(options.body, options.bodyFile); - // 7. Resolve repo DID, and the store a repository of the new kind keeps - const repoDid = await resolveRepositoryDid(context, client); - const store = await resolveKnotStore(repoDid); if (store) { await createInStore({ client, store, git, context, + source, title, body, baseBranch, + baseRef, headBranch, json: options.json, }); diff --git a/src/lib/pulls-api.ts b/src/lib/pulls-api.ts index 80e1f5b..29ded22 100644 --- a/src/lib/pulls-api.ts +++ b/src/lib/pulls-api.ts @@ -113,6 +113,8 @@ export interface PullData { uri: string; cid: string; sourceBranch?: string; + /** The repository the head is fetched from, when it is known: a fork's, or the target's own. */ + sourceRepo?: string; targetBranch: string; } diff --git a/tests/commands/pr.test.ts b/tests/commands/pr.test.ts index 16c9ba2..44fcc18 100644 --- a/tests/commands/pr.test.ts +++ b/tests/commands/pr.test.ts @@ -612,6 +612,181 @@ describe('pr create in a repository with its own store', () => { }); }); +describe('pr create from a fork, into the repository -R selects', () => { + const UPSTREAM_DID = 'did:plc:upstream'; + const FORK_DID = 'did:plc:fork'; + const STORE = { repoDid: UPSTREAM_DID, endpoint: 'https://knot.example' }; + const UPSTREAM_TIP = 'd'.repeat(40); + const BASE = 'a'.repeat(40); + const HEAD = 'b'.repeat(40); + const TARGET = { + owner: 'upstream.example', + ownerType: 'handle' as const, + name: 'tangled-cli', + remoteName: '', + remoteUrl: 'upstream.example/tangled-cli', + protocol: 'https' as const, + publicUrl: 'https://tangled.org/upstream.example/tangled-cli', + selectionSource: 'flag' as const, + }; + const FORK = { + owner: 'fork.example', + ownerType: 'handle' as const, + name: 'tangled-cli', + remoteName: 'origin', + remoteUrl: 'git@tangled.org:fork.example/tangled-cli', + protocol: 'ssh' as const, + publicUrl: 'https://tangled.org/fork.example/tangled-cli', + selectionSource: 'git' as const, + }; + let consoleLogSpy: ReturnType; + let consoleErrorSpy: ReturnType; + let gitMock: { + revparse: ReturnType; + log: ReturnType; + diff: ReturnType; + raw: ReturnType; + }; + + beforeEach(async () => { + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) as never; + consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) as never; + vi.spyOn(process, 'exit').mockImplementation((code) => { + throw new Error(`process.exit(${code})`); + }) as never; + vi.mocked(apiClient.createApiClient).mockReturnValue({ + resumeSession: vi.fn(async () => true), + } as never); + vi.mocked(context.getCurrentRepoContext).mockResolvedValue(TARGET); + vi.mocked(context.getGitRepoContext).mockResolvedValue(FORK); + vi.mocked(atUri.resolveRepoDid).mockImplementation(async (owner: string) => + owner === 'upstream.example' ? UPSTREAM_DID : FORK_DID + ); + vi.mocked(authHelpers.ensureAuthenticated).mockResolvedValue(undefined); + vi.mocked(bodyInput.readBodyInput).mockResolvedValue('Why'); + vi.mocked(knotStore.resolveKnotStore).mockImplementation(async (did: string) => + did === UPSTREAM_DID ? STORE : undefined + ); + vi.mocked(ticketsApi.createPullTicket).mockResolvedValue({ + id: '30', + number: 30, + title: 'Test PR', + body: 'Why', + state: 'open', + labels: [], + author: 'did:plc:me', + createdAt: '2026-11-04T00:00:00Z', + uri: `at://${UPSTREAM_DID}/org.tangled.track.ticket/30`, + cid: 'bafyticket', + patch: { uri: `at://${UPSTREAM_DID}/org.tangled.review.patch/bafypatch`, cid: 'bafypatch' }, + }); + gitMock = { + revparse: vi.fn(async (args: string[]) => { + if (args[0] === '--abbrev-ref') return 'feature/test\n'; + if (args[0] === 'FETCH_HEAD') return `${UPSTREAM_TIP}\n`; + return `${HEAD}\n`; + }), + log: vi.fn().mockResolvedValue({ total: 0, all: [] }), + diff: vi.fn().mockResolvedValue('diff --git a/file.ts b/file.ts\n+new line\n'), + raw: vi.fn(async (args: string[]) => { + if (args[0] === 'fetch') return ''; + if (args[0] === 'merge-base') return `${BASE}\n`; + if (args[0] === 'ls-remote') return `${HEAD}\trefs/heads/feature/test\n`; + throw new Error(`unexpected git ${args.join(' ')}`); + }), + }; + const { simpleGit } = await import('simple-git'); + vi.mocked(simpleGit).mockReturnValue(gitMock as never); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + const create = (...extra: string[]) => + createPrCommand().parseAsync([ + 'node', + 'test', + 'create', + '--title', + 'Test PR', + '--head', + 'feature/test', + ...extra, + ]); + + it("opens it in the target's store, with the fork as the repository the knot fetches the head from", async () => { + await create(); + + expect(knotStore.resolveKnotStore).toHaveBeenCalledWith(UPSTREAM_DID); + expect(ticketsApi.createPullTicket).toHaveBeenCalledWith(expect.anything(), STORE, { + title: 'Test PR', + body: 'Why', + targetBranch: 'main', + source: { branch: 'feature/test', repo: FORK_DID }, + base: BASE, + head: HEAD, + }); + const printed = consoleLogSpy.mock.calls.map((call) => String(call[0])).join('\n'); + expect(printed).toContain('Pull request #30 created'); + expect(printed).toContain( + 'fork.example/tangled-cli:feature/test → upstream.example/tangled-cli:main' + ); + }); + + it("checks the head on the fork's remote, and compares it with the target's branch, not the local one", async () => { + await create(); + + expect(gitMock.raw).toHaveBeenCalledWith(['ls-remote', 'origin', 'refs/heads/feature/test']); + expect(gitMock.raw).toHaveBeenCalledWith([ + 'fetch', + '--no-tags', + 'https://tangled.org/upstream.example/tangled-cli', + 'refs/heads/main', + ]); + expect(gitMock.raw).toHaveBeenCalledWith(['merge-base', UPSTREAM_TIP, 'feature/test']); + expect(gitMock.log).toHaveBeenCalledWith([`feature/test..${UPSTREAM_TIP}`]); + expect(gitMock.diff).toHaveBeenCalledWith([`${UPSTREAM_TIP}..feature/test`]); + }); + + it('gives the source repository in JSON', async () => { + await create('--json'); + + const printed = JSON.parse(String(consoleLogSpy.mock.calls.at(-1)?.[0])); + expect(printed).toMatchObject({ + number: 30, + sourceBranch: 'feature/test', + sourceRepo: FORK_DID, + targetBranch: 'main', + }); + }); + + it('refuses a target without a store, writing nothing', async () => { + vi.mocked(knotStore.resolveKnotStore).mockResolvedValue(undefined); + + await expect(create()).rejects.toThrow('process.exit(1)'); + + expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('no store of its own')); + expect(ticketsApi.createPullTicket).not.toHaveBeenCalled(); + expect(pullsApi.createPull).not.toHaveBeenCalled(); + expect(gitMock.raw).not.toHaveBeenCalledWith(expect.arrayContaining(['fetch'])); + }); + + it('opens a pull request within the repository when -R names the one the clone pushes to', async () => { + vi.mocked(context.getGitRepoContext).mockResolvedValue({ ...FORK, owner: 'upstream.example' }); + + await create(); + + expect(ticketsApi.createPullTicket).toHaveBeenCalledWith( + expect.anything(), + STORE, + expect.objectContaining({ source: { branch: 'feature/test', repo: UPSTREAM_DID } }) + ); + expect(gitMock.raw).not.toHaveBeenCalledWith(expect.arrayContaining(['fetch'])); + expect(gitMock.raw).toHaveBeenCalledWith(['merge-base', 'main', 'feature/test']); + }); +}); + describe('pr list, view and delete in a repository with its own store', () => { const STORE = { repoDid: REPO_DID, endpoint: 'https://knot.example' }; const pullTicket = ( -- knotmirror 0.0.1