Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
434 changes: 434 additions & 0 deletions config/scripts/github-opened-issue-repository.test.ts

Large diffs are not rendered by default.

204 changes: 204 additions & 0 deletions config/scripts/github-pr-assignee-repository.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import type * as GhUtils from '../../src/main/github/gh-utils'
import type * as ReactModule from 'react'
import type { GitHubOwnerRepo } from '../../src/shared/github/pull-request-types'
import type { GitHubWorkItem } from '../../src/shared/github/work-item-types'
import type { GitHubIssueUpdate } from '../../src/shared/issue-mutation-types'

const fixture = vi.hoisted(() => {
const state: {
callbacks: unknown[]
mutation: Promise<unknown> | null
gh: ReturnType<typeof vi.fn>
apiUpdate: ReturnType<typeof vi.fn>
patch: ReturnType<typeof vi.fn>
preference: 'origin' | 'upstream'
localGitOptions: { wslDistro?: string }
requests: { args: string[]; host?: string; cwd?: string; wslDistro?: string }[]
} = {
callbacks: [],
mutation: null,
gh: vi.fn(),
apiUpdate: vi.fn(),
patch: vi.fn(),
preference: 'origin',
localGitOptions: {},
requests: []
}
return state
})

vi.mock('react', async (original) => ({
...(await original<typeof ReactModule>()),
useState: (value: unknown) => [typeof value === 'function' ? value() : value, vi.fn()],
useMemo: <T>(getValue: () => T) => getValue(),
useCallback: <T>(callback: T) => {
fixture.callbacks.push(callback)
return callback
}
}))
vi.mock('zustand/react/shallow', () => ({ useShallow: <T>(selector: T) => selector }))
vi.mock('@/store', () => ({
useAppStore: Object.assign(
(selector: (state: unknown) => unknown) =>
selector({
patchWorkItem: fixture.patch,
patchProjectRowContent: fixture.patch,
repos: [],
settings: {}
}),
{ getState: () => ({ recordFeatureInteraction: vi.fn() }) }
)
}))
vi.mock('@/lib/repo-runtime-owner', () => ({
getSettingsForRepoRuntimeOwner: () => ({ activeRuntimeEnvironmentId: null })
}))
vi.mock('@/components/ui/popover', () => ({
Popover: vi.fn(),
PopoverContent: vi.fn(),
PopoverTrigger: vi.fn()
}))
vi.mock('@/hooks/useIssueMetadata', () => ({
useRepoAssignees: () => ({ data: [], loading: false, error: null }),
useImmediateMutation: () => ({
isPending: () => false,
run: (_key: string, spec: { mutate: () => Promise<unknown> }) => {
fixture.mutation = spec.mutate()
}
})
}))
vi.mock('@/hooks/useGitHubSlugMetadata', () => ({
useRepoAssigneesBySlug: () => ({
data: [{ login: 'octo', name: null, avatarUrl: '' }],
loading: false,
error: null
})
}))
vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback }))
vi.mock('@/components/github/work-item-state-presentation', () => ({ ReviewerAvatar: vi.fn() }))
vi.mock('../../src/main/github/gh-utils', async (original) => ({
...(await original<typeof GhUtils>()),
ghExecFileAsync: fixture.gh,
acquire: vi.fn(),
release: vi.fn(),
getOwnerRepoForRemote: async (_path: string, remote: string) => ({
owner: remote === 'upstream' ? 'upstream-owner' : 'fork-owner',
repo: 'widgets'
})
}))
vi.mock('../../src/main/git/remote-name-listing', () => ({
shouldProbeGitRemote: async () => true
}))

import { PRAssigneesPanel } from '../../src/renderer/src/components/github/PRAssigneesPanel'
import { updateIssue } from '../../src/main/github/issue-update'
import { _resetOriginGitHubApiRepositoryCache } from '../../src/main/github/github-api-repository'

const repoPath = join(tmpdir(), 'orca-pr-assignee-repository-fixture')

