opencode-github-pr 0.1.0 → 0.2.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/README.md +168 -59
- package/demo/fixtures.ts +74 -8
- package/dist/pr-dashboard.tui.js +8710 -0
- package/package.json +20 -11
- package/plugins/app/DashboardView.tsx +166 -83
- package/plugins/app/PRRow.tsx +86 -54
- package/plugins/app/StatusMessage.tsx +22 -0
- package/plugins/app/config.ts +90 -10
- package/plugins/app/theme.ts +1 -10
- package/plugins/app/usePRData.ts +256 -85
- package/plugins/domain/format.ts +11 -22
- package/plugins/domain/messages.ts +34 -12
- package/plugins/domain/pr-status.ts +23 -22
- package/plugins/domain/types.ts +23 -6
- package/plugins/infra/git.ts +287 -27
- package/plugins/infra/loader.ts +274 -41
- package/plugins/infra/mappers.ts +25 -49
- package/plugins/infra/octokit.ts +33 -17
- package/plugins/infra/queries.ts +137 -51
- package/plugins/pr-dashboard.tui.tsx +124 -40
- package/demo/demo.gif +0 -0
- package/plugins/domain/login.ts +0 -33
package/plugins/domain/format.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
// Pure formatting helpers used by the TUI sidebar
|
|
2
|
-
// relative age rendering.
|
|
1
|
+
// Pure formatting helpers used by the TUI sidebar.
|
|
3
2
|
|
|
4
3
|
const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" })
|
|
5
4
|
|
|
@@ -9,30 +8,20 @@ export function truncateTitle(title: string, maxWidth: number): string {
|
|
|
9
8
|
if (Bun.stringWidth(normalized) <= budget) return normalized
|
|
10
9
|
|
|
11
10
|
const contentBudget = Math.max(0, budget - Bun.stringWidth("…"))
|
|
11
|
+
let wholeWords = ""
|
|
12
|
+
for (const word of normalized.split(" ")) {
|
|
13
|
+
const next = wholeWords ? `${wholeWords} ${word}` : word
|
|
14
|
+
if (Bun.stringWidth(next) > contentBudget) break
|
|
15
|
+
wholeWords = next
|
|
16
|
+
}
|
|
17
|
+
if (wholeWords) return `${wholeWords}…`
|
|
18
|
+
|
|
19
|
+
// If even the first word is too long, fall back to a grapheme-safe cut.
|
|
12
20
|
let prefix = ""
|
|
13
|
-
let truncated = ""
|
|
14
21
|
for (const { segment } of graphemes.segment(normalized)) {
|
|
15
22
|
const next = prefix + segment
|
|
16
23
|
if (Bun.stringWidth(next) > contentBudget) break
|
|
17
24
|
prefix = next
|
|
18
|
-
truncated = prefix
|
|
19
25
|
}
|
|
20
|
-
|
|
21
|
-
const wordBoundary = truncated.lastIndexOf(" ")
|
|
22
|
-
if (wordBoundary > 0) truncated = truncated.slice(0, wordBoundary).trimEnd()
|
|
23
|
-
return `${truncated}…`
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export function formatAge(iso: string): string {
|
|
27
|
-
const t = Date.parse(iso)
|
|
28
|
-
if (Number.isNaN(t)) return ""
|
|
29
|
-
const diff = Date.now() - t
|
|
30
|
-
const m = Math.floor(diff / 60_000)
|
|
31
|
-
if (m < 1) return "now"
|
|
32
|
-
if (m < 60) return `${m}m`
|
|
33
|
-
const h = Math.floor(m / 60)
|
|
34
|
-
if (h < 24) return `${h}h`
|
|
35
|
-
const d = Math.floor(h / 24)
|
|
36
|
-
if (d < 30) return `${d}d`
|
|
37
|
-
return `${Math.floor(d / 30)}mo`
|
|
26
|
+
return `${prefix}…`
|
|
38
27
|
}
|
|
@@ -5,9 +5,7 @@ import type { PRListErrorKind } from "./types"
|
|
|
5
5
|
// Message convention:
|
|
6
6
|
// - Success messages are verb-specific and live in the tool/action
|
|
7
7
|
// that produces them (e.g. "Requested review from @alice on PR #42").
|
|
8
|
-
// - Tool/action failures use
|
|
9
|
-
// ("Failed: <detail>"). The tool description provides context; the
|
|
10
|
-
// error string just conveys what went wrong.
|
|
8
|
+
// - Tool/action failures use an error string appropriate to the action.
|
|
11
9
|
// - Reusable domain states (no repo, no auth, rate limit, HTTP status
|
|
12
10
|
// categories) have dedicated entries here because they're shared
|
|
13
11
|
// across multiple actions.
|
|
@@ -33,8 +31,6 @@ export const errorMessages = {
|
|
|
33
31
|
unknown: (msg: string) => msg,
|
|
34
32
|
},
|
|
35
33
|
|
|
36
|
-
// generic toast/tool failure fallback
|
|
37
|
-
failed: (msg: string) => `Failed: ${msg}`,
|
|
38
34
|
unknown: "unknown",
|
|
39
35
|
|
|
40
36
|
// dashboard view banners / empty states
|
|
@@ -50,6 +46,11 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
50
46
|
export function prListErrorKind(e: unknown): PRListErrorKind {
|
|
51
47
|
if (!e) return "unknown"
|
|
52
48
|
const details = isRecord(e) ? e : {}
|
|
49
|
+
const graphqlErrors = Array.isArray(details.errors) ? details.errors : []
|
|
50
|
+
const graphqlTypes = graphqlErrors.filter(isRecord).map((error) => error.type)
|
|
51
|
+
if (graphqlTypes.includes("NOT_FOUND")) return "not-found"
|
|
52
|
+
if (graphqlTypes.includes("FORBIDDEN")) return "forbidden"
|
|
53
|
+
if (graphqlTypes.includes("RATE_LIMITED")) return "rate-limit"
|
|
53
54
|
const status = typeof details.status === "number" ? details.status : undefined
|
|
54
55
|
const name = typeof details.name === "string" ? details.name : undefined
|
|
55
56
|
const code = typeof details.code === "string" ? details.code : undefined
|
|
@@ -125,23 +126,28 @@ export function prListErrorMessage(e: unknown): string {
|
|
|
125
126
|
}
|
|
126
127
|
|
|
127
128
|
export type RateLimitInfo =
|
|
128
|
-
| { isRateLimit: true; message: string; resetAt: number }
|
|
129
|
-
| { isRateLimit: false; message: null; resetAt: null }
|
|
129
|
+
| { isRateLimit: true; message: string; resetAt: number; isSecondary: boolean }
|
|
130
|
+
| { isRateLimit: false; message: null; resetAt: null; isSecondary: false }
|
|
130
131
|
|
|
131
132
|
// Detects GitHub primary/secondary rate-limit errors and extracts the
|
|
132
|
-
// reset time from
|
|
133
|
+
// reset time from x-ratelimit-reset or retry-after. Used by useDashboard to
|
|
133
134
|
// preserve the existing PR list when the error is a rate limit (the PRs
|
|
134
135
|
// are still valid; only the fetch failed).
|
|
135
136
|
export function parseRateLimitError(e: unknown): RateLimitInfo {
|
|
136
137
|
const details = isRecord(e) ? e : {}
|
|
137
138
|
const msg = typeof details.message === "string" ? details.message : ""
|
|
139
|
+
const graphqlErrors = Array.isArray(details.errors) ? details.errors : []
|
|
140
|
+
const hasGraphQLRateLimit = graphqlErrors.some((error) =>
|
|
141
|
+
isRecord(error) && error.type === "RATE_LIMITED"
|
|
142
|
+
)
|
|
138
143
|
const status = typeof details.status === "number" ? details.status : undefined
|
|
139
144
|
const isRateLimit =
|
|
140
145
|
status === 429 ||
|
|
141
146
|
(status === 403 && /rate limit/i.test(msg)) ||
|
|
147
|
+
hasGraphQLRateLimit ||
|
|
142
148
|
/rate limit (already exceeded|exceeded)/i.test(msg) ||
|
|
143
149
|
/api rate limit/i.test(msg)
|
|
144
|
-
if (!isRateLimit) return { isRateLimit: false, message: null, resetAt: null }
|
|
150
|
+
if (!isRateLimit) return { isRateLimit: false, message: null, resetAt: null, isSecondary: false }
|
|
145
151
|
|
|
146
152
|
const response = isRecord(details.response) ? details.response : {}
|
|
147
153
|
const headers = isRecord(response.headers)
|
|
@@ -149,13 +155,29 @@ export function parseRateLimitError(e: unknown): RateLimitInfo {
|
|
|
149
155
|
: isRecord(details.headers)
|
|
150
156
|
? details.headers
|
|
151
157
|
: {}
|
|
158
|
+
const rawDate = headers.date ?? headers.Date
|
|
159
|
+
const serverNow = rawDate === undefined ? null : Date.parse(String(rawDate))
|
|
160
|
+
const now = Date.now()
|
|
161
|
+
const clockOffset = serverNow !== null && Number.isFinite(serverNow) ? serverNow - now : 0
|
|
162
|
+
const rawRetryAfter = headers["retry-after"] ?? headers["Retry-After"]
|
|
163
|
+
const retryAfter = rawRetryAfter === undefined
|
|
164
|
+
? null
|
|
165
|
+
: /^\d+(?:\.\d+)?$/.test(String(rawRetryAfter))
|
|
166
|
+
? (serverNow !== null && Number.isFinite(serverNow) ? serverNow : now) +
|
|
167
|
+
Number(rawRetryAfter) * 1000 - clockOffset
|
|
168
|
+
: Number.isNaN(Date.parse(String(rawRetryAfter)))
|
|
169
|
+
? null
|
|
170
|
+
: Date.parse(String(rawRetryAfter)) - clockOffset
|
|
152
171
|
const rawReset = headers["x-ratelimit-reset"] ?? headers["X-RateLimit-Reset"]
|
|
153
|
-
const
|
|
172
|
+
const primaryReset = rawReset ? parseInt(String(rawReset), 10) * 1000 - clockOffset : null
|
|
173
|
+
const isSecondary =
|
|
174
|
+
/secondary rate limit/i.test(msg) || status === 429 || retryAfter !== null
|
|
175
|
+
const resetAt = isSecondary ? retryAfter ?? primaryReset : primaryReset
|
|
154
176
|
const resetText = resetAt ? new Date(resetAt).toLocaleTimeString() : "unknown time"
|
|
155
177
|
|
|
156
178
|
let detail = `GitHub API rate limit exceeded — resets at ${resetText}.`
|
|
157
|
-
if (
|
|
179
|
+
if (isSecondary) {
|
|
158
180
|
detail = `GitHub secondary rate limit hit (too many requests) — try again at ${resetText}.`
|
|
159
181
|
}
|
|
160
|
-
return { isRateLimit: true, message: detail, resetAt: resetAt ?? 0 }
|
|
182
|
+
return { isRateLimit: true, message: detail, resetAt: resetAt ?? 0, isSecondary }
|
|
161
183
|
}
|
|
@@ -6,15 +6,16 @@ import type { PR } from "./types"
|
|
|
6
6
|
export type StatusCategory = "pass" | "fail" | "pending" | "neutral" | "none"
|
|
7
7
|
export type StatusGroup = { status: StatusCategory; count: number }
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
if (pr.
|
|
13
|
-
if (pr.
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
return "
|
|
9
|
+
export function mergeReadiness(pr: PR): StatusCategory {
|
|
10
|
+
if (pr.reviewDecision === "CHANGES_REQUESTED") return "fail"
|
|
11
|
+
if (pr.mergeStateStatus === "DIRTY") return "fail"
|
|
12
|
+
if (pr.reviewDecision === "REVIEW_REQUIRED") return "pending"
|
|
13
|
+
if (pr.mergeStateStatus === "CLEAN" || pr.mergeStateStatus === "HAS_HOOKS") {
|
|
14
|
+
if (pr.reviewDecision === null || pr.reviewDecision === "APPROVED") return "pass"
|
|
15
|
+
return "neutral"
|
|
16
|
+
}
|
|
17
|
+
if (["BLOCKED", "BEHIND", "UNSTABLE"].includes(pr.mergeStateStatus)) return "pending"
|
|
18
|
+
return "none"
|
|
18
19
|
}
|
|
19
20
|
|
|
20
21
|
export function classifyCI(pr: PR): "pass" | "fail" | "pending" | "none" {
|
|
@@ -81,7 +82,7 @@ export function reviewStatusGroups(pr: PR): StatusGroup[] {
|
|
|
81
82
|
]))
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
export function commentThreadCounts(pr: PR): { open: number; resolved: number } | null {
|
|
85
|
+
export function commentThreadCounts(pr: PR): { open: number; resolved: number; truncated: boolean } | null {
|
|
85
86
|
if (pr.reviewThreads === null) return null
|
|
86
87
|
return pr.reviewThreads.reduce(
|
|
87
88
|
(counts, thread) => {
|
|
@@ -89,7 +90,7 @@ export function commentThreadCounts(pr: PR): { open: number; resolved: number }
|
|
|
89
90
|
else counts.open++
|
|
90
91
|
return counts
|
|
91
92
|
},
|
|
92
|
-
{ open: 0, resolved: 0 },
|
|
93
|
+
{ open: 0, resolved: 0, truncated: pr.reviewThreadsTruncated === true },
|
|
93
94
|
)
|
|
94
95
|
}
|
|
95
96
|
|
|
@@ -98,30 +99,30 @@ export function reviewSummary(pr: PR): {
|
|
|
98
99
|
changes: number
|
|
99
100
|
pending: number
|
|
100
101
|
commented: number
|
|
101
|
-
approvedLogins: string[]
|
|
102
|
-
changesLogins: string[]
|
|
103
|
-
pendingLogins: string[]
|
|
104
|
-
commentedLogins: string[]
|
|
105
102
|
} {
|
|
103
|
+
const pendingUsers = new Set<string>()
|
|
104
|
+
const pendingTeams = new Set<string>()
|
|
105
|
+
for (const request of pr.reviewRequests ?? []) {
|
|
106
|
+
if (request.type === "team") {
|
|
107
|
+
if (request.slug) pendingTeams.add(request.slug.toLowerCase())
|
|
108
|
+
} else if (request.login) {
|
|
109
|
+
pendingUsers.add(request.login.toLowerCase())
|
|
110
|
+
}
|
|
111
|
+
}
|
|
106
112
|
const approved = new Set<string>()
|
|
107
113
|
const changes = new Set<string>()
|
|
108
114
|
const commented = new Set<string>()
|
|
109
115
|
for (const r of pr.latestReviews ?? []) {
|
|
110
116
|
const login = r.author?.login
|
|
111
|
-
if (!login) continue
|
|
117
|
+
if (!login || pendingUsers.has(login.toLowerCase())) continue
|
|
112
118
|
if (r.state === "APPROVED") approved.add(login)
|
|
113
119
|
else if (r.state === "CHANGES_REQUESTED") changes.add(login)
|
|
114
120
|
else if (r.state === "COMMENTED") commented.add(login)
|
|
115
121
|
}
|
|
116
|
-
const pendingLogins = (pr.reviewRequests ?? []).map((r) => r.login).filter(Boolean)
|
|
117
122
|
return {
|
|
118
123
|
approved: approved.size,
|
|
119
124
|
changes: changes.size,
|
|
120
|
-
pending:
|
|
125
|
+
pending: pendingUsers.size + pendingTeams.size,
|
|
121
126
|
commented: commented.size,
|
|
122
|
-
approvedLogins: Array.from(approved),
|
|
123
|
-
changesLogins: Array.from(changes),
|
|
124
|
-
pendingLogins,
|
|
125
|
-
commentedLogins: Array.from(commented),
|
|
126
127
|
}
|
|
127
128
|
}
|
package/plugins/domain/types.ts
CHANGED
|
@@ -12,16 +12,23 @@ export type PR = {
|
|
|
12
12
|
isMerged: boolean
|
|
13
13
|
isClosed: boolean
|
|
14
14
|
headRefName: string
|
|
15
|
+
headRepositoryOwnerLogin?: string
|
|
15
16
|
authorLogin: string
|
|
16
17
|
assigneeLogins: string[]
|
|
17
18
|
additions: number
|
|
18
19
|
deletions: number
|
|
19
20
|
baseRefName: string
|
|
20
21
|
mergeable: string
|
|
22
|
+
mergeStateStatus: string
|
|
23
|
+
reviewDecision: string | null
|
|
21
24
|
statusCheckRollup: { state: string } | null
|
|
22
25
|
checkStatuses: string[] | null
|
|
23
26
|
reviewThreads: Array<{ isResolved: boolean }> | null
|
|
24
|
-
|
|
27
|
+
reviewThreadsTruncated?: boolean
|
|
28
|
+
reviewRequests: Array<
|
|
29
|
+
| { type: "user"; login: string }
|
|
30
|
+
| { type: "team"; slug: string }
|
|
31
|
+
> | null
|
|
25
32
|
latestReviews: Array<{ author: { login: string }; state: string }> | null
|
|
26
33
|
}
|
|
27
34
|
|
|
@@ -57,10 +64,20 @@ export type DashboardState = {
|
|
|
57
64
|
currentBranch: string | null
|
|
58
65
|
viewerLogin: string | null
|
|
59
66
|
fetchedAt: number | null
|
|
60
|
-
//
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
67
|
+
// The active status listing is fetched from GitHub in cursor-based batches.
|
|
68
|
+
pagination: {
|
|
69
|
+
listing: PRStatusFilter
|
|
70
|
+
scope: PRScope
|
|
71
|
+
scopeValue: string | null
|
|
72
|
+
cursor: string | null
|
|
73
|
+
hasMore: boolean
|
|
74
|
+
totalCount: number | null
|
|
75
|
+
pagesLoaded: number
|
|
76
|
+
searchResultsFetched: number
|
|
77
|
+
supplementalPRCount: number
|
|
78
|
+
loading: boolean
|
|
79
|
+
limitReached: boolean
|
|
80
|
+
}
|
|
64
81
|
error?: string
|
|
65
82
|
errorKind?: PRListErrorKind
|
|
66
83
|
}
|
|
@@ -71,7 +88,7 @@ export type DashboardState = {
|
|
|
71
88
|
export interface DashboardContext {
|
|
72
89
|
state: () => DashboardState
|
|
73
90
|
refresh: () => Promise<void>
|
|
74
|
-
|
|
91
|
+
loadMore: () => Promise<void>
|
|
75
92
|
selectedIdx: () => number
|
|
76
93
|
setSelectedIdx: (n: number) => void
|
|
77
94
|
}
|
package/plugins/infra/git.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
// the caller fall back to a "no repo" / "no branch PR" state.
|
|
6
6
|
|
|
7
7
|
import { existsSync, readFileSync, statSync } from "node:fs"
|
|
8
|
+
import { execFile } from "node:child_process"
|
|
9
|
+
import { homedir } from "node:os"
|
|
8
10
|
import { join, resolve } from "node:path"
|
|
9
11
|
import type { Repo } from "../domain/types"
|
|
10
12
|
import { enterpriseHostname } from "./github-enterprise"
|
|
@@ -12,12 +14,15 @@ import { enterpriseHostname } from "./github-enterprise"
|
|
|
12
14
|
export type { Repo }
|
|
13
15
|
|
|
14
16
|
const HEAD_REF_PREFIX = "ref: refs/heads/"
|
|
17
|
+
const SSH_CONFIG_TIMEOUT_MS = 500
|
|
18
|
+
const sshHostCache = new Map<string, Promise<string | null>>()
|
|
19
|
+
export type SshHostResolver = (host: string) => Promise<string | null>
|
|
15
20
|
|
|
16
21
|
export function currentBranch(cwd: string): string | null {
|
|
17
22
|
const paths = gitPaths(cwd)
|
|
18
|
-
if (!paths) return null
|
|
23
|
+
if (!paths?.branchDir) return null
|
|
19
24
|
try {
|
|
20
|
-
const headPath = join(paths.
|
|
25
|
+
const headPath = join(paths.branchDir, "HEAD")
|
|
21
26
|
if (!existsSync(headPath)) return null
|
|
22
27
|
const head = readFileSync(headPath, "utf8").trim()
|
|
23
28
|
if (!head.startsWith(HEAD_REF_PREFIX)) return null
|
|
@@ -27,14 +32,13 @@ export function currentBranch(cwd: string): string | null {
|
|
|
27
32
|
}
|
|
28
33
|
}
|
|
29
34
|
|
|
30
|
-
export function originRemoteUrl(cwd: string): string | null {
|
|
31
|
-
return remoteUrls(cwd).find(({ name }) => name === "origin")?.url ?? null
|
|
32
|
-
}
|
|
33
|
-
|
|
34
35
|
function remoteUrls(cwd: string): Array<{ name: string; url: string }> {
|
|
35
36
|
const paths = gitPaths(cwd)
|
|
36
37
|
if (!paths) return []
|
|
37
|
-
for (const configPath of new Set([
|
|
38
|
+
for (const configPath of new Set([
|
|
39
|
+
join(paths.commonDir, "config"),
|
|
40
|
+
join(paths.gitDir, "config"),
|
|
41
|
+
])) {
|
|
38
42
|
try {
|
|
39
43
|
if (!existsSync(configPath)) continue
|
|
40
44
|
const text = readFileSync(configPath, "utf8")
|
|
@@ -72,11 +76,15 @@ function unquoteConfigValue(value: string): string {
|
|
|
72
76
|
return trimmed
|
|
73
77
|
}
|
|
74
78
|
|
|
75
|
-
|
|
79
|
+
type GitPaths = { gitDir: string; commonDir: string; branchDir: string | null }
|
|
80
|
+
|
|
81
|
+
function gitPaths(cwd: string): GitPaths | null {
|
|
82
|
+
// Session directories may be nested below a checkout. Walk upward and stop
|
|
83
|
+
// at the first Git marker so nested repositories take precedence over parents.
|
|
76
84
|
let directory = resolve(cwd)
|
|
77
85
|
while (true) {
|
|
78
|
-
const dotGit = join(directory, ".git")
|
|
79
86
|
try {
|
|
87
|
+
const dotGit = join(directory, ".git")
|
|
80
88
|
if (existsSync(dotGit)) {
|
|
81
89
|
let gitDir: string
|
|
82
90
|
if (statSync(dotGit).isDirectory()) {
|
|
@@ -84,18 +92,18 @@ function gitPaths(cwd: string): { gitDir: string; commonDir: string } | null {
|
|
|
84
92
|
} else {
|
|
85
93
|
const gitFile = readFileSync(dotGit, "utf8").trim()
|
|
86
94
|
const match = /^gitdir:\s*(.+)$/m.exec(gitFile)
|
|
87
|
-
|
|
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 }
|
|
95
|
+
gitDir = match ? resolve(directory, match[1].trim()) : ""
|
|
97
96
|
}
|
|
97
|
+
if (gitDir) return pathsForGitDir(gitDir, gitDir)
|
|
98
98
|
}
|
|
99
|
+
|
|
100
|
+
// A worktree container may keep its shared repository in a sibling .bare.
|
|
101
|
+
// Its HEAD is the default branch, not the active worktree branch.
|
|
102
|
+
const bareDir = join(directory, ".bare")
|
|
103
|
+
if (isBareGitDir(bareDir)) return pathsForGitDir(bareDir, null)
|
|
104
|
+
|
|
105
|
+
// Also support opening the bare repository directory directly.
|
|
106
|
+
if (isBareGitDir(directory)) return pathsForGitDir(directory, directory)
|
|
99
107
|
} catch {
|
|
100
108
|
// A malformed marker may be inside a parent repository; keep searching.
|
|
101
109
|
}
|
|
@@ -106,13 +114,43 @@ function gitPaths(cwd: string): { gitDir: string; commonDir: string } | null {
|
|
|
106
114
|
}
|
|
107
115
|
}
|
|
108
116
|
|
|
109
|
-
|
|
117
|
+
function pathsForGitDir(gitDir: string, branchDir: string | null): GitPaths {
|
|
118
|
+
const commonDirFile = join(gitDir, "commondir")
|
|
119
|
+
const commonDir = existsSync(commonDirFile)
|
|
120
|
+
? resolve(gitDir, readFileSync(commonDirFile, "utf8").trim())
|
|
121
|
+
: gitDir
|
|
122
|
+
return { gitDir, commonDir, branchDir }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function isBareGitDir(directory: string): boolean {
|
|
126
|
+
try {
|
|
127
|
+
return (
|
|
128
|
+
statSync(directory).isDirectory() &&
|
|
129
|
+
existsSync(join(directory, "config")) &&
|
|
130
|
+
existsSync(join(directory, "HEAD")) &&
|
|
131
|
+
statSync(join(directory, "objects")).isDirectory()
|
|
132
|
+
)
|
|
133
|
+
} catch {
|
|
134
|
+
return false
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function parseGitHubRemote(
|
|
139
|
+
url: string,
|
|
140
|
+
enterpriseUrl?: string,
|
|
141
|
+
): Repo | null {
|
|
110
142
|
const remote = url.trim()
|
|
111
143
|
const configuredHost = enterpriseHostname(enterpriseUrl)
|
|
112
|
-
const supportedHosts = configuredHost
|
|
113
|
-
|
|
144
|
+
const supportedHosts = configuredHost
|
|
145
|
+
? [configuredHost]
|
|
146
|
+
: ["github.com", "ssh.github.com"]
|
|
147
|
+
const hostPattern = supportedHosts
|
|
148
|
+
.map((host) => host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
|
|
149
|
+
.join("|")
|
|
114
150
|
// Git accepts both URI-style SSH URLs and scp-style SSH URLs.
|
|
115
|
-
const scp = new RegExp(`^(?:git@)?(?:${hostPattern}):([^?#]+)$`, "i").exec(
|
|
151
|
+
const scp = new RegExp(`^(?:git@)?(?:${hostPattern}):([^?#]+)$`, "i").exec(
|
|
152
|
+
remote,
|
|
153
|
+
)
|
|
116
154
|
if (scp) return splitOwnerRepo(scp[1])
|
|
117
155
|
|
|
118
156
|
try {
|
|
@@ -123,7 +161,11 @@ export function parseGitHubRemote(url: string, enterpriseUrl?: string): Repo | n
|
|
|
123
161
|
) {
|
|
124
162
|
return null
|
|
125
163
|
}
|
|
126
|
-
if (
|
|
164
|
+
if (
|
|
165
|
+
!configuredHost &&
|
|
166
|
+
parsed.hostname.toLowerCase() === "ssh.github.com" &&
|
|
167
|
+
parsed.protocol !== "ssh:"
|
|
168
|
+
) {
|
|
127
169
|
return null
|
|
128
170
|
}
|
|
129
171
|
return splitOwnerRepo(parsed.pathname)
|
|
@@ -132,22 +174,240 @@ export function parseGitHubRemote(url: string, enterpriseUrl?: string): Repo | n
|
|
|
132
174
|
}
|
|
133
175
|
}
|
|
134
176
|
|
|
135
|
-
export function detectRepo(
|
|
177
|
+
export async function detectRepo(
|
|
136
178
|
cwd: string = process.cwd(),
|
|
137
179
|
enterpriseUrl = process.env.GITHUB_ENTERPRISE_URL,
|
|
138
|
-
|
|
180
|
+
resolveHost: SshHostResolver = sshHostName,
|
|
181
|
+
): Promise<Repo | null> {
|
|
139
182
|
const remotes = remoteUrls(cwd)
|
|
183
|
+
const rewrites = urlRewriteRules(cwd)
|
|
140
184
|
const preferred = [
|
|
141
185
|
...remotes.filter(({ name }) => name === "origin"),
|
|
142
186
|
...remotes.filter(({ name }) => name !== "origin"),
|
|
143
187
|
]
|
|
144
188
|
for (const { url } of preferred) {
|
|
145
|
-
const
|
|
189
|
+
const rewritten = rewriteRemoteUrl(url, rewrites)
|
|
190
|
+
const repo =
|
|
191
|
+
parseGitHubRemote(rewritten, enterpriseUrl) ??
|
|
192
|
+
parseGitHubRemote(await resolveSshAlias(rewritten, resolveHost), enterpriseUrl)
|
|
146
193
|
if (repo) return repo
|
|
147
194
|
}
|
|
148
195
|
return null
|
|
149
196
|
}
|
|
150
197
|
|
|
198
|
+
export async function detectPushRemoteOwner(
|
|
199
|
+
cwd: string,
|
|
200
|
+
branch: string | null,
|
|
201
|
+
enterpriseUrl = process.env.GITHUB_ENTERPRISE_URL,
|
|
202
|
+
resolveHost: SshHostResolver = sshHostName,
|
|
203
|
+
): Promise<string | null> {
|
|
204
|
+
if (!branch) return null
|
|
205
|
+
const paths = gitPaths(cwd)
|
|
206
|
+
if (!paths) return null
|
|
207
|
+
|
|
208
|
+
const branchPushRemote = readConfigValue(cwd, "branch", branch, "pushRemote")
|
|
209
|
+
const defaultPushRemote = readConfigValue(cwd, "remote", null, "pushDefault")
|
|
210
|
+
const branchRemote = readConfigValue(cwd, "branch", branch, "remote")
|
|
211
|
+
const remoteName = branchPushRemote || defaultPushRemote || branchRemote
|
|
212
|
+
if (!remoteName || remoteName === ".") return null
|
|
213
|
+
|
|
214
|
+
const rewrites = urlRewriteRules(cwd)
|
|
215
|
+
for (const { name, url } of remoteUrls(cwd)) {
|
|
216
|
+
if (name !== remoteName) continue
|
|
217
|
+
const rewritten = rewriteRemoteUrl(url, rewrites)
|
|
218
|
+
const repo =
|
|
219
|
+
parseGitHubRemote(rewritten, enterpriseUrl) ??
|
|
220
|
+
parseGitHubRemote(await resolveSshAlias(rewritten, resolveHost), enterpriseUrl)
|
|
221
|
+
if (repo) return repo.owner
|
|
222
|
+
}
|
|
223
|
+
return null
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
type UrlRewrite = { prefix: string; base: string }
|
|
227
|
+
|
|
228
|
+
function readConfigValue(
|
|
229
|
+
cwd: string,
|
|
230
|
+
section: "branch" | "remote",
|
|
231
|
+
subsection: string | null,
|
|
232
|
+
key: string,
|
|
233
|
+
): string | null {
|
|
234
|
+
const paths = gitPaths(cwd)
|
|
235
|
+
if (!paths) return null
|
|
236
|
+
const configPaths: string[] = []
|
|
237
|
+
if (process.env.GIT_CONFIG_NOSYSTEM !== "1") {
|
|
238
|
+
configPaths.push(process.env.GIT_CONFIG_SYSTEM || "/etc/gitconfig")
|
|
239
|
+
}
|
|
240
|
+
const home = homedir()
|
|
241
|
+
const xdgConfigHome = process.env.XDG_CONFIG_HOME || join(home, ".config")
|
|
242
|
+
configPaths.push(join(xdgConfigHome, "git", "config"))
|
|
243
|
+
configPaths.push(
|
|
244
|
+
process.env.GIT_CONFIG_GLOBAL || join(home, ".gitconfig"),
|
|
245
|
+
join(paths.commonDir, "config"),
|
|
246
|
+
join(paths.gitDir, "config"),
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
let value: string | null = null
|
|
250
|
+
for (const configPath of new Set(configPaths)) {
|
|
251
|
+
try {
|
|
252
|
+
if (!existsSync(configPath)) continue
|
|
253
|
+
const text = readFileSync(configPath, "utf8")
|
|
254
|
+
const escapedSubsection = subsection?.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
|
255
|
+
const sectionPattern = subsection === null
|
|
256
|
+
? new RegExp(`^\\s*\\[${section}\\]\\s*$`, "i")
|
|
257
|
+
: new RegExp(`^\\s*\\[${section}\\s+"${escapedSubsection}"\\]\\s*$`, "i")
|
|
258
|
+
const sectionRe = /^\s*\[.*\]\s*$/gm
|
|
259
|
+
let sectionMatch: RegExpExecArray | null
|
|
260
|
+
while ((sectionMatch = sectionRe.exec(text)) !== null) {
|
|
261
|
+
if (!sectionPattern.test(sectionMatch[0])) continue
|
|
262
|
+
const start = sectionRe.lastIndex
|
|
263
|
+
const nextSection = /^\s*\[/gm
|
|
264
|
+
nextSection.lastIndex = start
|
|
265
|
+
const end = nextSection.exec(text)?.index ?? text.length
|
|
266
|
+
const sectionText = text.slice(start, end)
|
|
267
|
+
const keyRe = new RegExp(`^\\s*${key}\\s*=\\s*(.*?)\\s*$`, "gim")
|
|
268
|
+
let keyMatch: RegExpExecArray | null
|
|
269
|
+
while ((keyMatch = keyRe.exec(sectionText)) !== null) {
|
|
270
|
+
value = unquoteConfigValue(keyMatch[1])
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
} catch {
|
|
274
|
+
// Missing or unreadable config scopes do not prevent branch filtering.
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return value
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function urlRewriteRules(cwd: string): UrlRewrite[] {
|
|
281
|
+
const paths = gitPaths(cwd)
|
|
282
|
+
if (!paths) return []
|
|
283
|
+
|
|
284
|
+
const configPaths: string[] = []
|
|
285
|
+
if (process.env.GIT_CONFIG_NOSYSTEM !== "1") {
|
|
286
|
+
configPaths.push(process.env.GIT_CONFIG_SYSTEM || "/etc/gitconfig")
|
|
287
|
+
}
|
|
288
|
+
const home = homedir()
|
|
289
|
+
const xdgConfigHome = process.env.XDG_CONFIG_HOME || join(home, ".config")
|
|
290
|
+
configPaths.push(join(xdgConfigHome, "git", "config"))
|
|
291
|
+
if (process.env.GIT_CONFIG_GLOBAL) {
|
|
292
|
+
configPaths.push(process.env.GIT_CONFIG_GLOBAL)
|
|
293
|
+
} else {
|
|
294
|
+
configPaths.push(join(home, ".gitconfig"))
|
|
295
|
+
}
|
|
296
|
+
configPaths.push(
|
|
297
|
+
join(paths.commonDir, "config"),
|
|
298
|
+
join(paths.gitDir, "config"),
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
const rewrites: UrlRewrite[] = []
|
|
302
|
+
for (const configPath of new Set(configPaths)) {
|
|
303
|
+
try {
|
|
304
|
+
if (!existsSync(configPath)) continue
|
|
305
|
+
const text = readFileSync(configPath, "utf8")
|
|
306
|
+
const sectionRe = /^\s*\[url\s+"((?:\\.|[^"])*)"\]\s*$/gim
|
|
307
|
+
let section: RegExpExecArray | null
|
|
308
|
+
while ((section = sectionRe.exec(text)) !== null) {
|
|
309
|
+
const start = sectionRe.lastIndex
|
|
310
|
+
const nextSection = /^\s*\[/gm
|
|
311
|
+
nextSection.lastIndex = start
|
|
312
|
+
const end = nextSection.exec(text)?.index ?? text.length
|
|
313
|
+
const base = unquoteConfigValue(`"${section[1]}"`)
|
|
314
|
+
const sectionText = text.slice(start, end)
|
|
315
|
+
const prefixRe = /^\s*insteadOf\s*=\s*(.*?)\s*$/gim
|
|
316
|
+
let prefix: RegExpExecArray | null
|
|
317
|
+
while ((prefix = prefixRe.exec(sectionText)) !== null) {
|
|
318
|
+
const value = unquoteConfigValue(prefix[1])
|
|
319
|
+
if (base && value) rewrites.push({ base, prefix: value })
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
} catch {
|
|
323
|
+
// Missing or unreadable config scopes do not prevent local detection.
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return rewrites
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function rewriteRemoteUrl(url: string, rewrites: UrlRewrite[]): string {
|
|
330
|
+
let best: UrlRewrite | null = null
|
|
331
|
+
for (const rewrite of rewrites) {
|
|
332
|
+
if (
|
|
333
|
+
url.startsWith(rewrite.prefix) &&
|
|
334
|
+
(!best || rewrite.prefix.length > best.prefix.length)
|
|
335
|
+
) {
|
|
336
|
+
best = rewrite
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return best ? `${best.base}${url.slice(best.prefix.length)}` : url
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async function resolveSshAlias(
|
|
343
|
+
url: string,
|
|
344
|
+
resolveHost: SshHostResolver,
|
|
345
|
+
): Promise<string> {
|
|
346
|
+
const scp = /^(?:([^@/:]+)@)?([A-Za-z0-9._-]+):([^?#]+)$/.exec(url)
|
|
347
|
+
if (scp && !scp[2].startsWith("-")) {
|
|
348
|
+
const hostName = scp[2].includes(".") ? null : await resolveHost(scp[2])
|
|
349
|
+
return hostName ? `${scp[1] ? `${scp[1]}@` : ""}${hostName}:${scp[3]}` : url
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
try {
|
|
353
|
+
const parsed = new URL(url)
|
|
354
|
+
if (
|
|
355
|
+
parsed.protocol !== "ssh:" ||
|
|
356
|
+
!/^[A-Za-z0-9._-]+$/.test(parsed.hostname) ||
|
|
357
|
+
parsed.hostname.startsWith("-")
|
|
358
|
+
) {
|
|
359
|
+
return url
|
|
360
|
+
}
|
|
361
|
+
const hostName = parsed.hostname.includes(".")
|
|
362
|
+
? null
|
|
363
|
+
: await resolveHost(parsed.hostname)
|
|
364
|
+
if (hostName) parsed.hostname = hostName
|
|
365
|
+
return parsed.toString()
|
|
366
|
+
} catch {
|
|
367
|
+
return url
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function sshHostName(host: string): Promise<string | null> {
|
|
372
|
+
const normalized = host.toLowerCase()
|
|
373
|
+
if (host.includes(".")) return Promise.resolve(null)
|
|
374
|
+
const cached = sshHostCache.get(normalized)
|
|
375
|
+
if (cached) return cached
|
|
376
|
+
// `ssh -G` prints effective client configuration without opening a
|
|
377
|
+
// connection. Keep execution asynchronous and bounded; public fully-qualified
|
|
378
|
+
// hostnames are not aliases and never reach this path.
|
|
379
|
+
const result = new Promise<string | null>((resolveResult) => {
|
|
380
|
+
const userConfig = join(process.env.HOME || homedir(), ".ssh", "config")
|
|
381
|
+
const args = existsSync(userConfig)
|
|
382
|
+
? ["-G", "-o", "CanonicalizeHostname=no", "-F", userConfig, host]
|
|
383
|
+
: ["-G", "-o", "CanonicalizeHostname=no", host]
|
|
384
|
+
execFile(
|
|
385
|
+
"ssh",
|
|
386
|
+
args,
|
|
387
|
+
{
|
|
388
|
+
encoding: "utf8",
|
|
389
|
+
timeout: SSH_CONFIG_TIMEOUT_MS,
|
|
390
|
+
maxBuffer: 64 * 1024,
|
|
391
|
+
windowsHide: true,
|
|
392
|
+
},
|
|
393
|
+
(error, stdout) => {
|
|
394
|
+
const match = typeof stdout === "string" ? /^hostname\s+(\S+)\s*$/im.exec(stdout) : null
|
|
395
|
+
const hostName = match?.[1]
|
|
396
|
+
const resolved =
|
|
397
|
+
!error &&
|
|
398
|
+
hostName &&
|
|
399
|
+
hostName.toLowerCase() !== normalized &&
|
|
400
|
+
/^[A-Za-z0-9.-]+$/.test(hostName)
|
|
401
|
+
? hostName
|
|
402
|
+
: null
|
|
403
|
+
resolveResult(resolved)
|
|
404
|
+
},
|
|
405
|
+
)
|
|
406
|
+
})
|
|
407
|
+
sshHostCache.set(normalized, result)
|
|
408
|
+
return result
|
|
409
|
+
}
|
|
410
|
+
|
|
151
411
|
function splitOwnerRepo(path: string): Repo | null {
|
|
152
412
|
const clean = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "")
|
|
153
413
|
const parts = clean.split("/")
|