opencode-github-pr 0.0.0-stage → 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.
@@ -0,0 +1,416 @@
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 { execFile } from "node:child_process"
9
+ import { homedir } from "node:os"
10
+ import { join, resolve } from "node:path"
11
+ import type { Repo } from "../domain/types"
12
+ import { enterpriseHostname } from "./github-enterprise"
13
+
14
+ export type { Repo }
15
+
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>
20
+
21
+ export function currentBranch(cwd: string): string | null {
22
+ const paths = gitPaths(cwd)
23
+ if (!paths?.branchDir) return null
24
+ try {
25
+ const headPath = join(paths.branchDir, "HEAD")
26
+ if (!existsSync(headPath)) return null
27
+ const head = readFileSync(headPath, "utf8").trim()
28
+ if (!head.startsWith(HEAD_REF_PREFIX)) return null
29
+ return head.slice(HEAD_REF_PREFIX.length) || null
30
+ } catch {
31
+ return null
32
+ }
33
+ }
34
+
35
+ function remoteUrls(cwd: string): Array<{ name: string; url: string }> {
36
+ const paths = gitPaths(cwd)
37
+ if (!paths) return []
38
+ for (const configPath of new Set([
39
+ join(paths.commonDir, "config"),
40
+ join(paths.gitDir, "config"),
41
+ ])) {
42
+ try {
43
+ if (!existsSync(configPath)) continue
44
+ const text = readFileSync(configPath, "utf8")
45
+ const remotes: Array<{ name: string; url: string }> = []
46
+ const sectionRe = /^\s*\[remote\s+"([^"]+)"\]\s*$/gim
47
+ let section: RegExpExecArray | null
48
+
49
+ while ((section = sectionRe.exec(text)) !== null) {
50
+ const start = sectionRe.lastIndex
51
+ const nextSection = /^\s*\[/gm
52
+ nextSection.lastIndex = start
53
+ const end = nextSection.exec(text)?.index ?? text.length
54
+ const sectionText = text.slice(start, end)
55
+ const urlRe = /^\s*url\s*=\s*(.*?)\s*$/gim
56
+ let urlMatch: RegExpExecArray | null
57
+ while ((urlMatch = urlRe.exec(sectionText)) !== null) {
58
+ const url = unquoteConfigValue(urlMatch[1])
59
+ if (url) remotes.push({ name: section[1], url })
60
+ }
61
+ }
62
+
63
+ if (remotes.length) return remotes
64
+ } catch {
65
+ // Try the other config location, or let callers report no repository.
66
+ }
67
+ }
68
+ return []
69
+ }
70
+
71
+ function unquoteConfigValue(value: string): string {
72
+ const trimmed = value.trim()
73
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
74
+ return trimmed.slice(1, -1).replace(/\\(["\\])/g, "$1")
75
+ }
76
+ return trimmed
77
+ }
78
+
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.
84
+ let directory = resolve(cwd)
85
+ while (true) {
86
+ try {
87
+ const dotGit = join(directory, ".git")
88
+ if (existsSync(dotGit)) {
89
+ let gitDir: string
90
+ if (statSync(dotGit).isDirectory()) {
91
+ gitDir = dotGit
92
+ } else {
93
+ const gitFile = readFileSync(dotGit, "utf8").trim()
94
+ const match = /^gitdir:\s*(.+)$/m.exec(gitFile)
95
+ gitDir = match ? resolve(directory, match[1].trim()) : ""
96
+ }
97
+ if (gitDir) return pathsForGitDir(gitDir, gitDir)
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)
107
+ } catch {
108
+ // A malformed marker may be inside a parent repository; keep searching.
109
+ }
110
+
111
+ const parent = resolve(directory, "..")
112
+ if (parent === directory) return null
113
+ directory = parent
114
+ }
115
+ }
116
+
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 {
142
+ const remote = url.trim()
143
+ const configuredHost = enterpriseHostname(enterpriseUrl)
144
+ const supportedHosts = configuredHost
145
+ ? [configuredHost]
146
+ : ["github.com", "ssh.github.com"]
147
+ const hostPattern = supportedHosts
148
+ .map((host) => host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
149
+ .join("|")
150
+ // Git accepts both URI-style SSH URLs and scp-style SSH URLs.
151
+ const scp = new RegExp(`^(?:git@)?(?:${hostPattern}):([^?#]+)$`, "i").exec(
152
+ remote,
153
+ )
154
+ if (scp) return splitOwnerRepo(scp[1])
155
+
156
+ try {
157
+ const parsed = new URL(remote)
158
+ if (
159
+ !supportedHosts.includes(parsed.hostname.toLowerCase()) ||
160
+ !["https:", "http:", "ssh:"].includes(parsed.protocol)
161
+ ) {
162
+ return null
163
+ }
164
+ if (
165
+ !configuredHost &&
166
+ parsed.hostname.toLowerCase() === "ssh.github.com" &&
167
+ parsed.protocol !== "ssh:"
168
+ ) {
169
+ return null
170
+ }
171
+ return splitOwnerRepo(parsed.pathname)
172
+ } catch {
173
+ return null
174
+ }
175
+ }
176
+
177
+ export async function detectRepo(
178
+ cwd: string = process.cwd(),
179
+ enterpriseUrl = process.env.GITHUB_ENTERPRISE_URL,
180
+ resolveHost: SshHostResolver = sshHostName,
181
+ ): Promise<Repo | null> {
182
+ const remotes = remoteUrls(cwd)
183
+ const rewrites = urlRewriteRules(cwd)
184
+ const preferred = [
185
+ ...remotes.filter(({ name }) => name === "origin"),
186
+ ...remotes.filter(({ name }) => name !== "origin"),
187
+ ]
188
+ for (const { url } of preferred) {
189
+ const rewritten = rewriteRemoteUrl(url, rewrites)
190
+ const repo =
191
+ parseGitHubRemote(rewritten, enterpriseUrl) ??
192
+ parseGitHubRemote(await resolveSshAlias(rewritten, resolveHost), enterpriseUrl)
193
+ if (repo) return repo
194
+ }
195
+ return null
196
+ }
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
+
411
+ function splitOwnerRepo(path: string): Repo | null {
412
+ const clean = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "")
413
+ const parts = clean.split("/")
414
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return null
415
+ return { owner: parts[0], repo: parts[1] }
416
+ }
@@ -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
+ }