fix: address review findings (#2036)

This commit is contained in:
Jinjing
2026-05-15 20:26:14 -07:00
committed by GitHub
parent f6282fb6e8
commit 6fe73ee1b4
5 changed files with 200 additions and 18 deletions
+10
View File
@@ -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',
+7 -3
View File
@@ -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
}
+22
View File
@@ -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', () => {
+40 -15
View File
@@ -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(
@@ -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<void>((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<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()))
})
}
})
})