From 6fe73ee1b496b7c85dc0be51082135cdab9c139d Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Fri, 15 May 2026 20:26:14 -0700 Subject: [PATCH] fix: address review findings (#2036) --- src/main/gitea/repository-ref.test.ts | 10 ++ src/main/gitea/repository-ref.ts | 10 +- src/main/gitlab/gl-utils.test.ts | 22 ++++ src/main/gitlab/gl-utils.ts | 55 +++++--- ...osted-review-bitbucket.integration.test.ts | 121 ++++++++++++++++++ 5 files changed, 200 insertions(+), 18 deletions(-) create mode 100644 src/main/source-control/hosted-review-bitbucket.integration.test.ts diff --git a/src/main/gitea/repository-ref.test.ts b/src/main/gitea/repository-ref.test.ts index 4ff86d8b7..61083b2f3 100644 --- a/src/main/gitea/repository-ref.test.ts +++ b/src/main/gitea/repository-ref.test.ts @@ -46,6 +46,16 @@ describe('Gitea repository ref parsing', () => { }) }) + it('preserves a scp-like SSH subpath when deriving the API base URL', () => { + expect(parseGiteaRepoRef('git@gitea.example.test:code/team/project.git')).toEqual({ + host: 'gitea.example.test', + owner: 'team', + repo: 'project', + apiBaseUrl: 'https://gitea.example.test/code/api/v1', + webBaseUrl: 'https://gitea.example.test/code' + }) + }) + it('parses ssh:// remotes without carrying the SSH port into web/API URLs', () => { expect(parseGiteaRepoRef('ssh://git@gitea.example.test:2222/team/project.git')).toEqual({ host: 'gitea.example.test', diff --git a/src/main/gitea/repository-ref.ts b/src/main/gitea/repository-ref.ts index d6bc6b2cc..1bae58455 100644 --- a/src/main/gitea/repository-ref.ts +++ b/src/main/gitea/repository-ref.ts @@ -51,7 +51,7 @@ function apiBaseUrlFromWebBase(webBaseUrl: string): string { return `${webBaseUrl.replace(/\/+$/, '')}/api/v1` } -function makeRepoRef(host: string, path: string, webBaseUrl: string): GiteaRepoRef | null { +function makeRepoRef(host: string, path: string, webOrigin: string): GiteaRepoRef | null { const normalizedHost = host.toLowerCase() if (!normalizedHost || KNOWN_NON_GITEA_HOSTS.has(normalizedHost)) { return null @@ -62,6 +62,11 @@ function makeRepoRef(host: string, path: string, webBaseUrl: string): GiteaRepoR return null } + // Why: Gitea/Forgejo can be hosted below a URL subpath. SSH-style remotes + // carry that base path in the repo path, so derive the web/API base here. + const webBaseUrl = parsed.basePath + ? `${webOrigin.replace(/\/+$/, '')}/${parsed.basePath}` + : webOrigin return { host: normalizedHost, owner: parsed.owner, @@ -98,8 +103,7 @@ export function parseGiteaRepoRef(remoteUrl: string): GiteaRepoRef | null { protocol === 'http:' || protocol === 'https:' ? `${protocol}//${url.host}` : `https://${url.hostname.toLowerCase()}` - const webBaseUrl = parsed.basePath ? `${webOrigin}/${parsed.basePath}` : webOrigin - return makeRepoRef(url.hostname, url.pathname, webBaseUrl) + return makeRepoRef(url.hostname, url.pathname, webOrigin) } catch { return null } diff --git a/src/main/gitlab/gl-utils.test.ts b/src/main/gitlab/gl-utils.test.ts index 96ab9a22b..c4a54fba9 100644 --- a/src/main/gitlab/gl-utils.test.ts +++ b/src/main/gitlab/gl-utils.test.ts @@ -61,6 +61,21 @@ describe('gitlab project ref parsing', () => { ).toEqual({ host: 'gitlab.example.com', path: 'team/api' }) }) + it('parses GitLab remotes with non-standard ports without treating the port as a path segment', () => { + expect( + parseGitLabProjectRef('ssh://git@gitlab.example.com:2222/team/api.git', [ + 'gitlab.com', + 'gitlab.example.com' + ]) + ).toEqual({ host: 'gitlab.example.com', path: 'team/api' }) + expect( + parseGitLabProjectRef('https://gitlab.example.com:8443/team/api.git', [ + 'gitlab.com', + 'gitlab.example.com' + ]) + ).toEqual({ host: 'gitlab.example.com', path: 'team/api' }) + }) + it('rejects single-segment paths (host root or user-only)', () => { expect(parseGitLabProjectRef('git@gitlab.com:foo.git')).toBeNull() expect(parseGitLabProjectRef('https://gitlab.com/foo.git')).toBeNull() @@ -72,6 +87,13 @@ describe('gitlab project ref parsing', () => { path: 'acme/widgets' }) }) + + it('preserves git protocol remote support', () => { + expect(parseGitLabProjectRef('git://gitlab.com/acme/widgets.git')).toEqual({ + host: 'gitlab.com', + path: 'acme/widgets' + }) + }) }) describe('gitlab project ref resolution', () => { diff --git a/src/main/gitlab/gl-utils.ts b/src/main/gitlab/gl-utils.ts index cec1a1df2..38fb75638 100644 --- a/src/main/gitlab/gl-utils.ts +++ b/src/main/gitlab/gl-utils.ts @@ -115,28 +115,53 @@ export function _resetProjectRefCache(): void { */ export const DEFAULT_GITLAB_HOSTS = ['gitlab.com'] as const +function normalizeHost(value: string): string { + return value.trim().toLowerCase() +} + +function stripGitSuffix(path: string): string { + return path.replace(/\.git$/i, '') +} + +function makeProjectRef( + host: string, + path: string, + knownHosts: readonly string[] +): ProjectRef | null { + const normalizedHost = normalizeHost(host) + if (!knownHosts.map(normalizeHost).includes(normalizedHost)) { + return null + } + const normalizedPath = stripGitSuffix(path.replace(/^\/+/, '')).trim() + // Reject paths without at least one group segment — `gitlab.com:foo` + // alone is not a project reference. + if (!normalizedPath.includes('/')) { + return null + } + return { host: normalizedHost, path: normalizedPath } +} + export function parseGitLabProjectRef( remoteUrl: string, knownHosts: readonly string[] = DEFAULT_GITLAB_HOSTS ): ProjectRef | null { const trimmed = remoteUrl.trim() - for (const host of knownHosts) { - const escapedHost = host.replace(/\./g, '\\.') - // Match SSH (git@host:path) and HTTPS (https://host/path) forms with an - // optional .git suffix. Path may contain nested groups — keep it whole. - const match = trimmed.match(new RegExp(`${escapedHost}[:/]([^\\s]+?)(?:\\.git)?$`)) - if (!match) { - continue + if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) { + const scpLike = trimmed.match(/^(?:[^@/:]+@)?([^:\s/]+):([^\s]+?)(?:\.git)?$/) + if (scpLike) { + return makeProjectRef(scpLike[1], scpLike[2], knownHosts) } - const path = match[1] - // Reject paths without at least one group segment — `gitlab.com:foo` - // alone is not a project reference. - if (!path.includes('/')) { - continue - } - return { host, path } } - return null + + try { + const url = new URL(trimmed) + if (!['http:', 'https:', 'ssh:', 'git:', 'git+ssh:'].includes(url.protocol.toLowerCase())) { + return null + } + return makeProjectRef(url.hostname, url.pathname, knownHosts) + } catch { + return null + } } export async function getProjectRefForRemote( diff --git a/src/main/source-control/hosted-review-bitbucket.integration.test.ts b/src/main/source-control/hosted-review-bitbucket.integration.test.ts new file mode 100644 index 000000000..8c66adf0a --- /dev/null +++ b/src/main/source-control/hosted-review-bitbucket.integration.test.ts @@ -0,0 +1,121 @@ +import { execFile } from 'child_process' +import { mkdtemp, rm } from 'fs/promises' +import { createServer, type IncomingMessage, type ServerResponse } from 'http' +import { tmpdir } from 'os' +import { join } from 'path' +import { promisify } from 'util' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { _resetBitbucketRepoRefCache } from '../bitbucket/repository-ref' +import { getHostedReviewForBranch } from './hosted-review' + +const execFileAsync = promisify(execFile) +const OLD_ENV = process.env + +type SeenRequest = { + pathname: string + search: string + authorization: string | undefined +} + +function sendJson(res: ServerResponse, body: unknown): void { + res.writeHead(200, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify(body)) +} + +describe('Bitbucket hosted review integration', () => { + beforeEach(() => { + process.env = { ...OLD_ENV, ORCA_BITBUCKET_ACCESS_TOKEN: 'local-token' } + delete process.env.ORCA_BITBUCKET_EMAIL + delete process.env.ORCA_BITBUCKET_API_TOKEN + _resetBitbucketRepoRefCache() + }) + + afterEach(() => { + process.env = OLD_ENV + _resetBitbucketRepoRefCache() + }) + + it('resolves a Bitbucket PR through real git remote parsing and HTTP API calls', async () => { + const seen: SeenRequest[] = [] + const server = createServer((req: IncomingMessage, res: ServerResponse) => { + const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`) + seen.push({ + pathname: url.pathname, + search: url.search, + authorization: req.headers.authorization + }) + + if (url.pathname === '/2.0/repositories/team/repo/pullrequests') { + sendJson(res, { + values: [ + { + id: 12, + title: 'Local Bitbucket branch', + state: 'OPEN', + updated_on: '2026-05-15T00:00:00Z', + links: { + html: { href: 'https://bitbucket.org/team/repo/pull-requests/12' } + }, + source: { + branch: { name: 'feature/bitbucket' }, + commit: { hash: 'abc123' } + } + } + ] + }) + return + } + + if (url.pathname === '/2.0/repositories/team/repo/commit/abc123/statuses/build') { + sendJson(res, { values: [{ state: 'SUCCESSFUL' }] }) + return + } + + res.writeHead(404, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify({ message: 'not found' })) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + + const repoPath = await mkdtemp(join(tmpdir(), 'orca-bitbucket-review-')) + try { + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('expected TCP server address') + } + + process.env.ORCA_BITBUCKET_API_BASE_URL = `http://127.0.0.1:${address.port}/2.0` + await execFileAsync('git', ['init'], { cwd: repoPath }) + await execFileAsync('git', ['remote', 'add', 'origin', 'git@bitbucket.org:team/repo.git'], { + cwd: repoPath + }) + + await expect( + getHostedReviewForBranch({ repoPath, branch: 'refs/heads/feature/bitbucket' }) + ).resolves.toEqual({ + provider: 'bitbucket', + number: 12, + title: 'Local Bitbucket branch', + state: 'open', + url: 'https://bitbucket.org/team/repo/pull-requests/12', + status: 'success', + updatedAt: '2026-05-15T00:00:00Z', + mergeable: 'UNKNOWN', + headSha: 'abc123' + }) + + expect(seen.map((request) => request.pathname)).toEqual([ + '/2.0/repositories/team/repo/pullrequests', + '/2.0/repositories/team/repo/commit/abc123/statuses/build' + ]) + expect(seen.every((request) => request.authorization === 'Bearer local-token')).toBe(true) + const query = new URLSearchParams(seen[0].search) + expect(query.get('q')).toContain('source.branch.name = "feature/bitbucket"') + expect(query.getAll('state')).toEqual(['OPEN', 'MERGED', 'DECLINED', 'SUPERSEDED']) + } finally { + await rm(repoPath, { recursive: true, force: true }) + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + } + }) +})