feat(ocm-cli): workspace repo sync and manager token targeting (#233)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-23 19:49:44 -04:00
1 parent e12f319592
commit a86e4b1238
69 files changed
+4858 -161

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
import { spawnSync } from 'child_process'
const SERVICE = 'opencode-manager'
export class KeychainError extends Error {
constructor(message: string, public exitCode: number | null) {
super(message)
this.name = 'KeychainError'
}
}
function runSecurity(args: string[], input?: string): { stdout: string; stderr: string; code: number | null } {
const res = spawnSync('security', args, {
input,
encoding: 'utf-8',
})
return { stdout: res.stdout ?? '', stderr: res.stderr ?? '', code: res.status }
}
export function setToken(account: string, token: string): void {
const res = runSecurity([
'add-generic-password',
'-s', SERVICE,
'-a', account,
'-w', token,
'-U',
])
if (res.code !== 0) {
throw new KeychainError(`Failed to store token in Keychain: ${res.stderr.trim()}`, res.code)
}
}
export function getToken(account: string): string | null {
const res = runSecurity([
'find-generic-password',
'-s', SERVICE,
'-a', account,
'-w',
])
if (res.code !== 0) return null
return res.stdout.trim() || null
}
export function deleteToken(account: string): boolean {
const res = runSecurity([
'delete-generic-password',
'-s', SERVICE,
'-a', account,
])
return res.code === 0
}
+45
View File
@@ -0,0 +1,45 @@
import { spawnSync } from 'child_process'
function git(cwd: string, args: string[]): string | null {
const res = spawnSync('git', args, { cwd, encoding: 'utf-8' })
if (res.status !== 0) return null
return (res.stdout ?? '').trim()
}
export function getRepoRoot(cwd: string): string | null {
return git(cwd, ['rev-parse', '--show-toplevel'])
}
export function getOriginUrl(dir: string): string | null {
return git(dir, ['remote', 'get-url', 'origin'])
}
export function getDirtyPaths(dir: string): Set<string> {
const out = git(dir, ['status', '--porcelain', '-z', '--untracked-files=all'])
if (!out) return new Set()
const paths = new Set<string>()
for (const record of out.split('\0')) {
if (!record) continue
const path = record.slice(3)
if (path) paths.add(path)
}
return paths
}
function normalizeUrl(url: string): string {
return url
.trim()
.replace(/\.git$/, '')
.replace(/^git@([^:]+):/, 'ssh://git@$1/')
.replace(/\/+$/, '')
.toLowerCase()
}
export function getBranchName(dir: string): string | null {
return git(dir, ['rev-parse', '--abbrev-ref', 'HEAD'])
}
export function urlsEqual(a: string | null | undefined, b: string | null | undefined): boolean {
if (!a || !b) return false
return normalizeUrl(a) === normalizeUrl(b)
}
+50
View File
@@ -0,0 +1,50 @@
export class ManagerApi {
constructor(
private baseUrl: string,
private token: string,
) {}
private headers(extra: Record<string, string> = {}): Record<string, string> {
return { Authorization: `Bearer ${this.token}`, ...extra }
}
async mirrorUp(
repoId: number,
body: ReadableStream<Uint8Array>,
opts: { force?: boolean; create?: { name: string; originUrl: string | null; branch: string | null } },
): Promise<{ repoId: number; branch: string; head: string; created: boolean }> {
const params = new URLSearchParams()
if (opts.force) params.set('force', '1')
if (opts.create) {
params.set('create', '1')
params.set('name', opts.create.name)
if (opts.create.originUrl) params.set('originUrl', opts.create.originUrl)
if (opts.create.branch) params.set('branch', opts.create.branch)
}
const qs = params.toString() ? `?${params.toString()}` : ''
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror${qs}`
const res = await fetch(url, {
method: 'POST',
headers: {
...this.headers(),
'Content-Type': 'application/x-tar',
},
body,
duplex: 'half',
} as RequestInit & { duplex: 'half' })
if (!res.ok) throw new Error(`mirror ${res.status}: ${await res.text()}`)
return (await res.json()) as { repoId: number; branch: string; head: string; created: boolean }
}
async mirrorDown(repoId: number): Promise<ReadableStream<Uint8Array>> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror`, {
headers: this.headers(),
})
if (!res.ok) throw new Error(`mirror ${res.status}: ${await res.text()}`)
return res.body!
}
}
+179
View File
@@ -0,0 +1,179 @@
import { spawnSync, spawn } from 'child_process'
import { existsSync } from 'fs'
import * as fsp from 'fs/promises'
import { Readable } from 'stream'
import { join } from 'path'
import { tmpdir } from 'os'
import { getRepoRoot, getOriginUrl, getDirtyPaths, urlsEqual } from './local-repo.js'
import type { ManagerApi } from './manager-api.js'
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo']
function getGitignoreExclusions(repoRoot: string): string[] {
const res = spawnSync('git', ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'], {
cwd: repoRoot,
encoding: 'utf-8',
})
if (res.status !== 0) return []
return (res.stdout ?? '').split('\n').filter((line) => line.length > 0)
}
export class MirrorAbort extends Error {
constructor(message: string) {
super(message)
this.name = 'MirrorAbort'
}
}
export interface RemoteRepoSummary {
repoId: number
name: string
originUrl: string | null
branch: string | null
}
export interface MirrorPlan {
repoRoot: string
localOrigin: string
matched: RemoteRepoSummary[]
}
export function prepareMirror(cwd: string, remotes: RemoteRepoSummary[]): MirrorPlan {
const repoRoot = getRepoRoot(cwd)
if (!repoRoot) throw new MirrorAbort('not in a git repository')
const localOrigin = getOriginUrl(repoRoot)
if (!localOrigin) throw new MirrorAbort('no origin URL found')
const matched = remotes.filter((r) => urlsEqual(localOrigin, r.originUrl))
return { repoRoot, localOrigin, matched }
}
export interface MirrorUpOpts {
api: ManagerApi
force: boolean
create?: { name: string; originUrl: string | null; branch: string | null }
}
export async function mirrorUp(
plan: MirrorPlan,
opts: MirrorUpOpts,
): Promise<{ repoId: number; branch: string; head: string; created: boolean }> {
const tarArgs = ['-c', '-C', plan.repoRoot]
for (const dir of HARDCODED_EXCLUDES) tarArgs.push('--exclude', dir)
const ignoredPaths = getGitignoreExclusions(plan.repoRoot)
let excludeFile: string | null = null
if (ignoredPaths.length > 0) {
excludeFile = join(tmpdir(), `ocm-exclude-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`)
await fsp.writeFile(excludeFile, ignoredPaths.join('\n'))
tarArgs.push('--exclude-from', excludeFile)
}
tarArgs.push('.')
const child = spawn('tar', tarArgs, { stdio: ['pipe', 'pipe', 'pipe'] })
const stderrChunks: Buffer[] = []
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
const tarExit = new Promise<void>((resolve, reject) => {
child.on('close', (code) => {
if (code === 0) resolve()
else {
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ''}`))
}
})
child.on('error', reject)
})
const body = Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>
const repoId = opts.create ? 0 : plan.matched[0]!.repoId
try {
const [result] = await Promise.all([
opts.api.mirrorUp(repoId, body, {
force: opts.force,
create: opts.create,
}),
tarExit,
])
return result
} finally {
if (excludeFile) {
await fsp.rm(excludeFile, { force: true }).catch(() => {})
}
}
}
export async function mirrorDown(
repoId: number,
repoRoot: string,
api: ManagerApi,
opts: { force: boolean } = { force: false },
): Promise<void> {
if (!opts.force && getDirtyPaths(repoRoot).size > 0) {
throw new MirrorAbort('working tree has uncommitted changes; rerun with --force')
}
const staging = `${repoRoot}.ocm-recv-${Date.now()}`
await fsp.mkdir(staging, { recursive: true })
try {
const tarball = await api.mirrorDown(repoId)
const child = spawn('tar', ['-x', '-f', '-', '-C', staging], { stdio: ['pipe', 'pipe', 'pipe'] })
const stderrChunks: Buffer[] = []
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
const tarDone = new Promise<void>((resolve, reject) => {
child.on('close', (code) => {
if (code === 0) resolve()
else {
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ''}`))
}
})
child.on('error', reject)
})
const stdinWritable = Readable.fromWeb(tarball as unknown as Parameters<typeof Readable.fromWeb>[0])
stdinWritable.pipe(child.stdin)
await tarDone
const backupDir = `${repoRoot}.ocm-backup-${Date.now()}`
await fsp.mkdir(backupDir, { recursive: true })
if (existsSync(repoRoot)) {
const entries = await fsp.readdir(repoRoot)
for (const entry of entries) {
await fsp.rename(join(repoRoot, entry), join(backupDir, entry))
}
}
try {
const stagingEntries = await fsp.readdir(staging)
for (const entry of stagingEntries) {
await fsp.rename(join(staging, entry), join(repoRoot, entry))
}
await fsp.rm(backupDir, { recursive: true, force: true }).catch(() => {})
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
} catch (swapError) {
const backupEntries = await fsp.readdir(backupDir).catch(() => [])
for (const entry of backupEntries) {
await fsp.rename(join(backupDir, entry), join(repoRoot, entry)).catch(() => {})
}
await fsp.rm(backupDir, { recursive: true, force: true }).catch(() => {})
throw swapError
}
} catch (error) {
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {})
throw error
}
}
+59
View File
@@ -0,0 +1,59 @@
import { mkdirSync, symlinkSync, lstatSync, readlinkSync, unlinkSync, existsSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const OCM_TARGET = join(PACKAGE_ROOT, 'dist', 'ocm.js')
const BIN_DIR = join(homedir(), '.local', 'bin')
const BIN_LINK = join(BIN_DIR, 'ocm')
function ensureSymlink(): { installed: boolean; message?: string } {
if (!existsSync(OCM_TARGET)) {
return { installed: false, message: `ocm-cli: missing ${OCM_TARGET}, skipping bin install` }
}
try {
chmodSync(OCM_TARGET, 0o755)
} catch {
// best effort
}
try {
mkdirSync(BIN_DIR, { recursive: true })
} catch (err) {
return { installed: false, message: `ocm-cli: cannot create ${BIN_DIR}: ${(err as Error).message}` }
}
try {
const stat = lstatSync(BIN_LINK)
if (stat.isSymbolicLink()) {
if (readlinkSync(BIN_LINK) === OCM_TARGET) {
return { installed: false }
}
unlinkSync(BIN_LINK)
} else {
return { installed: false, message: `ocm-cli: ${BIN_LINK} exists and is not a symlink; leaving alone` }
}
} catch {
// missing — fine
}
try {
symlinkSync(OCM_TARGET, BIN_LINK)
} catch (err) {
return { installed: false, message: `ocm-cli: failed to symlink ${BIN_LINK}: ${(err as Error).message}` }
}
const onPath = (process.env.PATH ?? '').split(':').includes(BIN_DIR)
const pathHint = onPath ? '' : ` (add "${BIN_DIR}" to your PATH to run \`ocm\`)`
return { installed: true, message: `ocm-cli: installed \`ocm\` at ${BIN_LINK}${pathHint}` }
}
const result = ensureSymlink()
if (result.message) {
process.stderr.write(`${result.message}\n`)
}
const plugin = async (): Promise<Record<string, never>> => ({})
export default plugin
+51
View File
@@ -0,0 +1,51 @@
import { getRepoRoot, getOriginUrl, urlsEqual } from './local-repo.js'
export interface TargetRepo {
repoId: number
name: string
branch: string | null
directory: string
originUrl?: string | null
}
export type ResolveResult =
| { kind: 'cwd-match'; repo: TargetRepo; repoRoot: string }
| { kind: 'last'; repo: TargetRepo }
| { kind: 'cwd-ambiguous'; matches: TargetRepo[]; localOrigin: string; repoRoot: string }
| { kind: 'local'; reason: 'no-match' | 'no-target'; repoRoot: string | null }
export interface ResolveInput {
cwd: string
repos: TargetRepo[]
last?: { repoId: number; name: string; directory: string; branch: string | null }
}
export function resolveTarget(input: ResolveInput): ResolveResult {
const repoRoot = getRepoRoot(input.cwd)
const localOrigin = repoRoot ? getOriginUrl(repoRoot) : null
if (repoRoot && localOrigin) {
const matches = input.repos.filter((r) => urlsEqual(localOrigin, r.originUrl))
if (matches.length === 1) {
return { kind: 'cwd-match', repo: matches[0]!, repoRoot }
}
if (matches.length > 1) {
return { kind: 'cwd-ambiguous', matches, localOrigin, repoRoot }
}
return { kind: 'local', reason: 'no-match', repoRoot }
}
if (input.last) {
return { kind: 'last', repo: toTarget(input.last) }
}
return { kind: 'local', reason: 'no-target', repoRoot }
}
function toTarget(last: NonNullable<ResolveInput['last']>): TargetRepo {
return {
repoId: last.repoId,
name: last.name,
branch: last.branch,
directory: last.directory,
}
}
+43
View File
@@ -0,0 +1,43 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import { homedir } from 'os'
import { dirname, join } from 'path'
export interface OcmState {
managerUrl: string
lastRepoId?: number
lastRepoName?: string
lastRepoDir?: string
lastRepoBranch?: string | null
updatedAt?: number
}
const STATE_DIR = join(homedir(), '.config', 'opencode-manager')
const STATE_FILE = join(STATE_DIR, 'state.json')
export function getStatePath(): string {
return STATE_FILE
}
export function readState(): OcmState | null {
if (!existsSync(STATE_FILE)) return null
try {
const raw = readFileSync(STATE_FILE, 'utf-8')
const parsed = JSON.parse(raw) as OcmState
if (!parsed.managerUrl) return null
return parsed
} catch {
return null
}
}
export function writeState(state: OcmState): void {
mkdirSync(dirname(STATE_FILE), { recursive: true })
const next: OcmState = { ...state, updatedAt: Date.now() }
writeFileSync(STATE_FILE, JSON.stringify(next, null, 2), { mode: 0o600 })
}
export function clearState(): void {
if (existsSync(STATE_FILE)) {
writeFileSync(STATE_FILE, '{}', { mode: 0o600 })
}
}