opencode-github-pr 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +331 -2
- package/demo/demo.gif +0 -0
- package/demo/fixtures.ts +158 -0
- package/package.json +56 -4
- package/plugins/app/DashboardView.tsx +290 -0
- package/plugins/app/PRRow.tsx +209 -0
- package/plugins/app/actions.tsx +25 -0
- package/plugins/app/config.ts +85 -0
- package/plugins/app/theme.ts +62 -0
- package/plugins/app/usePRData.ts +193 -0
- package/plugins/domain/format.ts +38 -0
- package/plugins/domain/login.ts +33 -0
- package/plugins/domain/messages.ts +161 -0
- package/plugins/domain/pr-filters.ts +40 -0
- package/plugins/domain/pr-links.ts +12 -0
- package/plugins/domain/pr-status.ts +127 -0
- package/plugins/domain/types.ts +77 -0
- package/plugins/infra/git.ts +156 -0
- package/plugins/infra/github-enterprise.ts +31 -0
- package/plugins/infra/loader.ts +123 -0
- package/plugins/infra/mappers.ts +117 -0
- package/plugins/infra/octokit.ts +115 -0
- package/plugins/infra/queries.ts +69 -0
- package/plugins/pr-dashboard.ts +8 -0
- package/plugins/pr-dashboard.tui.tsx +154 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// Local-git helpers: read .git/config and .git/HEAD directly so we don't
|
|
2
|
+
// need to spawn `git` or `gh` for repo detection / current-branch lookup.
|
|
3
|
+
//
|
|
4
|
+
// These are best-effort filesystem reads; failures surface as null and let
|
|
5
|
+
// the caller fall back to a "no repo" / "no branch PR" state.
|
|
6
|
+
|
|
7
|
+
import { existsSync, readFileSync, statSync } from "node:fs"
|
|
8
|
+
import { join, resolve } from "node:path"
|
|
9
|
+
import type { Repo } from "../domain/types"
|
|
10
|
+
import { enterpriseHostname } from "./github-enterprise"
|
|
11
|
+
|
|
12
|
+
export type { Repo }
|
|
13
|
+
|
|
14
|
+
const HEAD_REF_PREFIX = "ref: refs/heads/"
|
|
15
|
+
|
|
16
|
+
export function currentBranch(cwd: string): string | null {
|
|
17
|
+
const paths = gitPaths(cwd)
|
|
18
|
+
if (!paths) return null
|
|
19
|
+
try {
|
|
20
|
+
const headPath = join(paths.gitDir, "HEAD")
|
|
21
|
+
if (!existsSync(headPath)) return null
|
|
22
|
+
const head = readFileSync(headPath, "utf8").trim()
|
|
23
|
+
if (!head.startsWith(HEAD_REF_PREFIX)) return null
|
|
24
|
+
return head.slice(HEAD_REF_PREFIX.length) || null
|
|
25
|
+
} catch {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function originRemoteUrl(cwd: string): string | null {
|
|
31
|
+
return remoteUrls(cwd).find(({ name }) => name === "origin")?.url ?? null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function remoteUrls(cwd: string): Array<{ name: string; url: string }> {
|
|
35
|
+
const paths = gitPaths(cwd)
|
|
36
|
+
if (!paths) return []
|
|
37
|
+
for (const configPath of new Set([join(paths.commonDir, "config"), join(paths.gitDir, "config")])) {
|
|
38
|
+
try {
|
|
39
|
+
if (!existsSync(configPath)) continue
|
|
40
|
+
const text = readFileSync(configPath, "utf8")
|
|
41
|
+
const remotes: Array<{ name: string; url: string }> = []
|
|
42
|
+
const sectionRe = /^\s*\[remote\s+"([^"]+)"\]\s*$/gim
|
|
43
|
+
let section: RegExpExecArray | null
|
|
44
|
+
|
|
45
|
+
while ((section = sectionRe.exec(text)) !== null) {
|
|
46
|
+
const start = sectionRe.lastIndex
|
|
47
|
+
const nextSection = /^\s*\[/gm
|
|
48
|
+
nextSection.lastIndex = start
|
|
49
|
+
const end = nextSection.exec(text)?.index ?? text.length
|
|
50
|
+
const sectionText = text.slice(start, end)
|
|
51
|
+
const urlRe = /^\s*url\s*=\s*(.*?)\s*$/gim
|
|
52
|
+
let urlMatch: RegExpExecArray | null
|
|
53
|
+
while ((urlMatch = urlRe.exec(sectionText)) !== null) {
|
|
54
|
+
const url = unquoteConfigValue(urlMatch[1])
|
|
55
|
+
if (url) remotes.push({ name: section[1], url })
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (remotes.length) return remotes
|
|
60
|
+
} catch {
|
|
61
|
+
// Try the other config location, or let callers report no repository.
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return []
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function unquoteConfigValue(value: string): string {
|
|
68
|
+
const trimmed = value.trim()
|
|
69
|
+
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
70
|
+
return trimmed.slice(1, -1).replace(/\\(["\\])/g, "$1")
|
|
71
|
+
}
|
|
72
|
+
return trimmed
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function gitPaths(cwd: string): { gitDir: string; commonDir: string } | null {
|
|
76
|
+
let directory = resolve(cwd)
|
|
77
|
+
while (true) {
|
|
78
|
+
const dotGit = join(directory, ".git")
|
|
79
|
+
try {
|
|
80
|
+
if (existsSync(dotGit)) {
|
|
81
|
+
let gitDir: string
|
|
82
|
+
if (statSync(dotGit).isDirectory()) {
|
|
83
|
+
gitDir = dotGit
|
|
84
|
+
} else {
|
|
85
|
+
const gitFile = readFileSync(dotGit, "utf8").trim()
|
|
86
|
+
const match = /^gitdir:\s*(.+)$/m.exec(gitFile)
|
|
87
|
+
if (match) gitDir = resolve(directory, match[1].trim())
|
|
88
|
+
else gitDir = ""
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (gitDir) {
|
|
92
|
+
const commonDirFile = join(gitDir, "commondir")
|
|
93
|
+
const commonDir = existsSync(commonDirFile)
|
|
94
|
+
? resolve(gitDir, readFileSync(commonDirFile, "utf8").trim())
|
|
95
|
+
: gitDir
|
|
96
|
+
return { gitDir, commonDir }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
} catch {
|
|
100
|
+
// A malformed marker may be inside a parent repository; keep searching.
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const parent = resolve(directory, "..")
|
|
104
|
+
if (parent === directory) return null
|
|
105
|
+
directory = parent
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function parseGitHubRemote(url: string, enterpriseUrl?: string): Repo | null {
|
|
110
|
+
const remote = url.trim()
|
|
111
|
+
const configuredHost = enterpriseHostname(enterpriseUrl)
|
|
112
|
+
const supportedHosts = configuredHost ? [configuredHost] : ["github.com", "ssh.github.com"]
|
|
113
|
+
const hostPattern = supportedHosts.map((host) => host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")
|
|
114
|
+
// Git accepts both URI-style SSH URLs and scp-style SSH URLs.
|
|
115
|
+
const scp = new RegExp(`^(?:git@)?(?:${hostPattern}):([^?#]+)$`, "i").exec(remote)
|
|
116
|
+
if (scp) return splitOwnerRepo(scp[1])
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
const parsed = new URL(remote)
|
|
120
|
+
if (
|
|
121
|
+
!supportedHosts.includes(parsed.hostname.toLowerCase()) ||
|
|
122
|
+
!["https:", "http:", "ssh:"].includes(parsed.protocol)
|
|
123
|
+
) {
|
|
124
|
+
return null
|
|
125
|
+
}
|
|
126
|
+
if (!configuredHost && parsed.hostname.toLowerCase() === "ssh.github.com" && parsed.protocol !== "ssh:") {
|
|
127
|
+
return null
|
|
128
|
+
}
|
|
129
|
+
return splitOwnerRepo(parsed.pathname)
|
|
130
|
+
} catch {
|
|
131
|
+
return null
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function detectRepo(
|
|
136
|
+
cwd: string = process.cwd(),
|
|
137
|
+
enterpriseUrl = process.env.GITHUB_ENTERPRISE_URL,
|
|
138
|
+
): Repo | null {
|
|
139
|
+
const remotes = remoteUrls(cwd)
|
|
140
|
+
const preferred = [
|
|
141
|
+
...remotes.filter(({ name }) => name === "origin"),
|
|
142
|
+
...remotes.filter(({ name }) => name !== "origin"),
|
|
143
|
+
]
|
|
144
|
+
for (const { url } of preferred) {
|
|
145
|
+
const repo = parseGitHubRemote(url, enterpriseUrl)
|
|
146
|
+
if (repo) return repo
|
|
147
|
+
}
|
|
148
|
+
return null
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function splitOwnerRepo(path: string): Repo | null {
|
|
152
|
+
const clean = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "")
|
|
153
|
+
const parts = clean.split("/")
|
|
154
|
+
if (parts.length !== 2 || !parts[0] || !parts[1]) return null
|
|
155
|
+
return { owner: parts[0], repo: parts[1] }
|
|
156
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const GITHUB_ENTERPRISE_URL_ENV = "GITHUB_ENTERPRISE_URL"
|
|
2
|
+
|
|
3
|
+
const API_PATH_SUFFIX = "/api/v3"
|
|
4
|
+
|
|
5
|
+
export function enterpriseApiBaseUrl(value?: string): string | null {
|
|
6
|
+
const configured = value?.trim()
|
|
7
|
+
if (!configured) return null
|
|
8
|
+
|
|
9
|
+
let url: URL
|
|
10
|
+
try {
|
|
11
|
+
url = new URL(configured)
|
|
12
|
+
} catch {
|
|
13
|
+
throw new Error(`${GITHUB_ENTERPRISE_URL_ENV} must be an absolute HTTPS URL`)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) {
|
|
17
|
+
throw new Error(`${GITHUB_ENTERPRISE_URL_ENV} must be an HTTPS server URL without credentials, query, or fragment`)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const path = url.pathname.replace(/\/+$/, "")
|
|
21
|
+
if (path && !path.endsWith(API_PATH_SUFFIX)) {
|
|
22
|
+
throw new Error(`${GITHUB_ENTERPRISE_URL_ENV} must be the server URL or its /api/v3 API URL`)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return `${url.origin}${path || API_PATH_SUFFIX}`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function enterpriseHostname(value?: string): string | null {
|
|
29
|
+
const baseUrl = enterpriseApiBaseUrl(value)
|
|
30
|
+
return baseUrl ? new URL(baseUrl).hostname.toLowerCase() : null
|
|
31
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// High-level data loaders for the PR dashboard.
|
|
2
|
+
// Backed by Octokit (REST + GraphQL), which gives us built-in throttling,
|
|
3
|
+
// retry, and timeouts.
|
|
4
|
+
|
|
5
|
+
import { getOctokit } from "./octokit"
|
|
6
|
+
import { type Repo, type PR } from "../domain/types"
|
|
7
|
+
import { mapPullFromGraphQL, mapPullFromREST } from "./mappers"
|
|
8
|
+
import { PULL_REQUESTS_QUERY } from "./queries"
|
|
9
|
+
|
|
10
|
+
export type { Repo, PR }
|
|
11
|
+
|
|
12
|
+
export const MAX_REPOSITORY_PR_PAGES = 1
|
|
13
|
+
|
|
14
|
+
// Which PRs a listing covers. Open PRs are loaded on their own so that a
|
|
15
|
+
// backlog of closed PRs can't push them out of the page limit.
|
|
16
|
+
export type PRListing = "open" | "closed"
|
|
17
|
+
|
|
18
|
+
const LISTING_STATES: Record<PRListing, string[]> = {
|
|
19
|
+
open: ["OPEN"],
|
|
20
|
+
closed: ["CLOSED", "MERGED"],
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type RepositoryPRsResult = {
|
|
24
|
+
prs: PR[]
|
|
25
|
+
viewerLogin: string | null
|
|
26
|
+
listingTruncated: boolean
|
|
27
|
+
fetchedPages: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
31
|
+
return typeof value === "object" && value !== null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function readPullRequestPage(value: unknown): {
|
|
35
|
+
nodes: unknown[]
|
|
36
|
+
viewerLogin: string | null
|
|
37
|
+
hasNextPage: boolean
|
|
38
|
+
endCursor: string | null
|
|
39
|
+
} {
|
|
40
|
+
const root = isRecord(value) ? value : {}
|
|
41
|
+
const viewer = isRecord(root.viewer) ? root.viewer : {}
|
|
42
|
+
const repository = isRecord(root.repository) ? root.repository : {}
|
|
43
|
+
const connection = isRecord(repository.pullRequests) ? repository.pullRequests : {}
|
|
44
|
+
const pageInfo = isRecord(connection.pageInfo) ? connection.pageInfo : {}
|
|
45
|
+
return {
|
|
46
|
+
nodes: Array.isArray(connection.nodes) ? connection.nodes.filter((node) => node != null) : [],
|
|
47
|
+
viewerLogin: typeof viewer.login === "string" ? viewer.login : null,
|
|
48
|
+
hasNextPage: pageInfo.hasNextPage === true,
|
|
49
|
+
endCursor: typeof pageInfo.endCursor === "string" ? pageInfo.endCursor : null,
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Wraps octokit.graphql to return partial data when some fields error.
|
|
54
|
+
// GitHub's GraphQL API returns both `data` and `errors` when specific
|
|
55
|
+
// fields are inaccessible. Octokit throws on any errors, but the partial
|
|
56
|
+
// data is still usable — errored fields are null in the response.
|
|
57
|
+
async function graphqlPartial(
|
|
58
|
+
query: string,
|
|
59
|
+
vars: Record<string, unknown>,
|
|
60
|
+
requestTimeoutMs: number,
|
|
61
|
+
): Promise<unknown> {
|
|
62
|
+
try {
|
|
63
|
+
return await getOctokit(requestTimeoutMs).graphql(query, vars)
|
|
64
|
+
} catch (e: unknown) {
|
|
65
|
+
if (isRecord(e) && "data" in e && e.data) return e.data
|
|
66
|
+
throw e
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function repositoryPRs(
|
|
71
|
+
repo: Repo | null,
|
|
72
|
+
maxPages = MAX_REPOSITORY_PR_PAGES,
|
|
73
|
+
requestTimeoutMs = 15_000,
|
|
74
|
+
listing: PRListing = "open",
|
|
75
|
+
): Promise<RepositoryPRsResult> {
|
|
76
|
+
if (!repo) return { prs: [], viewerLogin: null, listingTruncated: false, fetchedPages: 0 }
|
|
77
|
+
const nodes: unknown[] = []
|
|
78
|
+
let after: string | null = null
|
|
79
|
+
let viewerLogin: string | null = null
|
|
80
|
+
let fetchedPages = 0
|
|
81
|
+
let hasNextPage = false
|
|
82
|
+
const seenCursors = new Set<string>()
|
|
83
|
+
do {
|
|
84
|
+
const data = await graphqlPartial(PULL_REQUESTS_QUERY, {
|
|
85
|
+
owner: repo.owner,
|
|
86
|
+
name: repo.repo,
|
|
87
|
+
states: LISTING_STATES[listing],
|
|
88
|
+
head: null,
|
|
89
|
+
after,
|
|
90
|
+
}, requestTimeoutMs)
|
|
91
|
+
const page = readPullRequestPage(data)
|
|
92
|
+
nodes.push(...page.nodes)
|
|
93
|
+
if (page.viewerLogin) viewerLogin = page.viewerLogin
|
|
94
|
+
hasNextPage = page.hasNextPage
|
|
95
|
+
fetchedPages++
|
|
96
|
+
if (!hasNextPage) {
|
|
97
|
+
after = null
|
|
98
|
+
break
|
|
99
|
+
}
|
|
100
|
+
const nextCursor = page.endCursor
|
|
101
|
+
if (typeof nextCursor !== "string" || nextCursor.length === 0 || seenCursors.has(nextCursor)) {
|
|
102
|
+
throw new Error("GitHub returned an invalid or repeated pull request pagination cursor")
|
|
103
|
+
}
|
|
104
|
+
seenCursors.add(nextCursor)
|
|
105
|
+
after = nextCursor
|
|
106
|
+
} while (hasNextPage && fetchedPages < maxPages)
|
|
107
|
+
return {
|
|
108
|
+
prs: nodes.map(mapPullFromGraphQL),
|
|
109
|
+
viewerLogin,
|
|
110
|
+
listingTruncated: hasNextPage,
|
|
111
|
+
fetchedPages,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function fetchOnePR(repo: Repo, pullNumber: number): Promise<PR> {
|
|
116
|
+
const octokit = getOctokit()
|
|
117
|
+
const { data } = await octokit.pulls.get({
|
|
118
|
+
owner: repo.owner,
|
|
119
|
+
repo: repo.repo,
|
|
120
|
+
pull_number: pullNumber,
|
|
121
|
+
})
|
|
122
|
+
return mapPullFromREST(data)
|
|
123
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// PR shape mappers: convert raw GitHub GraphQL and REST pull objects into
|
|
2
|
+
// the shared PR domain type. Both mappers live
|
|
3
|
+
// here so that changes to PR only need to be reflected in one place.
|
|
4
|
+
|
|
5
|
+
import type { PR } from "../domain/types"
|
|
6
|
+
|
|
7
|
+
type RecordValue = Record<string, unknown>
|
|
8
|
+
|
|
9
|
+
function record(value: unknown): RecordValue {
|
|
10
|
+
return typeof value === "object" && value !== null ? value as RecordValue : {}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function string(value: unknown, fallback = ""): string {
|
|
14
|
+
return typeof value === "string" ? value : fallback
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function number(value: unknown, fallback = 0): number {
|
|
18
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function array(value: unknown): unknown[] {
|
|
22
|
+
return Array.isArray(value) ? value : []
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Maps a GraphQL PullRequest node to PR.
|
|
26
|
+
export function mapPullFromGraphQL(value: unknown): PR {
|
|
27
|
+
const p = record(value)
|
|
28
|
+
const author = record(p.author)
|
|
29
|
+
const assignees = record(p.assignees)
|
|
30
|
+
const rollup = p.statusCheckRollup == null ? null : record(p.statusCheckRollup)
|
|
31
|
+
const contexts = rollup ? record(rollup.contexts) : {}
|
|
32
|
+
const reviewThreads = record(p.reviewThreads)
|
|
33
|
+
const reviewRequests = record(p.reviewRequests)
|
|
34
|
+
const latestReviews = record(p.latestReviews)
|
|
35
|
+
return {
|
|
36
|
+
number: number(p.number),
|
|
37
|
+
title: string(p.title),
|
|
38
|
+
url: string(p.url),
|
|
39
|
+
isDraft: p.isDraft === true,
|
|
40
|
+
isMerged: p.state === "MERGED" || p.merged === true,
|
|
41
|
+
isClosed: p.state === "CLOSED" || p.state === "MERGED" || p.merged === true,
|
|
42
|
+
headRefName: string(p.headRefName),
|
|
43
|
+
authorLogin: string(author.login),
|
|
44
|
+
assigneeLogins: array(assignees.nodes)
|
|
45
|
+
.map((assignee) => string(record(assignee).login))
|
|
46
|
+
.filter(Boolean),
|
|
47
|
+
additions: number(p.additions),
|
|
48
|
+
deletions: number(p.deletions),
|
|
49
|
+
baseRefName: string(p.baseRefName),
|
|
50
|
+
mergeable: string(p.mergeable, "UNKNOWN").toUpperCase(),
|
|
51
|
+
statusCheckRollup: rollup ? { state: string(rollup.state, "UNKNOWN") } : null,
|
|
52
|
+
checkStatuses: Array.isArray(contexts.nodes)
|
|
53
|
+
? contexts.nodes
|
|
54
|
+
.map((value) => {
|
|
55
|
+
const context = record(value)
|
|
56
|
+
return context.__typename === "CheckRun"
|
|
57
|
+
? string(context.conclusion) || string(context.status)
|
|
58
|
+
: string(context.state)
|
|
59
|
+
})
|
|
60
|
+
.filter(Boolean)
|
|
61
|
+
: null,
|
|
62
|
+
reviewThreads: Array.isArray(reviewThreads.nodes)
|
|
63
|
+
? reviewThreads.nodes.map((thread) => ({ isResolved: record(thread).isResolved === true }))
|
|
64
|
+
: null,
|
|
65
|
+
reviewRequests: array(reviewRequests.nodes)
|
|
66
|
+
.map((node) => string(record(record(node).requestedReviewer).login))
|
|
67
|
+
.filter(Boolean)
|
|
68
|
+
.map((login) => ({ login })),
|
|
69
|
+
latestReviews: array(latestReviews.nodes).map((value) => {
|
|
70
|
+
const review = record(value)
|
|
71
|
+
return {
|
|
72
|
+
author: { login: string(record(review.author).login) },
|
|
73
|
+
state: string(review.state),
|
|
74
|
+
}
|
|
75
|
+
}),
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Maps a REST `pulls.get` response data object to PR. REST doesn't
|
|
80
|
+
// provide statusCheckRollup, so the field is null.
|
|
81
|
+
export function mapPullFromREST(value: unknown): PR {
|
|
82
|
+
const p = record(value)
|
|
83
|
+
const head = record(p.head)
|
|
84
|
+
const base = record(p.base)
|
|
85
|
+
const user = record(p.user)
|
|
86
|
+
return {
|
|
87
|
+
number: number(p.number),
|
|
88
|
+
title: string(p.title),
|
|
89
|
+
url: string(p.html_url),
|
|
90
|
+
isDraft: p.draft === true,
|
|
91
|
+
isMerged: p.merged === true,
|
|
92
|
+
isClosed: p.state === "closed" || p.merged === true,
|
|
93
|
+
headRefName: string(head.ref),
|
|
94
|
+
authorLogin: string(user.login),
|
|
95
|
+
assigneeLogins: array(p.assignees)
|
|
96
|
+
.map((assignee) => string(record(assignee).login))
|
|
97
|
+
.filter(Boolean),
|
|
98
|
+
additions: number(p.additions),
|
|
99
|
+
deletions: number(p.deletions),
|
|
100
|
+
baseRefName: string(base.ref),
|
|
101
|
+
mergeable: p.mergeable === true ? "MERGEABLE" : p.mergeable === false ? "CONFLICTING" : "UNKNOWN",
|
|
102
|
+
statusCheckRollup: null,
|
|
103
|
+
checkStatuses: null,
|
|
104
|
+
reviewThreads: null,
|
|
105
|
+
reviewRequests: array(p.requested_reviewers)
|
|
106
|
+
.map((reviewer) => string(record(reviewer).login))
|
|
107
|
+
.filter(Boolean)
|
|
108
|
+
.map((login) => ({ login })),
|
|
109
|
+
latestReviews: array(p.latest_reviews).map((value) => {
|
|
110
|
+
const review = record(value)
|
|
111
|
+
return {
|
|
112
|
+
author: { login: string(record(review.user).login) },
|
|
113
|
+
state: string(review.state),
|
|
114
|
+
}
|
|
115
|
+
}),
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Octokit client factory for the PR dashboard.
|
|
2
|
+
// Auth: reads a GitHub token from the environment, then falls back to `gh auth token`.
|
|
3
|
+
//
|
|
4
|
+
// Plugins: throttling (respects X-RateLimit-Reset / Retry-After / secondary
|
|
5
|
+
// rate limits) and retry (handles 5xx and 429 with exponential backoff +
|
|
6
|
+
// jitter). doNotRetry covers 4xx that won't recover on their own.
|
|
7
|
+
|
|
8
|
+
import { Octokit } from "@octokit/rest"
|
|
9
|
+
import type { Octokit as CoreOctokit } from "@octokit/core"
|
|
10
|
+
import type { EndpointDefaults } from "@octokit/types"
|
|
11
|
+
import { throttling } from "@octokit/plugin-throttling"
|
|
12
|
+
import { retry } from "@octokit/plugin-retry"
|
|
13
|
+
import { execFileSync } from "node:child_process"
|
|
14
|
+
import { errorMessages } from "../domain/messages"
|
|
15
|
+
import { enterpriseApiBaseUrl, enterpriseHostname } from "./github-enterprise"
|
|
16
|
+
const OctokitWithPlugins = Octokit.plugin(throttling, retry)
|
|
17
|
+
|
|
18
|
+
function readGhAuthToken(hostname?: string): string | undefined {
|
|
19
|
+
try {
|
|
20
|
+
const args = ["auth", "token"]
|
|
21
|
+
if (hostname) args.push("--hostname", hostname)
|
|
22
|
+
const token = execFileSync("gh", args, {
|
|
23
|
+
encoding: "utf8",
|
|
24
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
25
|
+
timeout: 5_000,
|
|
26
|
+
}).trim()
|
|
27
|
+
return token || undefined
|
|
28
|
+
} catch {
|
|
29
|
+
return undefined
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function getAuthToken(
|
|
34
|
+
env: Record<string, string | undefined> = process.env,
|
|
35
|
+
ghAuthToken: (hostname?: string) => string | undefined = readGhAuthToken,
|
|
36
|
+
): string {
|
|
37
|
+
const token = env.GITHUB_TOKEN || env.GH_TOKEN || env.GITHUB_PERSONAL_ACCESS_TOKEN
|
|
38
|
+
if (token) return token
|
|
39
|
+
const ghToken = ghAuthToken(enterpriseHostname(env.GITHUB_ENTERPRISE_URL) ?? undefined)
|
|
40
|
+
if (ghToken) return ghToken
|
|
41
|
+
throw new Error(errorMessages.noAuthToken)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export type OctokitOpts = {
|
|
45
|
+
token?: string
|
|
46
|
+
enterpriseUrl?: string
|
|
47
|
+
fetch?: typeof globalThis.fetch
|
|
48
|
+
requestTimeoutMs?: number
|
|
49
|
+
throttle?: boolean
|
|
50
|
+
retry?: boolean
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function createOctokit(opts: OctokitOpts = {}): Octokit {
|
|
54
|
+
return new OctokitWithPlugins({
|
|
55
|
+
userAgent: "opencode-gh-pr",
|
|
56
|
+
auth: opts.token,
|
|
57
|
+
baseUrl: enterpriseApiBaseUrl(opts.enterpriseUrl) ?? undefined,
|
|
58
|
+
request: { timeout: opts.requestTimeoutMs ?? 15_000, fetch: opts.fetch },
|
|
59
|
+
throttle:
|
|
60
|
+
opts.throttle === false
|
|
61
|
+
? { enabled: false }
|
|
62
|
+
: {
|
|
63
|
+
onRateLimit: (
|
|
64
|
+
retryAfter: number,
|
|
65
|
+
options: Required<EndpointDefaults>,
|
|
66
|
+
octokit: CoreOctokit,
|
|
67
|
+
retryCount: number,
|
|
68
|
+
) => {
|
|
69
|
+
octokit.log.warn(
|
|
70
|
+
`[pr-dashboard] rate limit hit on ${options.method} ${options.url}; retry ${retryCount} after ${retryAfter}s`,
|
|
71
|
+
)
|
|
72
|
+
return retryCount < 2
|
|
73
|
+
},
|
|
74
|
+
onSecondaryRateLimit: (retryAfter: number, options: Required<EndpointDefaults>, octokit: CoreOctokit) => {
|
|
75
|
+
octokit.log.warn(
|
|
76
|
+
`[pr-dashboard] secondary rate limit on ${options.method} ${options.url}; would wait ${retryAfter}s, aborting`,
|
|
77
|
+
)
|
|
78
|
+
return false
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
retry:
|
|
82
|
+
opts.retry === false
|
|
83
|
+
? { enabled: false }
|
|
84
|
+
: {
|
|
85
|
+
doNotRetry: [400, 401, 403, 404, 422],
|
|
86
|
+
},
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let cached: {
|
|
91
|
+
token: string
|
|
92
|
+
requestTimeoutMs: number
|
|
93
|
+
baseUrl: string | null
|
|
94
|
+
client: Octokit
|
|
95
|
+
} | null = null
|
|
96
|
+
|
|
97
|
+
export function getOctokit(requestTimeoutMs = 15_000): Octokit {
|
|
98
|
+
const enterpriseUrl = process.env.GITHUB_ENTERPRISE_URL
|
|
99
|
+
const baseUrl = enterpriseApiBaseUrl(enterpriseUrl)
|
|
100
|
+
if (cached?.baseUrl === baseUrl && cached.requestTimeoutMs === requestTimeoutMs) {
|
|
101
|
+
return cached.client
|
|
102
|
+
}
|
|
103
|
+
const token = cached?.token ?? getAuthToken()
|
|
104
|
+
const client = createOctokit({ token, requestTimeoutMs, enterpriseUrl })
|
|
105
|
+
cached = { token, requestTimeoutMs, baseUrl, client }
|
|
106
|
+
return client
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function setOctokit(client: Octokit | null): void {
|
|
110
|
+
if (client === null) {
|
|
111
|
+
cached = null
|
|
112
|
+
} else {
|
|
113
|
+
cached = { token: "test", requestTimeoutMs: 15_000, baseUrl: null, client }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// GraphQL query strings used by the PR dashboard loaders.
|
|
2
|
+
//
|
|
3
|
+
// Kept separate from loader.ts so the query surface is easy to audit
|
|
4
|
+
// (scope requirements, field selection) without scrolling through the
|
|
5
|
+
// orchestration code.
|
|
6
|
+
|
|
7
|
+
// PRs for a repository (or one head branch) in the given GitHub states.
|
|
8
|
+
export const PULL_REQUESTS_QUERY = `query PullRequests($owner: String!, $name: String!, $states: [PullRequestState!]!, $head: String, $after: String) {
|
|
9
|
+
viewer {
|
|
10
|
+
login
|
|
11
|
+
}
|
|
12
|
+
repository(owner: $owner, name: $name) {
|
|
13
|
+
pullRequests(first: 100, after: $after, states: $states, headRefName: $head, orderBy: {field: UPDATED_AT, direction: DESC}) {
|
|
14
|
+
pageInfo {
|
|
15
|
+
hasNextPage
|
|
16
|
+
endCursor
|
|
17
|
+
}
|
|
18
|
+
nodes {
|
|
19
|
+
number
|
|
20
|
+
title
|
|
21
|
+
url
|
|
22
|
+
isDraft
|
|
23
|
+
state
|
|
24
|
+
headRefName
|
|
25
|
+
author { login }
|
|
26
|
+
assignees(first: 100) {
|
|
27
|
+
nodes { login }
|
|
28
|
+
}
|
|
29
|
+
additions
|
|
30
|
+
deletions
|
|
31
|
+
baseRefName
|
|
32
|
+
mergeable
|
|
33
|
+
statusCheckRollup {
|
|
34
|
+
state
|
|
35
|
+
contexts(first: 100) {
|
|
36
|
+
nodes {
|
|
37
|
+
__typename
|
|
38
|
+
... on CheckRun {
|
|
39
|
+
status
|
|
40
|
+
conclusion
|
|
41
|
+
}
|
|
42
|
+
... on StatusContext {
|
|
43
|
+
state
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
reviewThreads(first: 100) {
|
|
49
|
+
nodes {
|
|
50
|
+
isResolved
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
reviewRequests(first: 5) {
|
|
54
|
+
nodes {
|
|
55
|
+
requestedReviewer {
|
|
56
|
+
... on User { login }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
latestReviews(first: 5) {
|
|
61
|
+
nodes {
|
|
62
|
+
author { login }
|
|
63
|
+
state
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}`
|