Files
opencode-manager/shared/src/project-id-resolver.ts
T

79 lines
2.5 KiB
TypeScript

import { execFile } from 'child_process'
import { createHash } from 'crypto'
import { readFile } from 'fs/promises'
import path from 'path'
function git(cwd: string, args: string[]): Promise<string | null> {
return new Promise((resolve) => {
execFile('git', args, { cwd }, (error, stdout) => {
resolve(error ? null : stdout.trim())
})
})
}
function trimSlashes(value: string, leading: boolean, trailing: boolean): string {
let start = 0
let end = value.length
if (leading) while (start < end && value[start] === '/') start++
if (trailing) while (end > start && value[end - 1] === '/') end--
return value.slice(start, end)
}
function gitRemoteParts(host: string, name: string): string | undefined {
let pathname = trimSlashes(name, true, false)
if (pathname.endsWith('.git')) pathname = pathname.slice(0, -4)
else if (pathname.endsWith('.git/')) pathname = pathname.slice(0, -5)
pathname = trimSlashes(pathname, false, true)
if (!host || !pathname) return undefined
return `${host.toLowerCase()}/${pathname}`
}
export function normalizeGitRemote(input: string): string | undefined {
const value = input.trim()
if (!value) return undefined
try {
const parsed = new URL(value)
if (parsed.protocol === 'file:') return undefined
return gitRemoteParts(parsed.hostname, parsed.pathname)
} catch {
const scp = value.match(/^([^@/:]+@)?([^/:]+):(.+)$/)
if (scp) return gitRemoteParts(scp[2]!, scp[3]!)
return undefined
}
}
export function gitRemoteProjectId(originUrl: string): string | undefined {
const normalized = normalizeGitRemote(originUrl)
if (!normalized) return undefined
return createHash('sha1').update(`git-remote:${normalized}`).digest('hex')
}
export async function resolveOpenCodeProjectId(repoDir: string): Promise<string | null> {
const worktree = await git(repoDir, ['rev-parse', '--show-toplevel'])
if (!worktree) return null
const origin = await git(worktree, ['remote', 'get-url', 'origin'])
if (origin) {
const id = gitRemoteProjectId(origin)
if (id) return id
}
const commonDir = await git(repoDir, ['rev-parse', '--path-format=absolute', '--git-common-dir'])
if (commonDir) {
try {
const cached = (await readFile(path.join(commonDir, 'opencode'), 'utf-8')).trim()
if (cached) return cached
} catch {
}
}
const rootsOutput = await git(worktree, ['rev-list', '--max-parents=0', 'HEAD'])
if (rootsOutput) {
const root = rootsOutput.split('\n').map((line) => line.trim()).filter(Boolean).sort()[0]
if (root) return root
}
return null
}