Add Azure DevOps Repos hosted review support
Add Azure DevOps Repos hosted review lookup, preflight, and shared hosted-review plumbing.
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
getAzureDevOpsAuthStatus,
|
||||
getAzureDevOpsPullRequestForBranch,
|
||||
normalizeAzureDevOpsApiBaseUrl
|
||||
} from './client'
|
||||
import { _resetAzureDevOpsRepoRefCache } from './repository-ref'
|
||||
|
||||
const gitExecFileAsyncMock = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('../git/runner', () => ({
|
||||
gitExecFileAsync: gitExecFileAsyncMock
|
||||
}))
|
||||
|
||||
const OLD_ENV = process.env
|
||||
const OLD_FETCH = globalThis.fetch
|
||||
|
||||
describe('Azure DevOps client', () => {
|
||||
beforeEach(() => {
|
||||
process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'pat-token' }
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
_resetAzureDevOpsRepoRefCache()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = OLD_ENV
|
||||
globalThis.fetch = OLD_FETCH
|
||||
_resetAzureDevOpsRepoRefCache()
|
||||
})
|
||||
|
||||
it('normalizes configured API base URLs', () => {
|
||||
expect(normalizeAzureDevOpsApiBaseUrl('https://dev.azure.com/acme/Project/_apis/')).toBe(
|
||||
'https://dev.azure.com/acme/Project'
|
||||
)
|
||||
})
|
||||
|
||||
it('marks token-only auth as configured but unverified because repository remotes supply the API base URL', async () => {
|
||||
delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL
|
||||
await expect(getAzureDevOpsAuthStatus()).resolves.toEqual({
|
||||
configured: true,
|
||||
authenticated: false,
|
||||
account: null,
|
||||
baseUrl: null,
|
||||
tokenConfigured: true
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves a PR for a branch through repository, PR, and status REST calls', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValue({
|
||||
stdout: 'https://dev.azure.com/acme/Project/_git/repo\n'
|
||||
})
|
||||
const requests: { pathname: string; search: string; authorization: string | null }[] = []
|
||||
globalThis.fetch = vi.fn(async (input: string | URL | Request) => {
|
||||
const url = new URL(String(input))
|
||||
requests.push({
|
||||
pathname: url.pathname,
|
||||
search: url.search,
|
||||
authorization: null
|
||||
})
|
||||
const response = (body: unknown): Response =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
|
||||
if (url.pathname === '/acme/Project/_apis/git/repositories/repo') {
|
||||
return response({
|
||||
id: 'repo-guid',
|
||||
webUrl: 'https://dev.azure.com/acme/Project/_git/repo'
|
||||
})
|
||||
}
|
||||
if (url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests') {
|
||||
expect(url.searchParams.get('searchCriteria.sourceRefName')).toBe(
|
||||
'refs/heads/feature/azure'
|
||||
)
|
||||
expect(url.searchParams.get('searchCriteria.status')).toBe('all')
|
||||
return response({
|
||||
value: [
|
||||
{
|
||||
pullRequestId: 17,
|
||||
title: 'Old Azure PR',
|
||||
status: 'completed',
|
||||
creationDate: '2026-05-10T00:00:00Z',
|
||||
lastMergeSourceCommit: { commitId: 'oldsha' }
|
||||
},
|
||||
{
|
||||
pullRequestId: 18,
|
||||
title: 'Azure branch',
|
||||
status: 'active',
|
||||
creationDate: '2026-05-11T00:00:00Z',
|
||||
mergeStatus: 'succeeded',
|
||||
lastMergeSourceCommit: { commitId: 'abc123' }
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
if (
|
||||
url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests/18/statuses'
|
||||
) {
|
||||
return response({ value: [{ state: 'succeeded' }] })
|
||||
}
|
||||
return new Response(JSON.stringify({ message: 'not found' }), { status: 404 })
|
||||
}) as never
|
||||
|
||||
await expect(
|
||||
getAzureDevOpsPullRequestForBranch('/repo', 'refs/heads/feature/azure')
|
||||
).resolves.toEqual({
|
||||
number: 18,
|
||||
title: 'Azure branch',
|
||||
state: 'open',
|
||||
url: 'https://dev.azure.com/acme/Project/_git/repo/pullrequest/18',
|
||||
status: 'success',
|
||||
updatedAt: '2026-05-11T00:00:00Z',
|
||||
mergeable: 'MERGEABLE',
|
||||
headSha: 'abc123'
|
||||
})
|
||||
expect(requests.map((request) => request.pathname)).toEqual([
|
||||
'/acme/Project/_apis/git/repositories/repo',
|
||||
'/acme/Project/_apis/git/repositories/repo-guid/pullRequests',
|
||||
'/acme/Project/_apis/git/repositories/repo-guid/pullRequests/18/statuses'
|
||||
])
|
||||
})
|
||||
|
||||
it('uses the most recent branch PR instead of preferring stale active PRs', async () => {
|
||||
gitExecFileAsyncMock.mockResolvedValue({
|
||||
stdout: 'https://dev.azure.com/acme/Project/_git/repo\n'
|
||||
})
|
||||
globalThis.fetch = vi.fn(async (input: string | URL | Request) => {
|
||||
const url = new URL(String(input))
|
||||
const response = (body: unknown): Response =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
|
||||
if (url.pathname === '/acme/Project/_apis/git/repositories/repo') {
|
||||
return response({ id: 'repo-guid' })
|
||||
}
|
||||
if (url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests') {
|
||||
return response({
|
||||
value: [
|
||||
{
|
||||
pullRequestId: 20,
|
||||
title: 'Stale active PR',
|
||||
status: 'active',
|
||||
creationDate: '2026-05-10T00:00:00Z',
|
||||
mergeStatus: 'succeeded',
|
||||
lastMergeSourceCommit: { commitId: 'oldsha' }
|
||||
},
|
||||
{
|
||||
pullRequestId: 21,
|
||||
title: 'Latest completed PR',
|
||||
status: 'completed',
|
||||
creationDate: '2026-05-15T00:00:00Z',
|
||||
closedDate: '2026-05-16T00:00:00Z',
|
||||
mergeStatus: 'succeeded',
|
||||
lastMergeSourceCommit: { commitId: 'newsha' }
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
if (
|
||||
url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests/21/statuses'
|
||||
) {
|
||||
return response({ value: [{ state: 'succeeded' }] })
|
||||
}
|
||||
return new Response(JSON.stringify({ message: 'not found' }), { status: 404 })
|
||||
}) as never
|
||||
|
||||
await expect(
|
||||
getAzureDevOpsPullRequestForBranch('/repo', 'refs/heads/feature/azure')
|
||||
).resolves.toMatchObject({
|
||||
number: 21,
|
||||
title: 'Latest completed PR',
|
||||
state: 'merged',
|
||||
headSha: 'newsha'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,327 @@
|
||||
import { Buffer } from 'buffer'
|
||||
import {
|
||||
deriveAzureDevOpsStatus,
|
||||
mapAzureDevOpsPullRequest,
|
||||
type AzureDevOpsPullRequestInfo,
|
||||
type RawAzureDevOpsPullRequest,
|
||||
type RawAzureDevOpsStatus
|
||||
} from './pull-request-mappers'
|
||||
import { getAzureDevOpsRepoRef, type AzureDevOpsRepoRef } from './repository-ref'
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 5000
|
||||
|
||||
type AzureDevOpsAuthConfig = {
|
||||
apiBaseUrl: string | null
|
||||
pat: string | null
|
||||
accessToken: string | null
|
||||
username: string | null
|
||||
}
|
||||
|
||||
export type AzureDevOpsAuthStatus = {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
account: string | null
|
||||
baseUrl: string | null
|
||||
tokenConfigured: boolean
|
||||
}
|
||||
|
||||
type RequestOptions = {
|
||||
searchParams?: Record<string, string | number>
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
type RawAzureDevOpsRepository = {
|
||||
id?: string | null
|
||||
name?: string | null
|
||||
webUrl?: string | null
|
||||
_links?: {
|
||||
web?: {
|
||||
href?: string | null
|
||||
} | null
|
||||
} | null
|
||||
}
|
||||
|
||||
function envValue(name: string): string | null {
|
||||
const value = process.env[name]?.trim() ?? ''
|
||||
return value.length > 0 ? value : null
|
||||
}
|
||||
|
||||
export function normalizeAzureDevOpsApiBaseUrl(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.replace(/\/+$/, '')
|
||||
.replace(/\/_apis$/i, '')
|
||||
}
|
||||
|
||||
function getAuthConfig(): AzureDevOpsAuthConfig {
|
||||
return {
|
||||
apiBaseUrl: envValue('ORCA_AZURE_DEVOPS_API_BASE_URL'),
|
||||
pat: envValue('ORCA_AZURE_DEVOPS_TOKEN') ?? envValue('ORCA_AZURE_DEVOPS_PAT'),
|
||||
accessToken: envValue('ORCA_AZURE_DEVOPS_ACCESS_TOKEN'),
|
||||
username: envValue('ORCA_AZURE_DEVOPS_USERNAME')
|
||||
}
|
||||
}
|
||||
|
||||
function tokenConfigured(config: AzureDevOpsAuthConfig): boolean {
|
||||
return Boolean(config.pat || config.accessToken)
|
||||
}
|
||||
|
||||
function authHeaders(config: AzureDevOpsAuthConfig): Record<string, string> {
|
||||
if (config.accessToken) {
|
||||
return { Authorization: `Bearer ${config.accessToken}` }
|
||||
}
|
||||
if (config.pat) {
|
||||
const encoded = Buffer.from(`${config.username ?? ''}:${config.pat}`).toString('base64')
|
||||
return { Authorization: `Basic ${encoded}` }
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
function configuredApiBaseUrl(repo: AzureDevOpsRepoRef): string {
|
||||
const configured = getAuthConfig().apiBaseUrl
|
||||
return configured ? normalizeAzureDevOpsApiBaseUrl(configured) : repo.apiBaseUrl
|
||||
}
|
||||
|
||||
function apiUrl(baseUrl: string, path: string, searchParams?: RequestOptions['searchParams']): URL {
|
||||
const url = new URL(`${baseUrl.replace(/\/+$/, '')}${path}`)
|
||||
const params = { ...searchParams, 'api-version': searchParams?.['api-version'] ?? '7.1' }
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, String(value))
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
async function requestJsonAtBase<T>(
|
||||
baseUrl: string,
|
||||
path: string,
|
||||
options: RequestOptions = {}
|
||||
): Promise<T | null> {
|
||||
const config = getAuthConfig()
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? REQUEST_TIMEOUT_MS)
|
||||
try {
|
||||
const response = await fetch(apiUrl(baseUrl, path, options.searchParams), {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...authHeaders(config)
|
||||
},
|
||||
signal: controller.signal
|
||||
})
|
||||
if (!response.ok) {
|
||||
return null
|
||||
}
|
||||
return (await response.json()) as T
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
function requestJson<T>(
|
||||
repo: AzureDevOpsRepoRef,
|
||||
path: string,
|
||||
options: RequestOptions = {}
|
||||
): Promise<T | null> {
|
||||
return requestJsonAtBase(configuredApiBaseUrl(repo), path, options)
|
||||
}
|
||||
|
||||
function encodePathSegment(value: string): string {
|
||||
return encodeURIComponent(value)
|
||||
}
|
||||
|
||||
async function getRepository(
|
||||
repo: AzureDevOpsRepoRef
|
||||
): Promise<{ idOrName: string; webBaseUrl: string } | null> {
|
||||
const raw = await requestJson<RawAzureDevOpsRepository>(
|
||||
repo,
|
||||
`/_apis/git/repositories/${encodePathSegment(repo.repository)}`
|
||||
)
|
||||
if (!raw) {
|
||||
return { idOrName: repo.repository, webBaseUrl: repo.webBaseUrl }
|
||||
}
|
||||
return {
|
||||
idOrName: raw.id?.trim() || repo.repository,
|
||||
webBaseUrl: raw.webUrl ?? raw._links?.web?.href ?? repo.webBaseUrl
|
||||
}
|
||||
}
|
||||
|
||||
function readStatusList(
|
||||
raw: RawAzureDevOpsStatus[] | { value?: RawAzureDevOpsStatus[] } | null
|
||||
): RawAzureDevOpsStatus[] {
|
||||
if (Array.isArray(raw)) {
|
||||
return raw
|
||||
}
|
||||
return raw?.value ?? []
|
||||
}
|
||||
|
||||
async function getPullRequestStatuses(
|
||||
repo: AzureDevOpsRepoRef,
|
||||
repoIdOrName: string,
|
||||
pr: RawAzureDevOpsPullRequest
|
||||
): Promise<RawAzureDevOpsStatus[]> {
|
||||
const raw = await requestJson<RawAzureDevOpsStatus[] | { value?: RawAzureDevOpsStatus[] }>(
|
||||
repo,
|
||||
`/_apis/git/repositories/${encodePathSegment(repoIdOrName)}/pullRequests/${encodePathSegment(
|
||||
String(pr.pullRequestId)
|
||||
)}/statuses`
|
||||
)
|
||||
const prStatuses = readStatusList(raw)
|
||||
if (prStatuses.length > 0) {
|
||||
return prStatuses
|
||||
}
|
||||
const commitId = pr.lastMergeSourceCommit?.commitId?.trim()
|
||||
if (!commitId) {
|
||||
return pr.statuses ?? []
|
||||
}
|
||||
const commitStatuses = await requestJson<
|
||||
RawAzureDevOpsStatus[] | { value?: RawAzureDevOpsStatus[] }
|
||||
>(
|
||||
repo,
|
||||
`/_apis/git/repositories/${encodePathSegment(repoIdOrName)}/commits/${encodePathSegment(
|
||||
commitId
|
||||
)}/statuses`
|
||||
)
|
||||
return readStatusList(commitStatuses)
|
||||
}
|
||||
|
||||
async function normalizePullRequest(
|
||||
repo: AzureDevOpsRepoRef,
|
||||
repoIdOrName: string,
|
||||
webBaseUrl: string,
|
||||
raw: RawAzureDevOpsPullRequest
|
||||
): Promise<AzureDevOpsPullRequestInfo | null> {
|
||||
const statuses = await getPullRequestStatuses(repo, repoIdOrName, raw)
|
||||
return mapAzureDevOpsPullRequest(raw, deriveAzureDevOpsStatus(statuses), webBaseUrl)
|
||||
}
|
||||
|
||||
function sortPullRequestsForBranch(
|
||||
left: RawAzureDevOpsPullRequest,
|
||||
right: RawAzureDevOpsPullRequest
|
||||
): number {
|
||||
const leftTime = Date.parse(left.closedDate ?? left.creationDate ?? '') || 0
|
||||
const rightTime = Date.parse(right.closedDate ?? right.creationDate ?? '') || 0
|
||||
if (leftTime !== rightTime) {
|
||||
return rightTime - leftTime
|
||||
}
|
||||
const leftActive = left.status?.trim().toLowerCase() === 'active'
|
||||
const rightActive = right.status?.trim().toLowerCase() === 'active'
|
||||
if (leftActive !== rightActive) {
|
||||
return leftActive ? -1 : 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
export async function getAzureDevOpsAuthStatus(): Promise<AzureDevOpsAuthStatus> {
|
||||
const config = getAuthConfig()
|
||||
const baseUrl = config.apiBaseUrl ? normalizeAzureDevOpsApiBaseUrl(config.apiBaseUrl) : null
|
||||
const hasToken = tokenConfigured(config)
|
||||
if (!baseUrl && !hasToken) {
|
||||
return {
|
||||
configured: false,
|
||||
authenticated: false,
|
||||
account: null,
|
||||
baseUrl: null,
|
||||
tokenConfigured: false
|
||||
}
|
||||
}
|
||||
if (!baseUrl) {
|
||||
return {
|
||||
configured: true,
|
||||
authenticated: false,
|
||||
account: null,
|
||||
baseUrl: null,
|
||||
tokenConfigured: hasToken
|
||||
}
|
||||
}
|
||||
|
||||
const connection = await requestJsonAtBase<{
|
||||
authenticatedUser?: {
|
||||
providerDisplayName?: string | null
|
||||
customDisplayName?: string | null
|
||||
uniqueName?: string | null
|
||||
} | null
|
||||
}>(baseUrl, '/_apis/connectionData', { timeoutMs: 4000 })
|
||||
const user = connection?.authenticatedUser
|
||||
return {
|
||||
configured: hasToken || connection !== null,
|
||||
authenticated: connection !== null && (hasToken || user !== null),
|
||||
account: user?.providerDisplayName ?? user?.customDisplayName ?? user?.uniqueName ?? null,
|
||||
baseUrl,
|
||||
tokenConfigured: hasToken
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAzureDevOpsPullRequest(
|
||||
repoPath: string,
|
||||
prNumber: number
|
||||
): Promise<AzureDevOpsPullRequestInfo | null> {
|
||||
const repo = await getAzureDevOpsRepoRef(repoPath)
|
||||
if (!repo) {
|
||||
return null
|
||||
}
|
||||
const repository = await getRepository(repo)
|
||||
if (!repository) {
|
||||
return null
|
||||
}
|
||||
const raw = await requestJson<RawAzureDevOpsPullRequest>(
|
||||
repo,
|
||||
`/_apis/git/repositories/${encodePathSegment(repository.idOrName)}/pullRequests/${encodePathSegment(
|
||||
String(prNumber)
|
||||
)}`
|
||||
)
|
||||
return raw ? normalizePullRequest(repo, repository.idOrName, repository.webBaseUrl, raw) : null
|
||||
}
|
||||
|
||||
export async function getAzureDevOpsPullRequestForBranch(
|
||||
repoPath: string,
|
||||
branch: string,
|
||||
linkedPRNumber?: number | null
|
||||
): Promise<AzureDevOpsPullRequestInfo | null> {
|
||||
const branchName = branch.replace(/^refs\/heads\//, '')
|
||||
if (!branchName && linkedPRNumber == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
const repo = await getAzureDevOpsRepoRef(repoPath)
|
||||
if (!repo) {
|
||||
return null
|
||||
}
|
||||
const repository = await getRepository(repo)
|
||||
if (!repository) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (branchName) {
|
||||
const list = await requestJson<{ value?: RawAzureDevOpsPullRequest[] }>(
|
||||
repo,
|
||||
`/_apis/git/repositories/${encodePathSegment(repository.idOrName)}/pullRequests`,
|
||||
{
|
||||
searchParams: {
|
||||
'searchCriteria.sourceRefName': `refs/heads/${branchName}`,
|
||||
'searchCriteria.status': 'all',
|
||||
$top: 10
|
||||
}
|
||||
}
|
||||
)
|
||||
const raw = (list?.value ?? []).sort(sortPullRequestsForBranch)[0]
|
||||
if (raw) {
|
||||
return normalizePullRequest(repo, repository.idOrName, repository.webBaseUrl, raw)
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof linkedPRNumber !== 'number') {
|
||||
return null
|
||||
}
|
||||
const raw = await requestJson<RawAzureDevOpsPullRequest>(
|
||||
repo,
|
||||
`/_apis/git/repositories/${encodePathSegment(repository.idOrName)}/pullRequests/${encodePathSegment(
|
||||
String(linkedPRNumber)
|
||||
)}`
|
||||
)
|
||||
return raw ? normalizePullRequest(repo, repository.idOrName, repository.webBaseUrl, raw) : null
|
||||
}
|
||||
|
||||
export async function getAzureDevOpsRepoSlug(repoPath: string): Promise<AzureDevOpsRepoRef | null> {
|
||||
return getAzureDevOpsRepoRef(repoPath)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
deriveAzureDevOpsStatus,
|
||||
mapAzureDevOpsPullRequest,
|
||||
mapAzureDevOpsPullRequestState
|
||||
} from './pull-request-mappers'
|
||||
|
||||
describe('Azure DevOps pull request mappers', () => {
|
||||
it('maps Azure DevOps PR states into the hosted review state set', () => {
|
||||
expect(mapAzureDevOpsPullRequestState({ status: 'active' })).toBe('open')
|
||||
expect(mapAzureDevOpsPullRequestState({ status: 'active', isDraft: true })).toBe('draft')
|
||||
expect(mapAzureDevOpsPullRequestState({ status: 'completed' })).toBe('merged')
|
||||
expect(mapAzureDevOpsPullRequestState({ status: 'abandoned' })).toBe('closed')
|
||||
})
|
||||
|
||||
it('derives check status from Azure DevOps PR and commit status states', () => {
|
||||
expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }])).toBe('success')
|
||||
expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }, { state: 'pending' }])).toBe('pending')
|
||||
expect(deriveAzureDevOpsStatus([{ state: 'succeeded' }, { state: 'failed' }])).toBe('failure')
|
||||
expect(deriveAzureDevOpsStatus([])).toBe('neutral')
|
||||
})
|
||||
|
||||
it('maps a raw PR into hosted review info', () => {
|
||||
expect(
|
||||
mapAzureDevOpsPullRequest(
|
||||
{
|
||||
pullRequestId: 42,
|
||||
title: 'Add Azure support',
|
||||
status: 'active',
|
||||
creationDate: '2026-05-15T12:00:00Z',
|
||||
mergeStatus: 'succeeded',
|
||||
lastMergeSourceCommit: { commitId: 'abc123' }
|
||||
},
|
||||
'success',
|
||||
'https://dev.azure.com/acme/Project/_git/repo'
|
||||
)
|
||||
).toEqual({
|
||||
number: 42,
|
||||
title: 'Add Azure support',
|
||||
state: 'open',
|
||||
url: 'https://dev.azure.com/acme/Project/_git/repo/pullrequest/42',
|
||||
status: 'success',
|
||||
updatedAt: '2026-05-15T12:00:00Z',
|
||||
mergeable: 'MERGEABLE',
|
||||
headSha: 'abc123'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { CheckStatus, PRMergeableState } from '../../shared/types'
|
||||
|
||||
export type RawAzureDevOpsStatus = {
|
||||
state?: string | null
|
||||
}
|
||||
|
||||
export type RawAzureDevOpsPullRequest = {
|
||||
pullRequestId?: number
|
||||
codeReviewId?: number
|
||||
title?: string | null
|
||||
status?: string | null
|
||||
isDraft?: boolean | null
|
||||
creationDate?: string | null
|
||||
closedDate?: string | null
|
||||
mergeStatus?: string | null
|
||||
sourceRefName?: string | null
|
||||
lastMergeSourceCommit?: {
|
||||
commitId?: string | null
|
||||
} | null
|
||||
statuses?: RawAzureDevOpsStatus[] | null
|
||||
_links?: {
|
||||
web?: {
|
||||
href?: string | null
|
||||
} | null
|
||||
} | null
|
||||
}
|
||||
|
||||
export type AzureDevOpsPullRequestInfo = {
|
||||
number: number
|
||||
title: string
|
||||
state: 'open' | 'closed' | 'merged' | 'draft'
|
||||
url: string
|
||||
status: CheckStatus
|
||||
updatedAt: string
|
||||
mergeable: PRMergeableState
|
||||
headSha?: string
|
||||
}
|
||||
|
||||
export function mapAzureDevOpsPullRequestState(
|
||||
raw: Pick<RawAzureDevOpsPullRequest, 'isDraft' | 'status'>
|
||||
): AzureDevOpsPullRequestInfo['state'] {
|
||||
const status = raw.status?.trim().toLowerCase()
|
||||
if (status === 'completed') {
|
||||
return 'merged'
|
||||
}
|
||||
if (status === 'abandoned') {
|
||||
return 'closed'
|
||||
}
|
||||
if (raw.isDraft) {
|
||||
return 'draft'
|
||||
}
|
||||
return 'open'
|
||||
}
|
||||
|
||||
export function mapAzureDevOpsMergeable(mergeStatus: string | null | undefined): PRMergeableState {
|
||||
switch (mergeStatus?.trim().toLowerCase()) {
|
||||
case 'succeeded':
|
||||
return 'MERGEABLE'
|
||||
case 'conflicts':
|
||||
return 'CONFLICTING'
|
||||
default:
|
||||
return 'UNKNOWN'
|
||||
}
|
||||
}
|
||||
|
||||
function classifyAzureDevOpsStatus(state: string | null | undefined): CheckStatus {
|
||||
switch (state?.trim().toLowerCase()) {
|
||||
case 'succeeded':
|
||||
case 'success':
|
||||
return 'success'
|
||||
case 'failed':
|
||||
case 'error':
|
||||
case 'rejected':
|
||||
case 'canceled':
|
||||
case 'cancelled':
|
||||
return 'failure'
|
||||
case 'pending':
|
||||
case 'inprogress':
|
||||
case 'in_progress':
|
||||
case 'queued':
|
||||
case 'running':
|
||||
return 'pending'
|
||||
default:
|
||||
return 'neutral'
|
||||
}
|
||||
}
|
||||
|
||||
export function deriveAzureDevOpsStatus(statuses: readonly RawAzureDevOpsStatus[]): CheckStatus {
|
||||
if (statuses.length === 0) {
|
||||
return 'neutral'
|
||||
}
|
||||
const classified = statuses.map((status) => classifyAzureDevOpsStatus(status.state))
|
||||
if (classified.includes('failure')) {
|
||||
return 'failure'
|
||||
}
|
||||
if (classified.includes('pending')) {
|
||||
return 'pending'
|
||||
}
|
||||
if (classified.every((status) => status === 'success')) {
|
||||
return 'success'
|
||||
}
|
||||
return 'neutral'
|
||||
}
|
||||
|
||||
export function mapAzureDevOpsPullRequest(
|
||||
raw: RawAzureDevOpsPullRequest,
|
||||
status: CheckStatus,
|
||||
webBaseUrl: string
|
||||
): AzureDevOpsPullRequestInfo | null {
|
||||
if (typeof raw.pullRequestId !== 'number' || !raw.title) {
|
||||
return null
|
||||
}
|
||||
const headSha = raw.lastMergeSourceCommit?.commitId?.trim()
|
||||
return {
|
||||
number: raw.pullRequestId,
|
||||
title: raw.title,
|
||||
state: mapAzureDevOpsPullRequestState(raw),
|
||||
url:
|
||||
raw._links?.web?.href ?? `${webBaseUrl.replace(/\/+$/, '')}/pullrequest/${raw.pullRequestId}`,
|
||||
status,
|
||||
updatedAt: raw.closedDate ?? raw.creationDate ?? '',
|
||||
mergeable: mapAzureDevOpsMergeable(raw.mergeStatus),
|
||||
...(headSha ? { headSha } : {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseAzureDevOpsRepoRef } from './repository-ref'
|
||||
|
||||
describe('parseAzureDevOpsRepoRef', () => {
|
||||
it('parses dev.azure.com HTTPS remotes', () => {
|
||||
expect(
|
||||
parseAzureDevOpsRepoRef('https://dev.azure.com/acme/Project%20One/_git/repo-name')
|
||||
).toEqual({
|
||||
host: 'dev.azure.com',
|
||||
organization: 'acme',
|
||||
project: 'Project One',
|
||||
repository: 'repo-name',
|
||||
apiBaseUrl: 'https://dev.azure.com/acme/Project%20One',
|
||||
webBaseUrl: 'https://dev.azure.com/acme/Project%20One/_git/repo-name'
|
||||
})
|
||||
})
|
||||
|
||||
it('parses legacy visualstudio.com HTTPS remotes', () => {
|
||||
expect(parseAzureDevOpsRepoRef('https://acme.visualstudio.com/Project/_git/repo.git')).toEqual({
|
||||
host: 'acme.visualstudio.com',
|
||||
organization: 'acme',
|
||||
project: 'Project',
|
||||
repository: 'repo',
|
||||
apiBaseUrl: 'https://acme.visualstudio.com/Project',
|
||||
webBaseUrl: 'https://acme.visualstudio.com/Project/_git/repo'
|
||||
})
|
||||
})
|
||||
|
||||
it('parses Azure DevOps Services SSH remotes', () => {
|
||||
expect(parseAzureDevOpsRepoRef('git@ssh.dev.azure.com:v3/acme/Project/repo')).toEqual({
|
||||
host: 'dev.azure.com',
|
||||
organization: 'acme',
|
||||
project: 'Project',
|
||||
repository: 'repo',
|
||||
apiBaseUrl: 'https://dev.azure.com/acme/Project',
|
||||
webBaseUrl: 'https://dev.azure.com/acme/Project/_git/repo'
|
||||
})
|
||||
})
|
||||
|
||||
it('parses Azure DevOps Server HTTPS remotes from the _git path convention', () => {
|
||||
expect(
|
||||
parseAzureDevOpsRepoRef('https://ado.example.com/tfs/DefaultCollection/Project/_git/repo.git')
|
||||
).toEqual({
|
||||
host: 'ado.example.com',
|
||||
organization: null,
|
||||
project: 'Project',
|
||||
repository: 'repo',
|
||||
apiBaseUrl: 'https://ado.example.com/tfs/DefaultCollection/Project',
|
||||
webBaseUrl: 'https://ado.example.com/tfs/DefaultCollection/Project/_git/repo'
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores non-Azure remotes', () => {
|
||||
expect(parseAzureDevOpsRepoRef('git@github.com:stablyai/orca.git')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
import { gitExecFileAsync } from '../git/runner'
|
||||
|
||||
export type AzureDevOpsRepoRef = {
|
||||
host: string
|
||||
project: string
|
||||
repository: string
|
||||
apiBaseUrl: string
|
||||
webBaseUrl: string
|
||||
organization?: string | null
|
||||
}
|
||||
|
||||
const repoRefCache = new Map<string, AzureDevOpsRepoRef | null>()
|
||||
|
||||
/** @internal - exposed for tests only */
|
||||
export function _resetAzureDevOpsRepoRefCache(): void {
|
||||
repoRefCache.clear()
|
||||
}
|
||||
|
||||
function decodeSegment(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value)
|
||||
} catch {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
function encodeSegment(value: string): string {
|
||||
return encodeURIComponent(value)
|
||||
}
|
||||
|
||||
function splitPath(path: string): string[] {
|
||||
return path
|
||||
.replace(/\.git$/i, '')
|
||||
.split('/')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
.map(decodeSegment)
|
||||
}
|
||||
|
||||
function joinUrl(origin: string, segments: readonly string[]): string {
|
||||
const path = segments.map(encodeSegment).join('/')
|
||||
return path ? `${origin.replace(/\/+$/, '')}/${path}` : origin.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
function parseGitHttpPath(
|
||||
pathname: string
|
||||
): { prefix: string[]; project: string; repository: string } | null {
|
||||
const parts = splitPath(pathname)
|
||||
const gitIndex = parts.findIndex((part) => part.toLowerCase() === '_git')
|
||||
if (gitIndex < 1 || gitIndex + 1 >= parts.length) {
|
||||
return null
|
||||
}
|
||||
const project = parts[gitIndex - 1]
|
||||
const repository = parts[gitIndex + 1]
|
||||
if (!project || !repository) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
prefix: parts.slice(0, gitIndex - 1),
|
||||
project,
|
||||
repository
|
||||
}
|
||||
}
|
||||
|
||||
function makeCloudRef(
|
||||
host: string,
|
||||
organization: string,
|
||||
project: string,
|
||||
repository: string
|
||||
): AzureDevOpsRepoRef {
|
||||
return {
|
||||
host: host.toLowerCase(),
|
||||
organization,
|
||||
project,
|
||||
repository,
|
||||
apiBaseUrl: joinUrl('https://dev.azure.com', [organization, project]),
|
||||
webBaseUrl: joinUrl('https://dev.azure.com', [organization, project, '_git', repository])
|
||||
}
|
||||
}
|
||||
|
||||
function makeServerRef(
|
||||
host: string,
|
||||
origin: string,
|
||||
prefix: readonly string[],
|
||||
project: string,
|
||||
repository: string
|
||||
): AzureDevOpsRepoRef {
|
||||
return {
|
||||
host: host.toLowerCase(),
|
||||
organization: null,
|
||||
project,
|
||||
repository,
|
||||
apiBaseUrl: joinUrl(origin, [...prefix, project]),
|
||||
webBaseUrl: joinUrl(origin, [...prefix, project, '_git', repository])
|
||||
}
|
||||
}
|
||||
|
||||
function parseDevAzureUrl(url: URL): AzureDevOpsRepoRef | null {
|
||||
const parsed = parseGitHttpPath(url.pathname)
|
||||
const organization = parsed?.prefix[0]
|
||||
if (!parsed || !organization) {
|
||||
return null
|
||||
}
|
||||
return makeCloudRef(url.hostname, organization, parsed.project, parsed.repository)
|
||||
}
|
||||
|
||||
function parseVisualStudioUrl(url: URL): AzureDevOpsRepoRef | null {
|
||||
const parsed = parseGitHttpPath(url.pathname)
|
||||
const suffix = '.visualstudio.com'
|
||||
const host = url.hostname.toLowerCase()
|
||||
if (!parsed || !host.endsWith(suffix)) {
|
||||
return null
|
||||
}
|
||||
const organization = host.slice(0, -suffix.length)
|
||||
if (!organization) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
host,
|
||||
organization,
|
||||
project: parsed.project,
|
||||
repository: parsed.repository,
|
||||
apiBaseUrl: joinUrl(url.origin, [...parsed.prefix, parsed.project]),
|
||||
webBaseUrl: joinUrl(url.origin, [...parsed.prefix, parsed.project, '_git', parsed.repository])
|
||||
}
|
||||
}
|
||||
|
||||
function parseCloudSshPath(host: string, rawPath: string): AzureDevOpsRepoRef | null {
|
||||
if (host.toLowerCase() !== 'ssh.dev.azure.com') {
|
||||
return null
|
||||
}
|
||||
const parts = splitPath(rawPath)
|
||||
if (parts.length < 4 || parts[0].toLowerCase() !== 'v3') {
|
||||
return null
|
||||
}
|
||||
const [, organization, project, repository] = parts
|
||||
if (!organization || !project || !repository) {
|
||||
return null
|
||||
}
|
||||
return makeCloudRef('dev.azure.com', organization, project, repository)
|
||||
}
|
||||
|
||||
function parseScpLike(remoteUrl: string): AzureDevOpsRepoRef | null {
|
||||
const match = remoteUrl.match(/^(?:[^@/:]+@)?([^:\s/]+):([^\s]+?)(?:\.git)?$/)
|
||||
if (!match) {
|
||||
return null
|
||||
}
|
||||
return parseCloudSshPath(match[1], match[2])
|
||||
}
|
||||
|
||||
export function parseAzureDevOpsRepoRef(remoteUrl: string): AzureDevOpsRepoRef | null {
|
||||
const trimmed = remoteUrl.trim()
|
||||
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
|
||||
return parseScpLike(trimmed)
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(trimmed)
|
||||
const host = url.hostname.toLowerCase()
|
||||
if (host === 'ssh.dev.azure.com') {
|
||||
return parseCloudSshPath(host, url.pathname)
|
||||
}
|
||||
if (!['http:', 'https:', 'ssh:', 'git+ssh:'].includes(url.protocol.toLowerCase())) {
|
||||
return null
|
||||
}
|
||||
if (host === 'dev.azure.com') {
|
||||
return parseDevAzureUrl(url)
|
||||
}
|
||||
if (host.endsWith('.visualstudio.com')) {
|
||||
return parseVisualStudioUrl(url)
|
||||
}
|
||||
|
||||
const parsed = parseGitHttpPath(url.pathname)
|
||||
if (!parsed || !['http:', 'https:'].includes(url.protocol.toLowerCase())) {
|
||||
return null
|
||||
}
|
||||
// Why: Azure DevOps Server remotes are self-hosted and only reliably
|
||||
// identifiable by the `_git` path convention.
|
||||
return makeServerRef(host, url.origin, parsed.prefix, parsed.project, parsed.repository)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAzureDevOpsRepoRefForRemote(
|
||||
repoPath: string,
|
||||
remoteName: string
|
||||
): Promise<AzureDevOpsRepoRef | null> {
|
||||
const cacheKey = `${repoPath}\0${remoteName}`
|
||||
if (repoRefCache.has(cacheKey)) {
|
||||
return repoRefCache.get(cacheKey)!
|
||||
}
|
||||
try {
|
||||
const { stdout } = await gitExecFileAsync(['remote', 'get-url', remoteName], {
|
||||
cwd: repoPath
|
||||
})
|
||||
const result = parseAzureDevOpsRepoRef(stdout)
|
||||
repoRefCache.set(cacheKey, result)
|
||||
return result
|
||||
} catch {
|
||||
repoRefCache.set(cacheKey, null)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAzureDevOpsRepoRef(repoPath: string): Promise<AzureDevOpsRepoRef | null> {
|
||||
return getAzureDevOpsRepoRefForRemote(repoPath, 'origin')
|
||||
}
|
||||
@@ -70,6 +70,8 @@ describe('Gitea repository ref parsing', () => {
|
||||
expect(parseGiteaRepoRef('git@github.com:team/project.git')).toBeNull()
|
||||
expect(parseGiteaRepoRef('https://gitlab.com/team/project.git')).toBeNull()
|
||||
expect(parseGiteaRepoRef('https://bitbucket.org/team/project.git')).toBeNull()
|
||||
expect(parseGiteaRepoRef('https://dev.azure.com/team/project/_git/repo')).toBeNull()
|
||||
expect(parseGiteaRepoRef('https://team.visualstudio.com/project/_git/repo')).toBeNull()
|
||||
})
|
||||
|
||||
it('reads and caches the origin remote', async () => {
|
||||
|
||||
@@ -8,7 +8,13 @@ export type GiteaRepoRef = {
|
||||
webBaseUrl: string
|
||||
}
|
||||
|
||||
const KNOWN_NON_GITEA_HOSTS = new Set(['github.com', 'gitlab.com', 'bitbucket.org'])
|
||||
const KNOWN_NON_GITEA_HOSTS = new Set([
|
||||
'github.com',
|
||||
'gitlab.com',
|
||||
'bitbucket.org',
|
||||
'dev.azure.com',
|
||||
'ssh.dev.azure.com'
|
||||
])
|
||||
const repoRefCache = new Map<string, GiteaRepoRef | null>()
|
||||
|
||||
/** @internal - exposed for tests only */
|
||||
@@ -53,7 +59,11 @@ function apiBaseUrlFromWebBase(webBaseUrl: string): string {
|
||||
|
||||
function makeRepoRef(host: string, path: string, webOrigin: string): GiteaRepoRef | null {
|
||||
const normalizedHost = host.toLowerCase()
|
||||
if (!normalizedHost || KNOWN_NON_GITEA_HOSTS.has(normalizedHost)) {
|
||||
if (
|
||||
!normalizedHost ||
|
||||
KNOWN_NON_GITEA_HOSTS.has(normalizedHost) ||
|
||||
normalizedHost.endsWith('.visualstudio.com')
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector
|
||||
linkedGitHubPR: args.linkedGitHubPR ?? null,
|
||||
linkedGitLabMR: args.linkedGitLabMR ?? null,
|
||||
linkedBitbucketPR: args.linkedBitbucketPR ?? null,
|
||||
linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null,
|
||||
linkedGiteaPR: args.linkedGiteaPR ?? null
|
||||
})
|
||||
if (review?.provider === 'github' && !stats.hasCountedPR(review.url)) {
|
||||
|
||||
@@ -9,6 +9,7 @@ const {
|
||||
hydrateShellPathMock,
|
||||
mergePathSegmentsMock,
|
||||
getBitbucketAuthStatusMock,
|
||||
getAzureDevOpsAuthStatusMock,
|
||||
getGiteaAuthStatusMock
|
||||
} = vi.hoisted(() => ({
|
||||
handleMock: vi.fn(),
|
||||
@@ -17,6 +18,7 @@ const {
|
||||
hydrateShellPathMock: vi.fn(),
|
||||
mergePathSegmentsMock: vi.fn(),
|
||||
getBitbucketAuthStatusMock: vi.fn(),
|
||||
getAzureDevOpsAuthStatusMock: vi.fn(),
|
||||
getGiteaAuthStatusMock: vi.fn()
|
||||
}))
|
||||
|
||||
@@ -45,6 +47,10 @@ vi.mock('../bitbucket/client', () => ({
|
||||
getBitbucketAuthStatus: getBitbucketAuthStatusMock
|
||||
}))
|
||||
|
||||
vi.mock('../azure-devops/client', () => ({
|
||||
getAzureDevOpsAuthStatus: getAzureDevOpsAuthStatusMock
|
||||
}))
|
||||
|
||||
vi.mock('../gitea/client', () => ({
|
||||
getGiteaAuthStatus: getGiteaAuthStatusMock
|
||||
}))
|
||||
@@ -61,6 +67,13 @@ type HandlerMap = Record<string, (_event?: unknown, args?: { force?: boolean })
|
||||
describe('preflight', () => {
|
||||
const handlers: HandlerMap = {}
|
||||
const defaultBitbucketStatus = { configured: false, authenticated: false, account: null }
|
||||
const defaultAzureDevOpsStatus = {
|
||||
configured: false,
|
||||
authenticated: false,
|
||||
account: null,
|
||||
baseUrl: null,
|
||||
tokenConfigured: false
|
||||
}
|
||||
const defaultGiteaStatus = {
|
||||
configured: false,
|
||||
authenticated: false,
|
||||
@@ -75,8 +88,10 @@ describe('preflight', () => {
|
||||
hydrateShellPathMock.mockReset()
|
||||
mergePathSegmentsMock.mockReset()
|
||||
getBitbucketAuthStatusMock.mockReset()
|
||||
getAzureDevOpsAuthStatusMock.mockReset()
|
||||
getGiteaAuthStatusMock.mockReset()
|
||||
getBitbucketAuthStatusMock.mockResolvedValue(defaultBitbucketStatus)
|
||||
getAzureDevOpsAuthStatusMock.mockResolvedValue(defaultAzureDevOpsStatus)
|
||||
getGiteaAuthStatusMock.mockResolvedValue(defaultGiteaStatus)
|
||||
_resetPreflightCache()
|
||||
|
||||
@@ -107,6 +122,7 @@ describe('preflight', () => {
|
||||
gh: { installed: true, authenticated: true },
|
||||
glab: { installed: true, authenticated: true },
|
||||
bitbucket: defaultBitbucketStatus,
|
||||
azureDevOps: defaultAzureDevOpsStatus,
|
||||
gitea: defaultGiteaStatus
|
||||
})
|
||||
expect(execFileAsyncMock).toHaveBeenNthCalledWith(4, 'gh', ['auth', 'status'], {
|
||||
@@ -209,6 +225,7 @@ describe('preflight', () => {
|
||||
gh: { installed: true, authenticated: true },
|
||||
glab: { installed: true, authenticated: true },
|
||||
bitbucket: defaultBitbucketStatus,
|
||||
azureDevOps: defaultAzureDevOpsStatus,
|
||||
gitea: defaultGiteaStatus
|
||||
})
|
||||
})
|
||||
@@ -236,6 +253,7 @@ describe('preflight', () => {
|
||||
gh: { installed: true, authenticated: false },
|
||||
glab: { installed: true, authenticated: true },
|
||||
bitbucket: defaultBitbucketStatus,
|
||||
azureDevOps: defaultAzureDevOpsStatus,
|
||||
gitea: defaultGiteaStatus
|
||||
})
|
||||
expect(refreshedStatus).toEqual({
|
||||
@@ -243,6 +261,7 @@ describe('preflight', () => {
|
||||
gh: { installed: true, authenticated: true },
|
||||
glab: { installed: true, authenticated: true },
|
||||
bitbucket: defaultBitbucketStatus,
|
||||
azureDevOps: defaultAzureDevOpsStatus,
|
||||
gitea: defaultGiteaStatus
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@ import path from 'path'
|
||||
import { TUI_AGENT_CONFIG } from '../../shared/tui-agent-config'
|
||||
import type { PathSource, ShellHydrationFailureReason } from '../../shared/types'
|
||||
import { hydrateShellPath, mergePathSegments } from '../startup/hydrate-shell-path'
|
||||
import { getAzureDevOpsAuthStatus } from '../azure-devops/client'
|
||||
import { getBitbucketAuthStatus } from '../bitbucket/client'
|
||||
import { getGiteaAuthStatus } from '../gitea/client'
|
||||
import { getActiveMultiplexer } from './ssh'
|
||||
@@ -20,6 +21,13 @@ export type PreflightStatus = {
|
||||
// gate on `glab?.authenticated`.
|
||||
glab?: { installed: boolean; authenticated: boolean }
|
||||
bitbucket?: { configured: boolean; authenticated: boolean; account: string | null }
|
||||
azureDevOps?: {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
account: string | null
|
||||
baseUrl: string | null
|
||||
tokenConfigured: boolean
|
||||
}
|
||||
gitea?: {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
@@ -169,10 +177,11 @@ export async function runPreflightCheck(force = false): Promise<PreflightStatus>
|
||||
isCommandAvailable('glab')
|
||||
])
|
||||
|
||||
const [ghAuthenticated, glabAuthenticated, bitbucket, gitea] = await Promise.all([
|
||||
const [ghAuthenticated, glabAuthenticated, bitbucket, azureDevOps, gitea] = await Promise.all([
|
||||
ghInstalled ? isGhAuthenticated() : Promise.resolve(false),
|
||||
glabInstalled ? isGlabAuthenticated() : Promise.resolve(false),
|
||||
getBitbucketAuthStatus(),
|
||||
getAzureDevOpsAuthStatus(),
|
||||
getGiteaAuthStatus()
|
||||
])
|
||||
|
||||
@@ -181,6 +190,7 @@ export async function runPreflightCheck(force = false): Promise<PreflightStatus>
|
||||
gh: { installed: ghInstalled, authenticated: ghAuthenticated },
|
||||
glab: { installed: glabInstalled, authenticated: glabAuthenticated },
|
||||
bitbucket,
|
||||
azureDevOps,
|
||||
gitea
|
||||
}
|
||||
|
||||
|
||||
@@ -4544,6 +4544,7 @@ export class OrcaRuntimeService {
|
||||
linkedGitHubPR?: number | null
|
||||
linkedGitLabMR?: number | null
|
||||
linkedBitbucketPR?: number | null
|
||||
linkedAzureDevOpsPR?: number | null
|
||||
linkedGiteaPR?: number | null
|
||||
}): Promise<HostedReviewInfo | null> {
|
||||
const repo = await this.resolveRepoSelector(args.repoSelector)
|
||||
@@ -4554,6 +4555,7 @@ export class OrcaRuntimeService {
|
||||
linkedGitHubPR: args.linkedGitHubPR ?? null,
|
||||
linkedGitLabMR: args.linkedGitLabMR ?? null,
|
||||
linkedBitbucketPR: args.linkedBitbucketPR ?? null,
|
||||
linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null,
|
||||
linkedGiteaPR: args.linkedGiteaPR ?? null
|
||||
})
|
||||
if (review?.provider === 'github' && this.stats && !this.stats.hasCountedPR(review.url)) {
|
||||
@@ -4583,6 +4585,7 @@ export class OrcaRuntimeService {
|
||||
linkedGitHubPR: args.linkedGitHubPR ?? null,
|
||||
linkedGitLabMR: args.linkedGitLabMR ?? null,
|
||||
linkedBitbucketPR: args.linkedBitbucketPR ?? null,
|
||||
linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null,
|
||||
linkedGiteaPR: args.linkedGiteaPR ?? null
|
||||
})
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ describe('hosted review RPC methods', () => {
|
||||
linkedGitHubPR: 12,
|
||||
linkedGitLabMR: null,
|
||||
linkedBitbucketPR: null,
|
||||
linkedAzureDevOpsPR: null,
|
||||
linkedGiteaPR: null
|
||||
})
|
||||
expect(response).toMatchObject({
|
||||
@@ -87,6 +88,7 @@ describe('hosted review RPC methods', () => {
|
||||
linkedGitHubPR: null,
|
||||
linkedGitLabMR: null,
|
||||
linkedBitbucketPR: null,
|
||||
linkedAzureDevOpsPR: null,
|
||||
linkedGiteaPR: null
|
||||
})
|
||||
expect(response).toMatchObject({
|
||||
|
||||
@@ -8,6 +8,7 @@ const HostedReviewForBranch = z.object({
|
||||
linkedGitHubPR: z.number().int().positive().nullable().optional(),
|
||||
linkedGitLabMR: z.number().int().positive().nullable().optional(),
|
||||
linkedBitbucketPR: z.number().int().positive().nullable().optional(),
|
||||
linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(),
|
||||
linkedGiteaPR: z.number().int().positive().nullable().optional()
|
||||
})
|
||||
|
||||
@@ -22,12 +23,13 @@ const HostedReviewCreationEligibility = z.object({
|
||||
linkedGitHubPR: z.number().int().positive().nullable().optional(),
|
||||
linkedGitLabMR: z.number().int().positive().nullable().optional(),
|
||||
linkedBitbucketPR: z.number().int().positive().nullable().optional(),
|
||||
linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(),
|
||||
linkedGiteaPR: z.number().int().positive().nullable().optional()
|
||||
})
|
||||
|
||||
const HostedReviewCreate = z.object({
|
||||
repo: requiredString('Missing repo selector'),
|
||||
provider: z.enum(['github', 'gitlab', 'bitbucket', 'gitea', 'unsupported']),
|
||||
provider: z.enum(['github', 'gitlab', 'bitbucket', 'azure-devops', 'gitea', 'unsupported']),
|
||||
base: requiredString('Missing base branch'),
|
||||
head: z.string().optional(),
|
||||
title: requiredString('Missing title'),
|
||||
@@ -46,6 +48,7 @@ export const HOSTED_REVIEW_METHODS: RpcMethod[] = [
|
||||
linkedGitHubPR: params.linkedGitHubPR ?? null,
|
||||
linkedGitLabMR: params.linkedGitLabMR ?? null,
|
||||
linkedBitbucketPR: params.linkedBitbucketPR ?? null,
|
||||
linkedAzureDevOpsPR: params.linkedAzureDevOpsPR ?? null,
|
||||
linkedGiteaPR: params.linkedGiteaPR ?? null
|
||||
})
|
||||
}),
|
||||
@@ -64,6 +67,7 @@ export const HOSTED_REVIEW_METHODS: RpcMethod[] = [
|
||||
linkedGitHubPR: params.linkedGitHubPR ?? null,
|
||||
linkedGitLabMR: params.linkedGitLabMR ?? null,
|
||||
linkedBitbucketPR: params.linkedBitbucketPR ?? null,
|
||||
linkedAzureDevOpsPR: params.linkedAzureDevOpsPR ?? null,
|
||||
linkedGiteaPR: params.linkedGiteaPR ?? null
|
||||
})
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
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 { _resetAzureDevOpsRepoRefCache } from '../azure-devops/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('Azure DevOps hosted review integration', () => {
|
||||
beforeEach(() => {
|
||||
process.env = { ...OLD_ENV, ORCA_AZURE_DEVOPS_TOKEN: 'local-pat' }
|
||||
delete process.env.ORCA_AZURE_DEVOPS_API_BASE_URL
|
||||
_resetAzureDevOpsRepoRefCache()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = OLD_ENV
|
||||
_resetAzureDevOpsRepoRefCache()
|
||||
})
|
||||
|
||||
it('resolves an Azure Repos 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 === '/acme/Project/_apis/git/repositories/repo') {
|
||||
sendJson(res, {
|
||||
id: 'repo-guid',
|
||||
webUrl: 'https://dev.azure.com/acme/Project/_git/repo'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests') {
|
||||
expect(url.searchParams.get('searchCriteria.sourceRefName')).toBe(
|
||||
'refs/heads/feature/azure'
|
||||
)
|
||||
sendJson(res, {
|
||||
value: [
|
||||
{
|
||||
pullRequestId: 31,
|
||||
title: 'Azure branch',
|
||||
status: 'active',
|
||||
creationDate: '2026-05-16T00:00:00Z',
|
||||
mergeStatus: 'succeeded',
|
||||
lastMergeSourceCommit: { commitId: 'abc123' }
|
||||
}
|
||||
]
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
url.pathname === '/acme/Project/_apis/git/repositories/repo-guid/pullRequests/31/statuses'
|
||||
) {
|
||||
sendJson(res, { value: [{ state: 'succeeded' }] })
|
||||
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-azure-review-'))
|
||||
try {
|
||||
const address = server.address()
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('expected TCP server address')
|
||||
}
|
||||
process.env.ORCA_AZURE_DEVOPS_API_BASE_URL = `http://127.0.0.1:${address.port}/acme/Project`
|
||||
|
||||
await execFileAsync('git', ['init'], { cwd: repoPath })
|
||||
await execFileAsync(
|
||||
'git',
|
||||
['remote', 'add', 'origin', 'https://dev.azure.com/acme/Project/_git/repo'],
|
||||
{ cwd: repoPath }
|
||||
)
|
||||
|
||||
await expect(
|
||||
getHostedReviewForBranch({ repoPath, branch: 'refs/heads/feature/azure' })
|
||||
).resolves.toEqual({
|
||||
provider: 'azure-devops',
|
||||
number: 31,
|
||||
title: 'Azure branch',
|
||||
state: 'open',
|
||||
url: 'https://dev.azure.com/acme/Project/_git/repo/pullrequest/31',
|
||||
status: 'success',
|
||||
updatedAt: '2026-05-16T00:00:00Z',
|
||||
mergeable: 'MERGEABLE',
|
||||
headSha: 'abc123'
|
||||
})
|
||||
|
||||
expect(seen.map((request) => request.pathname)).toEqual([
|
||||
'/acme/Project/_apis/git/repositories/repo',
|
||||
'/acme/Project/_apis/git/repositories/repo-guid/pullRequests',
|
||||
'/acme/Project/_apis/git/repositories/repo-guid/pullRequests/31/statuses'
|
||||
])
|
||||
expect(seen.every((request) => request.authorization === 'Basic OmxvY2FsLXBhdA==')).toBe(true)
|
||||
} finally {
|
||||
await rm(repoPath, { recursive: true, force: true })
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => (error ? reject(error) : resolve()))
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,7 @@ const {
|
||||
getRepoSlugMock,
|
||||
getProjectSlugMock,
|
||||
getBitbucketRepoSlugMock,
|
||||
getAzureDevOpsRepoSlugMock,
|
||||
getGiteaRepoSlugMock,
|
||||
getHostedReviewForBranchMock,
|
||||
ghExecFileAsyncMock,
|
||||
@@ -15,6 +16,7 @@ const {
|
||||
getRepoSlugMock: vi.fn(),
|
||||
getProjectSlugMock: vi.fn(),
|
||||
getBitbucketRepoSlugMock: vi.fn(),
|
||||
getAzureDevOpsRepoSlugMock: vi.fn(),
|
||||
getGiteaRepoSlugMock: vi.fn(),
|
||||
getHostedReviewForBranchMock: vi.fn(),
|
||||
ghExecFileAsyncMock: vi.fn(),
|
||||
@@ -35,6 +37,10 @@ vi.mock('../bitbucket/client', () => ({
|
||||
getBitbucketRepoSlug: getBitbucketRepoSlugMock
|
||||
}))
|
||||
|
||||
vi.mock('../azure-devops/client', () => ({
|
||||
getAzureDevOpsRepoSlug: getAzureDevOpsRepoSlugMock
|
||||
}))
|
||||
|
||||
vi.mock('../gitea/client', () => ({
|
||||
getGiteaRepoSlug: getGiteaRepoSlugMock
|
||||
}))
|
||||
@@ -56,22 +62,36 @@ vi.mock('./hosted-review', () => ({
|
||||
|
||||
import { createHostedReview, getHostedReviewCreationEligibility } from './hosted-review-creation'
|
||||
|
||||
function resetMocks(): void {
|
||||
for (const mock of [
|
||||
createGitHubPullRequestMock,
|
||||
getRepoSlugMock,
|
||||
getProjectSlugMock,
|
||||
getBitbucketRepoSlugMock,
|
||||
getAzureDevOpsRepoSlugMock,
|
||||
getGiteaRepoSlugMock,
|
||||
getHostedReviewForBranchMock,
|
||||
ghExecFileAsyncMock,
|
||||
gitExecFileAsyncMock,
|
||||
getUpstreamStatusMock
|
||||
]) {
|
||||
mock.mockReset()
|
||||
}
|
||||
}
|
||||
|
||||
function mockGitHubProvider(): void {
|
||||
getProjectSlugMock.mockResolvedValue(null)
|
||||
getRepoSlugMock.mockResolvedValue({ owner: 'acme', repo: 'orca' })
|
||||
getBitbucketRepoSlugMock.mockResolvedValue(null)
|
||||
getAzureDevOpsRepoSlugMock.mockResolvedValue(null)
|
||||
getGiteaRepoSlugMock.mockResolvedValue(null)
|
||||
}
|
||||
|
||||
describe('createHostedReview', () => {
|
||||
beforeEach(() => {
|
||||
createGitHubPullRequestMock.mockReset()
|
||||
getRepoSlugMock.mockReset()
|
||||
getProjectSlugMock.mockReset()
|
||||
getBitbucketRepoSlugMock.mockReset()
|
||||
getGiteaRepoSlugMock.mockReset()
|
||||
getHostedReviewForBranchMock.mockReset()
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
getUpstreamStatusMock.mockReset()
|
||||
resetMocks()
|
||||
|
||||
getProjectSlugMock.mockResolvedValue(null)
|
||||
getRepoSlugMock.mockResolvedValue({ owner: 'acme', repo: 'orca' })
|
||||
getBitbucketRepoSlugMock.mockResolvedValue(null)
|
||||
getGiteaRepoSlugMock.mockResolvedValue(null)
|
||||
mockGitHubProvider()
|
||||
getHostedReviewForBranchMock.mockResolvedValue(null)
|
||||
ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
|
||||
getUpstreamStatusMock.mockResolvedValue({
|
||||
@@ -198,20 +218,9 @@ describe('createHostedReview', () => {
|
||||
|
||||
describe('getHostedReviewCreationEligibility', () => {
|
||||
beforeEach(() => {
|
||||
createGitHubPullRequestMock.mockReset()
|
||||
getRepoSlugMock.mockReset()
|
||||
getProjectSlugMock.mockReset()
|
||||
getBitbucketRepoSlugMock.mockReset()
|
||||
getGiteaRepoSlugMock.mockReset()
|
||||
getHostedReviewForBranchMock.mockReset()
|
||||
ghExecFileAsyncMock.mockReset()
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
getUpstreamStatusMock.mockReset()
|
||||
resetMocks()
|
||||
|
||||
getProjectSlugMock.mockResolvedValue(null)
|
||||
getRepoSlugMock.mockResolvedValue({ owner: 'acme', repo: 'orca' })
|
||||
getBitbucketRepoSlugMock.mockResolvedValue(null)
|
||||
getGiteaRepoSlugMock.mockResolvedValue(null)
|
||||
mockGitHubProvider()
|
||||
getHostedReviewForBranchMock.mockResolvedValue(null)
|
||||
ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
|
||||
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'Feature title\n', stderr: '' })
|
||||
@@ -313,8 +322,7 @@ describe('getHostedReviewCreationEligibility', () => {
|
||||
).resolves.toMatchObject({
|
||||
provider: 'gitlab',
|
||||
canCreate: false,
|
||||
blockedReason: 'unsupported_provider',
|
||||
nextAction: null
|
||||
blockedReason: 'unsupported_provider'
|
||||
})
|
||||
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
normalizeHostedReviewBaseRef,
|
||||
normalizeHostedReviewHeadRef
|
||||
} from '../../shared/hosted-review-refs'
|
||||
import { getAzureDevOpsRepoSlug } from '../azure-devops/client'
|
||||
import { getBitbucketRepoSlug } from '../bitbucket/client'
|
||||
import { getGiteaRepoSlug } from '../gitea/client'
|
||||
import { createGitHubPullRequest, getRepoSlug } from '../github/client'
|
||||
@@ -44,6 +45,9 @@ async function detectHostedReviewProvider(repoPath: string): Promise<HostedRevie
|
||||
if (await getBitbucketRepoSlug(repoPath)) {
|
||||
return 'bitbucket'
|
||||
}
|
||||
if (await getAzureDevOpsRepoSlug(repoPath)) {
|
||||
return 'azure-devops'
|
||||
}
|
||||
if (await getGiteaRepoSlug(repoPath)) {
|
||||
return 'gitea'
|
||||
}
|
||||
@@ -234,6 +238,7 @@ export async function getHostedReviewCreationEligibility(
|
||||
linkedGitHubPR: args.linkedGitHubPR ?? null,
|
||||
linkedGitLabMR: args.linkedGitLabMR ?? null,
|
||||
linkedBitbucketPR: args.linkedBitbucketPR ?? null,
|
||||
linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null,
|
||||
linkedGiteaPR: args.linkedGiteaPR ?? null
|
||||
})
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ const {
|
||||
getPRForBranchMock,
|
||||
getBitbucketRepoSlugMock,
|
||||
getBitbucketPullRequestForBranchMock,
|
||||
getAzureDevOpsRepoSlugMock,
|
||||
getAzureDevOpsPullRequestForBranchMock,
|
||||
getGiteaRepoSlugMock,
|
||||
getGiteaPullRequestForBranchMock
|
||||
} = vi.hoisted(() => ({
|
||||
@@ -16,6 +18,8 @@ const {
|
||||
getPRForBranchMock: vi.fn(),
|
||||
getBitbucketRepoSlugMock: vi.fn(),
|
||||
getBitbucketPullRequestForBranchMock: vi.fn(),
|
||||
getAzureDevOpsRepoSlugMock: vi.fn(),
|
||||
getAzureDevOpsPullRequestForBranchMock: vi.fn(),
|
||||
getGiteaRepoSlugMock: vi.fn(),
|
||||
getGiteaPullRequestForBranchMock: vi.fn()
|
||||
}))
|
||||
@@ -37,6 +41,12 @@ vi.mock('../bitbucket/client', () => ({
|
||||
getBitbucketPullRequest: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../azure-devops/client', () => ({
|
||||
getAzureDevOpsRepoSlug: getAzureDevOpsRepoSlugMock,
|
||||
getAzureDevOpsPullRequestForBranch: getAzureDevOpsPullRequestForBranchMock,
|
||||
getAzureDevOpsPullRequest: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../gitea/client', () => ({
|
||||
getGiteaRepoSlug: getGiteaRepoSlugMock,
|
||||
getGiteaPullRequestForBranch: getGiteaPullRequestForBranchMock,
|
||||
@@ -53,6 +63,8 @@ describe('getHostedReviewForBranch', () => {
|
||||
getPRForBranchMock.mockReset()
|
||||
getBitbucketRepoSlugMock.mockReset()
|
||||
getBitbucketPullRequestForBranchMock.mockReset()
|
||||
getAzureDevOpsRepoSlugMock.mockReset()
|
||||
getAzureDevOpsPullRequestForBranchMock.mockReset()
|
||||
getGiteaRepoSlugMock.mockReset()
|
||||
getGiteaPullRequestForBranchMock.mockReset()
|
||||
})
|
||||
@@ -154,6 +166,7 @@ describe('getHostedReviewForBranch', () => {
|
||||
getProjectSlugMock.mockResolvedValue(null)
|
||||
getRepoSlugMock.mockResolvedValue(null)
|
||||
getBitbucketRepoSlugMock.mockResolvedValue(null)
|
||||
getAzureDevOpsRepoSlugMock.mockResolvedValue(null)
|
||||
getGiteaRepoSlugMock.mockResolvedValue({
|
||||
host: 'git.example.com',
|
||||
owner: 'team',
|
||||
@@ -189,4 +202,50 @@ describe('getHostedReviewForBranch', () => {
|
||||
})
|
||||
expect(getGiteaPullRequestForBranchMock).toHaveBeenCalledWith('/repo', 'feature/gitea', 14)
|
||||
})
|
||||
|
||||
it('falls through to Azure DevOps before Gitea when origin is an Azure Repos remote', async () => {
|
||||
getProjectSlugMock.mockResolvedValue(null)
|
||||
getRepoSlugMock.mockResolvedValue(null)
|
||||
getBitbucketRepoSlugMock.mockResolvedValue(null)
|
||||
getAzureDevOpsRepoSlugMock.mockResolvedValue({
|
||||
host: 'dev.azure.com',
|
||||
organization: 'team',
|
||||
project: 'Project',
|
||||
repository: 'orca'
|
||||
})
|
||||
getAzureDevOpsPullRequestForBranchMock.mockResolvedValue({
|
||||
number: 21,
|
||||
title: 'Azure branch',
|
||||
state: 'open',
|
||||
url: 'https://dev.azure.com/team/Project/_git/orca/pullrequest/21',
|
||||
status: 'success',
|
||||
updatedAt: '2026-05-16T00:00:00.000Z',
|
||||
mergeable: 'MERGEABLE',
|
||||
headSha: 'abc123'
|
||||
})
|
||||
|
||||
await expect(
|
||||
getHostedReviewForBranch({
|
||||
repoPath: '/repo',
|
||||
branch: 'feature/azure',
|
||||
linkedAzureDevOpsPR: 21
|
||||
})
|
||||
).resolves.toEqual({
|
||||
provider: 'azure-devops',
|
||||
number: 21,
|
||||
title: 'Azure branch',
|
||||
state: 'open',
|
||||
url: 'https://dev.azure.com/team/Project/_git/orca/pullrequest/21',
|
||||
status: 'success',
|
||||
updatedAt: '2026-05-16T00:00:00.000Z',
|
||||
mergeable: 'MERGEABLE',
|
||||
headSha: 'abc123'
|
||||
})
|
||||
expect(getAzureDevOpsPullRequestForBranchMock).toHaveBeenCalledWith(
|
||||
'/repo',
|
||||
'feature/azure',
|
||||
21
|
||||
)
|
||||
expect(getGiteaRepoSlugMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { HostedReviewInfo } from '../../shared/hosted-review'
|
||||
import type { MRInfo, PRInfo } from '../../shared/types'
|
||||
import {
|
||||
getAzureDevOpsPullRequest,
|
||||
getAzureDevOpsPullRequestForBranch,
|
||||
getAzureDevOpsRepoSlug
|
||||
} from '../azure-devops/client'
|
||||
import type { AzureDevOpsPullRequestInfo } from '../azure-devops/pull-request-mappers'
|
||||
import {
|
||||
getBitbucketPullRequest,
|
||||
getBitbucketPullRequestForBranch,
|
||||
@@ -66,6 +72,20 @@ function mapBitbucketReview(pr: BitbucketPullRequestInfo): HostedReviewInfo {
|
||||
}
|
||||
}
|
||||
|
||||
function mapAzureDevOpsReview(pr: AzureDevOpsPullRequestInfo): HostedReviewInfo {
|
||||
return {
|
||||
provider: 'azure-devops',
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
state: pr.state,
|
||||
url: pr.url,
|
||||
status: pr.status,
|
||||
updatedAt: pr.updatedAt,
|
||||
mergeable: pr.mergeable,
|
||||
...(pr.headSha ? { headSha: pr.headSha } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function mapGiteaReview(pr: GiteaPullRequestInfo): HostedReviewInfo {
|
||||
return {
|
||||
provider: 'gitea',
|
||||
@@ -87,6 +107,7 @@ export async function getHostedReviewForBranch(input: {
|
||||
linkedGitHubPR?: number | null
|
||||
linkedGitLabMR?: number | null
|
||||
linkedBitbucketPR?: number | null
|
||||
linkedAzureDevOpsPR?: number | null
|
||||
linkedGiteaPR?: number | null
|
||||
}): Promise<HostedReviewInfo | null> {
|
||||
const branchName = input.branch.replace(/^refs\/heads\//, '')
|
||||
@@ -95,6 +116,7 @@ export async function getHostedReviewForBranch(input: {
|
||||
input.linkedGitHubPR == null &&
|
||||
input.linkedGitLabMR == null &&
|
||||
input.linkedBitbucketPR == null &&
|
||||
input.linkedAzureDevOpsPR == null &&
|
||||
input.linkedGiteaPR == null
|
||||
) {
|
||||
return null
|
||||
@@ -132,6 +154,16 @@ export async function getHostedReviewForBranch(input: {
|
||||
return pr ? mapBitbucketReview(pr) : null
|
||||
}
|
||||
|
||||
const azureDevOpsRepo = await getAzureDevOpsRepoSlug(input.repoPath)
|
||||
if (azureDevOpsRepo) {
|
||||
const pr = await getAzureDevOpsPullRequestForBranch(
|
||||
input.repoPath,
|
||||
branchName,
|
||||
input.linkedAzureDevOpsPR ?? null
|
||||
)
|
||||
return pr ? mapAzureDevOpsReview(pr) : null
|
||||
}
|
||||
|
||||
const giteaRepo = await getGiteaRepoSlug(input.repoPath)
|
||||
if (giteaRepo) {
|
||||
const pr = await getGiteaPullRequestForBranch(
|
||||
@@ -147,7 +179,7 @@ export async function getHostedReviewForBranch(input: {
|
||||
|
||||
export async function getHostedReviewByNumber(input: {
|
||||
repoPath: string
|
||||
provider: 'github' | 'gitlab' | 'bitbucket' | 'gitea'
|
||||
provider: 'github' | 'gitlab' | 'bitbucket' | 'azure-devops' | 'gitea'
|
||||
number: number
|
||||
}): Promise<HostedReviewInfo | null> {
|
||||
if (input.provider === 'gitlab') {
|
||||
@@ -158,6 +190,10 @@ export async function getHostedReviewByNumber(input: {
|
||||
const pr = await getBitbucketPullRequest(input.repoPath, input.number)
|
||||
return pr ? mapBitbucketReview(pr) : null
|
||||
}
|
||||
if (input.provider === 'azure-devops') {
|
||||
const pr = await getAzureDevOpsPullRequest(input.repoPath, input.number)
|
||||
return pr ? mapAzureDevOpsReview(pr) : null
|
||||
}
|
||||
if (input.provider === 'gitea') {
|
||||
const pr = await getGiteaPullRequest(input.repoPath, input.number)
|
||||
return pr ? mapGiteaReview(pr) : null
|
||||
|
||||
@@ -342,6 +342,13 @@ export type PreflightStatus = {
|
||||
* include it. Consumers gate on `glab?.installed` / `authenticated`. */
|
||||
glab?: { installed: boolean; authenticated: boolean }
|
||||
bitbucket?: { configured: boolean; authenticated: boolean; account: string | null }
|
||||
azureDevOps?: {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
account: string | null
|
||||
baseUrl: string | null
|
||||
tokenConfigured: boolean
|
||||
}
|
||||
gitea?: {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
|
||||
@@ -1146,6 +1146,13 @@ const api = {
|
||||
gh: { installed: boolean; authenticated: boolean }
|
||||
glab?: { installed: boolean; authenticated: boolean }
|
||||
bitbucket?: { configured: boolean; authenticated: boolean; account: string | null }
|
||||
azureDevOps?: {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
account: string | null
|
||||
baseUrl: string | null
|
||||
tokenConfigured: boolean
|
||||
}
|
||||
gitea?: {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
|
||||
@@ -53,6 +53,11 @@ export const INTEGRATIONS_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [
|
||||
description: 'Bitbucket Cloud authentication via API token environment variables.',
|
||||
keywords: ['bitbucket', 'integration', 'pull request', 'api token']
|
||||
},
|
||||
{
|
||||
title: 'Azure DevOps Integration',
|
||||
description: 'Azure DevOps Repos authentication via token environment variables.',
|
||||
keywords: ['azure devops', 'azure repos', 'ado', 'integration', 'pull request', 'api token']
|
||||
},
|
||||
{
|
||||
title: 'Gitea Integration',
|
||||
description: 'Gitea authentication via API token environment variables.',
|
||||
@@ -70,8 +75,17 @@ type GhStatus = 'checking' | 'connected' | 'not-installed' | 'not-authenticated'
|
||||
// modes (probe in-flight / installed-but-unauth / missing entirely).
|
||||
type GlabStatus = GhStatus
|
||||
type BitbucketStatus = 'checking' | 'connected' | 'not-configured' | 'not-authenticated'
|
||||
type AzureDevOpsStatus = 'checking' | 'configured' | 'not-configured' | 'not-authenticated'
|
||||
type GiteaStatus = 'checking' | 'configured' | 'not-configured' | 'not-authenticated'
|
||||
|
||||
type TokenApiPreflightStatus = {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
account: string | null
|
||||
baseUrl: string | null
|
||||
tokenConfigured: boolean
|
||||
}
|
||||
|
||||
type GiteaPreflightStatus = {
|
||||
configured: boolean
|
||||
authenticated: boolean
|
||||
@@ -80,6 +94,21 @@ type GiteaPreflightStatus = {
|
||||
tokenConfigured: boolean
|
||||
}
|
||||
|
||||
function tokenApiStatusFromPreflight(
|
||||
status: TokenApiPreflightStatus | undefined
|
||||
): AzureDevOpsStatus {
|
||||
if (!status?.configured) {
|
||||
return 'not-configured'
|
||||
}
|
||||
if (status.tokenConfigured && !status.baseUrl) {
|
||||
return 'configured'
|
||||
}
|
||||
if (status.tokenConfigured && !status.authenticated) {
|
||||
return 'not-authenticated'
|
||||
}
|
||||
return 'configured'
|
||||
}
|
||||
|
||||
function giteaStatusFromPreflight(status: GiteaPreflightStatus | undefined): GiteaStatus {
|
||||
if (!status?.configured) {
|
||||
return 'not-configured'
|
||||
@@ -103,6 +132,9 @@ export function IntegrationsPane(): React.JSX.Element {
|
||||
const [glabStatus, setGlabStatus] = useState<GlabStatus>('checking')
|
||||
const [bitbucketStatus, setBitbucketStatus] = useState<BitbucketStatus>('checking')
|
||||
const [bitbucketAccount, setBitbucketAccount] = useState<string | null>(null)
|
||||
const [azureDevOpsStatus, setAzureDevOpsStatus] = useState<AzureDevOpsStatus>('checking')
|
||||
const [azureDevOpsAccount, setAzureDevOpsAccount] = useState<string | null>(null)
|
||||
const [azureDevOpsBaseUrl, setAzureDevOpsBaseUrl] = useState<string | null>(null)
|
||||
const [giteaStatus, setGiteaStatus] = useState<GiteaStatus>('checking')
|
||||
const [giteaAccount, setGiteaAccount] = useState<string | null>(null)
|
||||
const [giteaBaseUrl, setGiteaBaseUrl] = useState<string | null>(null)
|
||||
@@ -147,6 +179,10 @@ export function IntegrationsPane(): React.JSX.Element {
|
||||
} else {
|
||||
setBitbucketStatus('connected')
|
||||
}
|
||||
const azureDevOps = status.azureDevOps
|
||||
setAzureDevOpsAccount(azureDevOps?.account ?? null)
|
||||
setAzureDevOpsBaseUrl(azureDevOps?.baseUrl ?? null)
|
||||
setAzureDevOpsStatus(tokenApiStatusFromPreflight(azureDevOps))
|
||||
const gitea = status.gitea
|
||||
setGiteaAccount(gitea?.account ?? null)
|
||||
setGiteaBaseUrl(gitea?.baseUrl ?? null)
|
||||
@@ -253,6 +289,16 @@ export function IntegrationsPane(): React.JSX.Element {
|
||||
})
|
||||
}
|
||||
|
||||
const handleRefreshAzureDevOps = (): void => {
|
||||
setAzureDevOpsStatus('checking')
|
||||
void window.api.preflight.check({ force: true }).then((status) => {
|
||||
const azureDevOps = status.azureDevOps
|
||||
setAzureDevOpsAccount(azureDevOps?.account ?? null)
|
||||
setAzureDevOpsBaseUrl(azureDevOps?.baseUrl ?? null)
|
||||
setAzureDevOpsStatus(tokenApiStatusFromPreflight(azureDevOps))
|
||||
})
|
||||
}
|
||||
|
||||
const handleRefreshGitea = (): void => {
|
||||
setGiteaStatus('checking')
|
||||
void window.api.preflight.check({ force: true }).then((status) => {
|
||||
@@ -502,6 +548,93 @@ export function IntegrationsPane(): React.JSX.Element {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Azure DevOps */}
|
||||
<div className="rounded-md border border-border/50 bg-muted/30 px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<GitPullRequestArrow className="size-5 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0 flex-1 space-y-0.5">
|
||||
<p className="text-sm font-medium">Azure DevOps</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{azureDevOpsStatus === 'configured'
|
||||
? azureDevOpsAccount
|
||||
? `${azureDevOpsAccount} · Pull requests and build statuses`
|
||||
: azureDevOpsBaseUrl
|
||||
? `${azureDevOpsBaseUrl} · Pull requests and build statuses`
|
||||
: 'Pull requests and build statuses for detected Azure Repos'
|
||||
: 'Pull requests and build statuses via Azure DevOps REST API tokens.'}
|
||||
</p>
|
||||
</div>
|
||||
{azureDevOpsStatus === 'checking' ? (
|
||||
<LoaderCircle className="size-4 shrink-0 animate-spin text-muted-foreground" />
|
||||
) : azureDevOpsStatus === 'configured' ? (
|
||||
<span className="shrink-0 rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2.5 py-1 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">
|
||||
{azureDevOpsAccount ? 'Connected' : 'Configured'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="shrink-0 rounded-full border border-amber-500/30 bg-amber-500/10 px-2.5 py-1 text-[11px] font-medium text-amber-700 dark:text-amber-300">
|
||||
{azureDevOpsStatus === 'not-configured' ? 'Not configured' : 'Auth failed'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{azureDevOpsStatus !== 'checking' && azureDevOpsStatus !== 'configured' && (
|
||||
<div className="mt-3 rounded-md border border-border/30 bg-background/50 px-3 py-2.5 space-y-2">
|
||||
{azureDevOpsStatus === 'not-configured' ? (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Set <span className="font-mono text-[11px]">ORCA_AZURE_DEVOPS_TOKEN</span>, or set{' '}
|
||||
<span className="font-mono text-[11px]">ORCA_AZURE_DEVOPS_ACCESS_TOKEN</span>. Set{' '}
|
||||
<span className="font-mono text-[11px]">ORCA_AZURE_DEVOPS_API_BASE_URL</span> only
|
||||
when Orca cannot derive the API base URL from the git remote.
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
window.api.shell.openUrl(
|
||||
'https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate'
|
||||
)
|
||||
}
|
||||
>
|
||||
<ExternalLink className="size-3.5 mr-1.5" />
|
||||
Learn more
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={handleRefreshAzureDevOps}>
|
||||
Re-check
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Azure DevOps credentials are configured but could not authenticate. Check the
|
||||
token, API base URL, and repository permissions, then restart Orca if environment
|
||||
variables changed.
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
window.api.shell.openUrl(
|
||||
'https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-requests/get-pull-requests'
|
||||
)
|
||||
}
|
||||
>
|
||||
<ExternalLink className="size-3.5 mr-1.5" />
|
||||
Learn more
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={handleRefreshAzureDevOps}>
|
||||
Re-check
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Gitea */}
|
||||
<div className="rounded-md border border-border/50 bg-muted/30 px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
@@ -109,6 +109,9 @@ function getProviderName(review: WorktreeCardPrDisplay): string {
|
||||
if (review.provider === 'bitbucket') {
|
||||
return 'Bitbucket'
|
||||
}
|
||||
if (review.provider === 'azure-devops') {
|
||||
return 'Azure DevOps'
|
||||
}
|
||||
if (review.provider === 'gitea') {
|
||||
return 'Gitea'
|
||||
}
|
||||
|
||||
@@ -80,6 +80,7 @@ describe('hosted review slice', () => {
|
||||
linkedGitHubPR: null,
|
||||
linkedGitLabMR: 5,
|
||||
linkedBitbucketPR: null,
|
||||
linkedAzureDevOpsPR: null,
|
||||
linkedGiteaPR: null
|
||||
})
|
||||
})
|
||||
@@ -107,6 +108,7 @@ describe('hosted review slice', () => {
|
||||
linkedGitHubPR: 12,
|
||||
linkedGitLabMR: null,
|
||||
linkedBitbucketPR: null,
|
||||
linkedAzureDevOpsPR: null,
|
||||
linkedGiteaPR: null
|
||||
},
|
||||
{ timeoutMs: 30_000 }
|
||||
@@ -128,6 +130,7 @@ describe('hosted review slice', () => {
|
||||
linkedGitHubPR: null,
|
||||
linkedGitLabMR: 33,
|
||||
linkedBitbucketPR: null,
|
||||
linkedAzureDevOpsPR: null,
|
||||
linkedGiteaPR: null
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,6 +16,7 @@ type LinkedReviewHints = {
|
||||
linkedGitHubPR?: number | null
|
||||
linkedGitLabMR?: number | null
|
||||
linkedBitbucketPR?: number | null
|
||||
linkedAzureDevOpsPR?: number | null
|
||||
linkedGiteaPR?: number | null
|
||||
}
|
||||
|
||||
@@ -43,6 +44,7 @@ function linkedReviewHintKey(options?: LinkedReviewHints): string {
|
||||
['github', options?.linkedGitHubPR ?? null],
|
||||
['gitlab', options?.linkedGitLabMR ?? null],
|
||||
['bitbucket', options?.linkedBitbucketPR ?? null],
|
||||
['azure-devops', options?.linkedAzureDevOpsPR ?? null],
|
||||
['gitea', options?.linkedGiteaPR ?? null]
|
||||
] as const
|
||||
return hints
|
||||
@@ -89,6 +91,7 @@ export type HostedReviewSlice = {
|
||||
linkedGitHubPR?: number | null
|
||||
linkedGitLabMR?: number | null
|
||||
linkedBitbucketPR?: number | null
|
||||
linkedAzureDevOpsPR?: number | null
|
||||
linkedGiteaPR?: number | null
|
||||
}
|
||||
) => Promise<HostedReviewInfo | null>
|
||||
@@ -101,6 +104,7 @@ type RefreshHostedReviewCardArgs = {
|
||||
linkedGitHubPR?: number | null
|
||||
linkedGitLabMR?: number | null
|
||||
linkedBitbucketPR?: number | null
|
||||
linkedAzureDevOpsPR?: number | null
|
||||
linkedGiteaPR?: number | null
|
||||
}
|
||||
|
||||
@@ -114,6 +118,7 @@ export function refreshHostedReviewCard(
|
||||
linkedGitHubPR: args.linkedGitHubPR ?? null,
|
||||
linkedGitLabMR: args.linkedGitLabMR ?? null,
|
||||
linkedBitbucketPR: args.linkedBitbucketPR ?? null,
|
||||
linkedAzureDevOpsPR: args.linkedAzureDevOpsPR ?? null,
|
||||
linkedGiteaPR: args.linkedGiteaPR ?? null
|
||||
})
|
||||
}
|
||||
@@ -195,6 +200,7 @@ export const createHostedReviewSlice: StateCreator<AppState, [], [], HostedRevie
|
||||
linkedGitHubPR: options?.linkedGitHubPR ?? null,
|
||||
linkedGitLabMR: options?.linkedGitLabMR ?? null,
|
||||
linkedBitbucketPR: options?.linkedBitbucketPR ?? null,
|
||||
linkedAzureDevOpsPR: options?.linkedAzureDevOpsPR ?? null,
|
||||
linkedGiteaPR: options?.linkedGiteaPR ?? null
|
||||
}
|
||||
const review =
|
||||
|
||||
@@ -772,7 +772,21 @@ function createPreflightApi(): NonNullable<Partial<PreloadApi>['preflight']> {
|
||||
git: { installed: false },
|
||||
gh: { installed: false, authenticated: false },
|
||||
glab: { installed: false, authenticated: false },
|
||||
bitbucket: { configured: false, authenticated: false, account: null }
|
||||
bitbucket: { configured: false, authenticated: false, account: null },
|
||||
azureDevOps: {
|
||||
configured: false,
|
||||
authenticated: false,
|
||||
account: null,
|
||||
baseUrl: null,
|
||||
tokenConfigured: false
|
||||
},
|
||||
gitea: {
|
||||
configured: false,
|
||||
authenticated: false,
|
||||
account: null,
|
||||
baseUrl: null,
|
||||
tokenConfigured: false
|
||||
}
|
||||
}
|
||||
const fallbackRefreshAgents: RefreshAgentsResult = {
|
||||
agents: [],
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { CheckStatus, PRConflictSummary, PRMergeableState } from './types'
|
||||
|
||||
export type HostedReviewProvider = 'github' | 'gitlab' | 'bitbucket' | 'gitea' | 'unsupported'
|
||||
export type HostedReviewProvider =
|
||||
| 'github'
|
||||
| 'gitlab'
|
||||
| 'bitbucket'
|
||||
| 'azure-devops'
|
||||
| 'gitea'
|
||||
| 'unsupported'
|
||||
|
||||
export type HostedReviewState = 'open' | 'closed' | 'merged' | 'draft'
|
||||
|
||||
@@ -24,6 +30,7 @@ export type HostedReviewForBranchArgs = {
|
||||
linkedGitHubPR?: number | null
|
||||
linkedGitLabMR?: number | null
|
||||
linkedBitbucketPR?: number | null
|
||||
linkedAzureDevOpsPR?: number | null
|
||||
linkedGiteaPR?: number | null
|
||||
}
|
||||
|
||||
@@ -111,6 +118,7 @@ export type HostedReviewCreationEligibilityArgs = {
|
||||
linkedGitHubPR?: number | null
|
||||
linkedGitLabMR?: number | null
|
||||
linkedBitbucketPR?: number | null
|
||||
linkedAzureDevOpsPR?: number | null
|
||||
linkedGiteaPR?: number | null
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user