beforeEach(() => {
fixture.callbacks = []
fixture.mutation = null
fixture.requests = []
fixture.localGitOptions = {}
fixture.gh.mockReset()
fixture.gh.mockImplementation(
async (
args: string[],
options: {
host?: string
cwd?: string
wslDistro?: string
}
) => {
fixture.requests.push({
args,
host: options.host,
cwd: options.cwd,
wslDistro: options.wslDistro
})
return { stdout: '', stderr: '' }
}
)
_resetOriginGitHubApiRepositoryCache()
fixture.apiUpdate = vi.fn(
(args: {
repoPath: string
number: number
updates: GitHubIssueUpdate
ownerRepo?: GitHubOwnerRepo
}) =>
updateIssue(
args.repoPath,
args.number,
args.updates,
null,
fixture.localGitOptions,
fixture.preference,
args.ownerRepo
)
)
vi.stubGlobal('window', { api: { gh: { updateIssue: fixture.apiUpdate } } })
})

afterEach(() => vi.unstubAllGlobals())

it.each([
{ owner: 'upstream-owner', preference: 'origin', assigned: false, legacy: false },
{ owner: 'upstream-owner', preference: 'origin', assigned: true, legacy: false },
{ owner: 'fork-owner', preference: 'upstream', assigned: false, legacy: false },
{ owner: 'fork-owner', preference: 'upstream', assigned: true, legacy: false },
{ owner: 'upstream-owner', preference: 'origin', assigned: false, legacy: true }
] as const)(
'keeps $owner PR assignees under $preference (remove=$assigned, legacy=$legacy)',
async ({ owner, preference, assigned, legacy }) => {
fixture.preference = preference
fixture.localGitOptions = owner === 'fork-owner' ? { wslDistro: 'Ubuntu' } : {}
const item: GitHubWorkItem = {
id: 'pr:5',
type: 'pr',
number: 5,
title: 'Opened PR',
state: 'open',
url: `https://github.com/${owner}/widgets/pull/5`,
prRepo: legacy ? undefined : { owner, repo: 'widgets', host: 'github.com' },
labels: [],
updatedAt: '',
author: null,
repoId: 'repo-1',
assignees: assigned ? [{ login: 'octo', name: null, avatarUrl: '' }] : []
}
PRAssigneesPanel({ item, repoPath, projectOrigin: undefined, onMutated: vi.fn() })
const toggleAssignee = fixture.callbacks.at(-1)
if (typeof toggleAssignee !== 'function') {
throw new Error('PR panel did not create an assignee handler')
}
toggleAssignee('octo')
await fixture.mutation
expect(fixture.requests).toEqual([
{
args: [
'issue',
'edit',
'5',
'--repo',
`${owner}/widgets`,
assigned ? '--remove-assignee' : '--add-assignee',
'octo'
],
host: 'github.com',
cwd: repoPath,
wslDistro: fixture.localGitOptions.wslDistro
}
])
expect(fixture.apiUpdate).toHaveBeenCalledWith(
expect.objectContaining({
repoPath,
repoId: item.repoId,
ownerRepo: { owner, repo: 'widgets', host: 'github.com' }
})
)
}
)
6 changes: 5 additions & 1 deletion src/main/github/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ export {
type PullRequestPushTarget
} from './client/lookup/pull-request-push-target'
export { getRepoSlug, getRepoUpstream } from './client/fetch/repo-slug-upstream'
export { getWorkItem, getWorkItemByOwnerRepo } from './client/fetch/get-work-item'
export {
getWorkItem,
getWorkItemByOwnerRepo,
getWorkItemWithRepository
} from './client/fetch/get-work-item'
export { listWorkItems } from './client/list/list-work-items'
export { mergePR } from './client/merge/merge-pr'
export { removePRReviewers, requestPRReviewers } from './client/update/pr-reviewers'
Expand Down
69 changes: 51 additions & 18 deletions src/main/github/client/fetch/get-work-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,30 @@ export async function getWorkItem(
localGitOptions: LocalGitExecOptions = {},
preference?: IssueSourcePreference
): Promise<MainWorkItem | null> {
const { item } = await getWorkItemWithRepository(
repoPath,
number,
type,
connectionId,
localGitOptions,
preference
)
return item
}

