Files
opencode-manager/shared/src/project-id-resolver.ts
T
Chris Scott 01e50a7019 feat: add bundle-based OCM mirror sync (#289)
* feat: add bundle-based OCM mirror sync

* feat: add OpenCode model editor and HEAD-safe bundle import

* fix: consolidate discovery-cache, batch bundle refs, remove dead code (#290)

* fix: consolidate discovery-cache, batch bundle refs, remove dead code

* refactor: consolidate discovery cache into generic discoverCached, extract spawnGit helper

* feat: extract project-id-resolver, add CLI full-fallback prompt, wire lint into root scripts

- Extract shared project-id-resolver for origin URL matching (replaces local-repo duplicates)
- Add promptYesNo / confirmFullFallback to ocm CLI before slow full mirror
- Backend: consolidate opencode-workspaces routes with project-id-resolver
- Frontend: fix schedules prompt/global page navigation
- CLI: add eslint config, lint/lint:fix scripts, fix no-fallthrough in ocm.ts
- Root: wire CLI into build, test, typecheck, lint, lint:fix chains
- Fix test lint issues (_code, const, require→import)

* fix: replace polynomial regex with linear-time string ops in gitRemoteParts

* feat: add divergence guards for push/pull, streaming bundle upload, server-side ancestry check

- Backend: GET /:repoId/mirror/head (head+branch+dirty) and GET /:repoId/mirror/contains/:sha (ancestry check)
- CLI: checkPushDivergence warns before overwriting server commits; checkPullDivergence warns before discarding local commits; both require confirm or --force
- Bundle upload now streams from disk instead of buffering entire file in memory
- Version visible in --help and default (no-arg) output
- Version bump 0.1.5 → 0.2.0

* fix: show connecting message before fetching repos in default command

* fix: update default command messages to reflect actual matching behavior
2026-06-28 11:57:38 -04:00

95 lines
3.2 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}`
}
/**
* Normalizes a git remote URL into OpenCode's `host/path` identity form, or
* returns undefined for unsupported remotes (e.g. `file:` URLs). Mirrors the
* normalization in OpenCode's `ProjectV2.resolve`.
*/
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
}
}
/**
* Computes the OpenCode remote-backed project ID for a git origin URL, or
* undefined when the remote cannot be normalized.
*/
export function gitRemoteProjectId(originUrl: string): string | undefined {
const normalized = normalizeGitRemote(originUrl)
if (!normalized) return undefined
return createHash('sha1').update(`git-remote:${normalized}`).digest('hex')
}
/**
* Resolves the OpenCode project ID for a git working directory using the same
* precedence OpenCode applies: normalized origin remote hash, then the cached
* `<git-common-dir>/opencode` id, then the sorted first root commit. Returns
* null when the directory is not a git repository or no id can be derived.
*/
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 {
// cache file absent or unreadable
}
}
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
}