export type WorkItemRepositoryLookup = {
item: MainWorkItem | null
repository: GitHubApiRepository | null
}

export async function getWorkItemWithRepository(
repoPath: string,
number: number,
type?: 'issue' | 'pr',
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {},
preference?: IssueSourcePreference
): Promise<WorkItemRepositoryLookup> {
await acquire()
try {
// Why: listWorkItems uses resolveIssueGitHubApiRepositorySource; open-by-number
Expand All @@ -35,18 +59,24 @@ export async function getWorkItem(
// Why: explicit origin with no origin identity must not bare-lookup ambient gh
// (same fail-closed rule as origin-pinned PR candidate resolution).
if (!source && preference === 'origin') {
return null
return { item: null, repository: null }
}
return {
item: await fetchIssueWorkItem(repoPath, source, number, connectionId, localGitOptions),
repository: source
}
return await fetchIssueWorkItem(repoPath, source, number, connectionId, localGitOptions)
}
if (type === 'pr') {
return await fetchPullRequestWorkItemFromCandidates(
repoPath,
number,
connectionId,
localGitOptions,
preference
)
return {
item: await fetchPullRequestWorkItemFromCandidates(
repoPath,
number,
connectionId,
localGitOptions,
preference
),
repository: null
}
}

try {
Expand All @@ -65,7 +95,7 @@ export async function getWorkItem(
localGitOptions
)
if (issue) {
return issue
return { item: issue, repository: source }
}
}
} catch (err) {
Expand All @@ -75,15 +105,18 @@ export async function getWorkItem(
throw err
}
}
return await fetchPullRequestWorkItemFromCandidates(
repoPath,
number,
connectionId,
localGitOptions,
preference
)
return {
item: await fetchPullRequestWorkItemFromCandidates(
repoPath,
number,
connectionId,
localGitOptions,
preference
),
repository: null
}
} catch {
return null
return { item: null, repository: null }
} finally {
release()
}
Expand Down
21 changes: 21 additions & 0 deletions src/main/github/github-api-repository-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,25 @@ describe('isValidGitHubApiRepository', () => {
expect(isValidGitHubApiRepository({ owner: 'acme', repo: '..' })).toBe(false)
expect(isValidGitHubApiRepository({ owner: 'acme', repo: 'a/b' })).toBe(false)
})

it.each([42, false, null, {}])('rejects a non-string repository host: %j', (host) => {
expect(isValidGitHubApiRepository({ owner: 'acme', repo: 'orca', host })).toBe(false)
})

it.each([undefined, 'github.com', 'github.enterprise.test:8443'])(
'accepts supported legacy or explicit repository host types: %j',
(host) => {
expect(isValidGitHubApiRepository({ owner: 'acme', repo: 'orca', host })).toBe(true)
}
)

it.each([
null,
'acme/orca',
{ owner: 42, repo: 'orca' },
{ owner: 'acme', repo: 42 },
{ owner: 'acme' }
])('rejects malformed runtime repository identities: %j', (repository) => {
expect(isValidGitHubApiRepository(repository)).toBe(false)
})
})
15 changes: 14 additions & 1 deletion src/main/github/github-api-repository-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,21 @@ export type GitHubApiRepositoryResolution =
const OWNER_SLUG_RE = GITHUB_OWNER_SLUG_RE
const REPOSITORY_SLUG_RE = /^[A-Za-z0-9._-]+$/

export function isValidGitHubApiRepository(repository: GitHubOwnerRepo): boolean {
export function isValidGitHubApiRepository(repository: unknown): repository is GitHubOwnerRepo {
if (
!repository ||
typeof repository !== 'object' ||
!('owner' in repository) ||
!('repo' in repository)
) {
return false
}
return (
typeof repository.owner === 'string' &&
typeof repository.repo === 'string' &&
(!('host' in repository) ||
repository.host === undefined ||
typeof repository.host === 'string') &&
OWNER_SLUG_RE.test(repository.owner) &&
REPOSITORY_SLUG_RE.test(repository.repo) &&
repository.repo !== '.' &&
Expand Down
Loading
Loading