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

+420
View File
@@ -0,0 +1,420 @@
import { spawn, spawnSync } from 'child_process'
import { basename } from 'path'
import { readState, writeState, clearState, getStatePath, type OcmState } from '../src/state.js'
import { getToken, setToken, deleteToken, KeychainError } from '../src/keychain.js'
import { ManagerApi } from '../src/manager-api.js'
import { mirrorUp, mirrorDown, prepareMirror } from '../src/mirror.js'
import type { RemoteRepoSummary } from '../src/mirror.js'
import { getBranchName } from '../src/local-repo.js'
import { resolveTarget } from '../src/resolve-target.js'
const USAGE = `ocm - OpenCode Manager workspace launcher
Usage:
ocm Attach to the Manager repo matching $PWD's git origin,
fall back to the last selected repo, or launch local
opencode when no Manager target applies
ocm login <url> [token] Save manager URL + token (token via stdin if omitted)
ocm logout Forget saved token (Keychain) and state
ocm status Show current manager URL, repo, and whether token is set
ocm list List ready repos from the manager
ocm use <repoId|name> Attach to a specific repo and remember it as last
ocm push [--force] [--create] [--yes] Mirror $PWD to the matching Manager repo (or create one)
ocm pull [--force] Mirror the matching Manager repo over $PWD
ocm --help Show this help
`
interface ManagerRepo {
repoId: number
name: string
branch: string | null
cloneStatus: string
directory: string
originUrl?: string | null
extra: { repoId: number; localPath: string; fullPath: string }
}
function die(msg: string, code = 1): never {
process.stderr.write(`ocm: ${msg}\n`)
process.exit(code)
}
function info(msg: string): void {
process.stdout.write(`${msg}\n`)
}
function requireState(): OcmState {
const state = readState()
if (!state || !state.managerUrl) {
die(`no manager configured. Run \`ocm login <url>\` first.`)
}
return state
}
function requireToken(state: OcmState): string {
const token = getToken(state.managerUrl)
if (!token) {
die(`no token in Keychain for ${state.managerUrl}. Run \`ocm login ${state.managerUrl}\`.`)
}
return token
}
async function fetchRepos(managerUrl: string, token: string): Promise<ManagerRepo[]> {
const res = await fetch(`${managerUrl}/api/internal/opencode-workspaces`, {
headers: { Authorization: `Bearer ${token}` },
})
if (!res.ok) {
throw new Error(`manager responded ${res.status} ${res.statusText}`)
}
const data = (await res.json()) as { workspaces: ManagerRepo[] }
return data.workspaces
}
function attach(managerUrl: string, token: string, repo: ManagerRepo): never {
const proxyUrl = `${managerUrl}/api/opencode-proxy`
const args = [
'attach',
proxyUrl,
'--dir', repo.directory,
'--password', token,
'--username', 'opencode',
]
const child = spawn('opencode', args, { stdio: 'inherit' })
child.on('close', (code) => process.exit(code ?? 0))
child.on('error', (err) => die(`failed to spawn opencode: ${err.message}`))
// hand control to child
return undefined as never
}
function findRepo(repos: ManagerRepo[], needle: string | number): ManagerRepo | undefined {
if (typeof needle === 'number') {
return repos.find((r) => r.repoId === needle)
}
const asNum = Number(needle)
if (!Number.isNaN(asNum)) {
const byId = repos.find((r) => r.repoId === asNum)
if (byId) return byId
}
return repos.find((r) => r.name === needle) ?? repos.find((r) => r.name.toLowerCase() === needle.toLowerCase())
}
async function cmdLogin(args: string[]): Promise<void> {
const url = args[0]
if (!url) die('usage: ocm login <url> [token]')
const normalisedUrl = url.replace(/\/+$/, '')
let token = args[1]
if (!token) {
if (process.stdin.isTTY) {
process.stderr.write('Paste token (input hidden): ')
const res = spawnSync('bash', ['-c', 'read -s LINE && printf "%s" "$LINE"'], {
stdio: ['inherit', 'pipe', 'inherit'],
encoding: 'utf-8',
})
process.stderr.write('\n')
token = (res.stdout ?? '').trim()
} else {
token = await new Promise<string>((resolve) => {
const chunks: Buffer[] = []
process.stdin.on('data', (c) => chunks.push(c))
process.stdin.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8').trim()))
})
}
}
if (!token) die('no token provided')
try {
setToken(normalisedUrl, token)
} catch (err) {
if (err instanceof KeychainError) die(`Keychain error: ${err.message}`)
throw err
}
const existing = readState()
writeState({
...existing,
managerUrl: normalisedUrl,
})
info(`Saved token for ${normalisedUrl} in Keychain.`)
info(`State file: ${getStatePath()}`)
}
async function cmdLogout(): Promise<void> {
const state = readState()
if (!state || !state.managerUrl) {
info('Nothing to log out from.')
return
}
const deleted = deleteToken(state.managerUrl)
clearState()
info(deleted ? `Removed Keychain entry for ${state.managerUrl}.` : `No Keychain entry found.`)
info('State cleared.')
}
async function cmdStatus(): Promise<void> {
const state = readState()
if (!state) {
info('no state. run: ocm login <url>')
return
}
info(`manager url: ${state.managerUrl}`)
info(`token in kc: ${getToken(state.managerUrl) ? 'yes' : 'no'}`)
if (state.lastRepoId !== undefined) {
info(`last repo: ${state.lastRepoName} (id=${state.lastRepoId}, branch=${state.lastRepoBranch ?? 'n/a'})`)
info(`last repo dir: ${state.lastRepoDir}`)
} else {
info('last repo: (none)')
}
info(`state file: ${getStatePath()}`)
}
async function cmdList(): Promise<void> {
const state = requireState()
const token = requireToken(state)
const repos = await fetchRepos(state.managerUrl, token)
if (repos.length === 0) {
info('No ready repos.')
return
}
const idWidth = Math.max(...repos.map((r) => String(r.repoId).length))
const nameWidth = Math.max(...repos.map((r) => r.name.length))
for (const r of repos) {
const id = String(r.repoId).padStart(idWidth)
const name = r.name.padEnd(nameWidth)
const branch = r.branch ? ` (${r.branch})` : ''
info(`${id} ${name} ${r.cloneStatus}${branch}`)
}
}
async function cmdUse(args: string[]): Promise<void> {
const needle = args[0]
if (!needle) die('usage: ocm use <repoId|name>')
const state = requireState()
const token = requireToken(state)
const repos = await fetchRepos(state.managerUrl, token)
const repo = findRepo(repos, needle)
if (!repo) die(`repo not found: ${needle}`)
writeState({
...state,
lastRepoId: repo.repoId,
lastRepoName: repo.name,
lastRepoDir: repo.directory,
lastRepoBranch: repo.branch,
})
attach(state.managerUrl, token, repo)
}
async function cmdDefault(): Promise<void> {
const state = requireState()
const token = requireToken(state)
const last = state.lastRepoId !== undefined && state.lastRepoDir
? {
repoId: state.lastRepoId,
name: state.lastRepoName ?? `repo-${state.lastRepoId}`,
directory: state.lastRepoDir,
branch: state.lastRepoBranch ?? null,
}
: undefined
const repos = await fetchRepos(state.managerUrl, token)
const result = resolveTarget({ cwd: process.cwd(), repos, last })
switch (result.kind) {
case 'cwd-match': {
const repo = result.repo
info(`attaching to ${repo.name} (matched $PWD origin)`)
writeState({
...state,
lastRepoId: repo.repoId,
lastRepoName: repo.name,
lastRepoDir: repo.directory,
lastRepoBranch: repo.branch,
})
attach(state.managerUrl, token, toManagerRepo(repo))
return
}
case 'last':
attach(state.managerUrl, token, toManagerRepo(result.repo))
return
case 'cwd-ambiguous': {
const names = result.matches.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
die(`multiple Manager repos match origin ${result.localOrigin}: ${names}; disambiguate with \`ocm use <repoId>\``)
}
case 'local':
runLocalOpencode(result.reason)
return
}
}
function runLocalOpencode(reason: 'no-match' | 'no-target'): never {
const message = reason === 'no-match'
? 'no Manager repo matches $PWD; launching local opencode'
: 'no last repo; launching local opencode'
process.stderr.write(`ocm: ${message}\n`)
const child = spawn('opencode', [], { stdio: 'inherit' })
child.on('close', (code) => process.exit(code ?? 0))
child.on('error', (err) => die(`failed to spawn opencode: ${err.message}`))
return undefined as never
}
function toManagerRepo(repo: { repoId: number; name: string; branch: string | null; directory: string }): ManagerRepo {
return {
repoId: repo.repoId,
name: repo.name,
branch: repo.branch,
cloneStatus: 'ready',
directory: repo.directory,
extra: { repoId: repo.repoId, localPath: '', fullPath: repo.directory },
}
}
export async function cmdPush(args: string[]): Promise<void> {
let force = false
let create = false
let yes = false
for (const arg of args) {
if (arg === '--force') force = true
else if (arg === '--create') create = true
else if (arg === '--yes') yes = true
}
const state = requireState()
const token = requireToken(state)
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
const remotes: RemoteRepoSummary[] = repos.map((r) => ({
repoId: r.repoId,
name: r.name,
originUrl: r.originUrl ?? null,
branch: r.branch,
}))
const plan = prepareMirror(process.cwd(), remotes)
if (plan.matched.length === 0) {
if (!create) {
die(`no matching Manager repo for origin ${plan.localOrigin}. Re-run with --create to create one.`)
}
const name = basename(plan.repoRoot)
const branch = getBranchName(plan.repoRoot)
if (process.stdin.isTTY && !yes) {
process.stderr.write(`Create Manager repo "${name}" by uploading ${plan.repoRoot} (origin: ${plan.localOrigin})? [y/N] `)
const res = spawnSync('bash', ['-c', 'read LINE && printf "%s" "$LINE"'], {
stdio: ['inherit', 'pipe', 'inherit'],
encoding: 'utf-8',
})
const answer = (res.stdout ?? '').trim().toLowerCase()
if (answer !== 'y' && answer !== 'yes') {
die('aborted')
}
} else if (!process.stdin.isTTY && !yes) {
die('stdin is not a TTY; pass --yes to confirm creation')
}
const result = await mirrorUp(plan, {
api,
force,
create: { name, originUrl: plan.localOrigin, branch },
})
info(`pushed ${plan.repoRoot} -> ${result.created ? 'created' : 'updated'} (repoId=${result.repoId}, branch=${result.branch})`)
} else if (plan.matched.length === 1) {
const result = await mirrorUp(plan, { api, force })
info(`pushed ${plan.repoRoot} -> ${plan.matched[0]!.name} (repoId=${result.repoId}, branch=${result.branch})`)
} else {
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
die(`multiple Manager repos match origin ${plan.localOrigin}: ${names}; disambiguate with \`ocm push <repoId>\``)
}
}
async function cmdPull(args: string[]): Promise<void> {
let force = false
for (const arg of args) {
if (arg === '--force') force = true
}
const state = requireState()
const token = requireToken(state)
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
const remotes: RemoteRepoSummary[] = repos.map((r) => ({
repoId: r.repoId,
name: r.name,
originUrl: r.originUrl ?? null,
branch: r.branch,
}))
const plan = prepareMirror(process.cwd(), remotes)
if (plan.matched.length === 0) {
die(`no matching Manager repo for origin ${plan.localOrigin}.`)
}
if (plan.matched.length > 1) {
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
die(`multiple Manager repos match origin ${plan.localOrigin}: ${names}; disambiguate with \`ocm pull <repoId>\``)
}
await mirrorDown(plan.matched[0]!.repoId, plan.repoRoot, api, { force })
info(`pulled ${plan.matched[0]!.name} -> ${plan.repoRoot}`)
}
async function main(): Promise<void> {
const [, , cmd, ...rest] = process.argv
if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
process.stdout.write(USAGE)
return
}
try {
switch (cmd) {
case undefined:
await cmdDefault()
break
case 'login':
await cmdLogin(rest)
break
case 'logout':
await cmdLogout()
break
case 'status':
await cmdStatus()
break
case 'list':
case 'ls':
await cmdList()
break
case 'use':
case 'attach':
await cmdUse(rest)
break
case 'push':
await cmdPush(rest)
break
case 'pull':
await cmdPull(rest)
break
default:
die(`unknown command: ${cmd}. run \`ocm --help\``)
}
} catch (err) {
die(err instanceof Error ? err.message : String(err))
}
}
// Only run main when executed directly (not imported by tests).
const entryUrl = process.argv[1] ? `file://${process.argv[1]}` : ''
if (entryUrl === import.meta.url || process.argv[1]?.endsWith('/ocm.js') || process.argv[1]?.endsWith('/ocm')) {
void main()
}
+39
View File
@@ -0,0 +1,39 @@
{
"name": "@opencode-manager/ocm-cli",
"version": "0.1.0",
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/chriswritescode-dev/opencode-manager.git",
"directory": "ocm-cli"
},
"type": "module",
"main": "./dist/plugin.js",
"exports": {
".": {
"import": "./dist/plugin.js"
}
},
"bin": {
"ocm": "./dist/ocm.js"
},
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "bun scripts/build.ts",
"postinstall": "node scripts/postinstall.mjs || true",
"typecheck": "tsc --noEmit",
"test": "bun scripts/build.ts && vitest run",
"test:watch": "vitest",
"prepublishOnly": "bun scripts/build.ts"
},
"dependencies": {},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.5.0",
"vitest": "^3.1.0"
}
}
+47
View File
@@ -0,0 +1,47 @@
import { chmodSync, writeFileSync, rmSync, readFileSync } from 'fs'
import { join } from 'path'
const root = join(import.meta.dir, '..')
const dist = join(root, 'dist')
rmSync(dist, { recursive: true, force: true })
console.log('Bundling ocm CLI...')
const cliResult = await Bun.build({
entrypoints: [join(root, 'bin', 'ocm.ts')],
outdir: dist,
target: 'node',
format: 'esm',
naming: { entry: 'ocm.js' },
})
if (!cliResult.success) {
for (const log of cliResult.logs) {
console.error(log)
}
process.exit(1)
}
console.log('Bundling opencode plugin entry...')
const pluginResult = await Bun.build({
entrypoints: [join(root, 'src', 'plugin.ts')],
outdir: dist,
target: 'node',
format: 'esm',
naming: { entry: 'plugin.js' },
})
if (!pluginResult.success) {
for (const log of pluginResult.logs) {
console.error(log)
}
process.exit(1)
}
const ocmJsPath = join(dist, 'ocm.js')
const ocmJsContent = readFileSync(ocmJsPath, 'utf-8')
const withoutShebang = ocmJsContent.startsWith('#!') ? ocmJsContent.slice(ocmJsContent.indexOf('\n') + 1) : ocmJsContent
writeFileSync(ocmJsPath, `#!/usr/bin/env node\n${withoutShebang}`)
chmodSync(ocmJsPath, 0o755)
console.log('Build complete')
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env node
import { existsSync, mkdirSync, symlinkSync, unlinkSync, lstatSync, readlinkSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
import { join, resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const target = join(root, 'dist', 'ocm.js')
if (!existsSync(target)) {
// dist not built yet — silently skip
process.exit(0)
}
try {
chmodSync(target, 0o755)
} catch {
// best effort
}
// If installed via `npm i -g` / `bun add -g`, the binary is already linked
// by the package manager via the `bin` field. Only do the ~/.local/bin
// symlink for local workspace installs.
if (process.env.npm_config_global === 'true' || process.env.npm_config_global === true) {
process.exit(0)
}
const binDir = join(homedir(), '.local', 'bin')
try {
mkdirSync(binDir, { recursive: true })
} catch (err) {
process.stderr.write(`ocm-cli: cannot create ${binDir}: ${err.message}\n`)
process.exit(0)
}
const link = join(binDir, 'ocm')
try {
const stat = lstatSync(link)
if (stat.isSymbolicLink()) {
if (readlinkSync(link) === target) {
process.exit(0)
}
unlinkSync(link)
} else {
process.stderr.write(`ocm-cli: ${link} exists and is not a symlink; leaving alone\n`)
process.exit(0)
}
} catch {
// missing — fine
}
try {
symlinkSync(target, link)
} catch (err) {
process.stderr.write(`ocm-cli: failed to symlink ${link}: ${err.message}\n`)
process.exit(0)
}
process.stdout.write(`ocm installed at ${link}\n`)
const path = process.env.PATH ?? ''
if (!path.split(':').includes(binDir)) {
process.stdout.write(`note: ${binDir} is not on your PATH. Add to your shell rc:\n`)
process.stdout.write(` export PATH="${binDir}:$PATH"\n`)
}
+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 })
}
}
+390
View File
@@ -0,0 +1,390 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readdirSync, readFileSync } from 'fs'
import { join } from 'path'
import { tmpdir } from 'os'
import { spawnSync, execSync } from 'child_process'
import { prepareMirror, MirrorAbort, mirrorDown, mirrorUp } from '../src/mirror'
describe('prepareMirror', () => {
let tmpDir: string
beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'mirror-test-'))
})
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true })
})
it('rejects when not in a git repo', () => {
const nonGitDir = join(tmpDir, 'non-git')
mkdirSync(nonGitDir)
expect(() => prepareMirror(nonGitDir, [])).toThrow(MirrorAbort)
expect(() => prepareMirror(nonGitDir, [])).toThrow('not in a git repository')
})
it('rejects when no origin URL found', () => {
const gitDir = join(tmpDir, 'git-no-origin')
mkdirSync(gitDir)
spawnSync('git', ['init'], { cwd: gitDir, stdio: 'ignore' })
expect(() => prepareMirror(gitDir, [])).toThrow(MirrorAbort)
expect(() => prepareMirror(gitDir, [])).toThrow('no origin URL found')
})
it('returns empty matched array when no remote matches', () => {
const gitDir = join(tmpDir, 'git-mismatch')
mkdirSync(gitDir)
spawnSync('git', ['init'], { cwd: gitDir, stdio: 'ignore' })
spawnSync('git', ['remote', 'add', 'origin', 'https://github.com/other/repo.git'], { cwd: gitDir, stdio: 'ignore' })
const remotes = [
{ repoId: 1, name: 'my-repo', originUrl: 'https://github.com/me/repo.git', branch: 'main' },
]
const plan = prepareMirror(gitDir, remotes)
expect(plan.matched).toHaveLength(0)
expect(plan.localOrigin).toContain('other/repo')
})
it('returns matching repos when origin matches', () => {
const gitDir = join(tmpDir, 'git-match')
mkdirSync(gitDir)
spawnSync('git', ['init'], { cwd: gitDir, stdio: 'ignore' })
spawnSync('git', ['remote', 'add', 'origin', 'https://github.com/me/repo.git'], { cwd: gitDir, stdio: 'ignore' })
const remotes = [
{ repoId: 1, name: 'my-repo', originUrl: 'https://github.com/me/repo.git', branch: 'main' },
{ repoId: 2, name: 'other-repo', originUrl: 'https://github.com/other/repo.git', branch: 'main' },
]
const plan = prepareMirror(gitDir, remotes)
expect(plan.matched).toHaveLength(1)
expect(plan.matched[0]!.repoId).toBe(1)
expect(plan.localOrigin).toContain('me/repo')
})
})
describe('cmdPush', () => {
let originalArgv: string[]
let originalIsTTY: boolean | undefined
beforeEach(() => {
originalArgv = process.argv.slice()
originalIsTTY = process.stdin.isTTY
vi.restoreAllMocks()
})
afterEach(() => {
process.argv = originalArgv
if (originalIsTTY !== undefined) process.stdin.isTTY = originalIsTTY
})
it('errors with "stdin is not a TTY" when --create requested non-interactively and --yes omitted', async () => {
process.stdin.isTTY = false
process.argv = ['node', 'ocm', 'push', '--create']
let stderrOutput = ''
vi.spyOn(process.stderr, 'write').mockImplementation((msg: string | Uint8Array) => {
stderrOutput += typeof msg === 'string' ? msg : new TextDecoder().decode(msg)
return true
})
vi.spyOn(process, 'exit').mockImplementation((code?: string | number | null) => {
throw new Error(stderrOutput.trim())
})
const mockState = { managerUrl: 'http://localhost:5003' }
vi.doMock('../src/state.js', () => ({
readState: () => mockState,
writeState: () => {},
clearState: () => {},
getStatePath: () => '/tmp/state.json',
}))
vi.doMock('../src/keychain.js', () => ({
getToken: () => 'test-token',
setToken: () => {},
deleteToken: () => true,
KeychainError: class extends Error {},
}))
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ workspaces: [] }),
}))
const { cmdPush } = await import('../bin/ocm')
await expect(cmdPush(['--create'])).rejects.toThrow('stdin is not a TTY; pass --yes to confirm creation')
})
})
describe('mirrorDown', () => {
let tmpDir: string
beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'mirror-down-test-'))
})
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true })
})
function createTarball(dir: string): Buffer {
const tarFile = join(tmpDir, 'test.tar')
execSync(`tar -cf "${tarFile}" -C "${dir}" .`)
return require('fs').readFileSync(tarFile)
}
it('stages tarball in sibling directory next to repoRoot', async () => {
const repoRoot = join(tmpDir, 'repo')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
const contentDir = join(tmpDir, 'content')
mkdirSync(contentDir)
writeFileSync(join(contentDir, 'file.txt'), 'hello')
const tarData = createTarball(contentDir)
const mockApi = {
mirrorDown: vi.fn().mockResolvedValue(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(tarData))
controller.close()
},
})
),
} as any
await mirrorDown(1, repoRoot, mockApi, { force: true })
expect(existsSync(join(repoRoot, 'file.txt'))).toBe(true)
const entries = readdirSync(tmpDir).filter((e) => e.startsWith('repo.ocm-recv-'))
expect(entries.length).toBe(0)
})
it('restores original repo when swap fails after creating backup', async () => {
const repoRoot = join(tmpDir, 'repo-swap-fail')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'file.txt'), 'original content')
const contentDir = join(tmpDir, 'content-fail')
mkdirSync(contentDir)
writeFileSync(join(contentDir, 'new-file.txt'), 'new content')
const tarData = createTarball(contentDir)
const mockApi = {
mirrorDown: vi.fn().mockResolvedValue(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(tarData))
controller.close()
},
})
),
} as any
try {
await mirrorDown(1, repoRoot, mockApi, { force: true })
} catch {
const entries = readdirSync(tmpDir).filter((e) => e.startsWith('repo-swap-fail.ocm-backup-'))
expect(entries.length).toBe(0)
expect(existsSync(repoRoot)).toBe(true)
expect(existsSync(join(repoRoot, 'file.txt'))).toBe(true)
}
const entriesAfterSuccess = readdirSync(tmpDir).filter((e) => e.startsWith('repo-swap-fail.ocm-backup-'))
expect(entriesAfterSuccess.length).toBe(0)
})
it('throws MirrorAbort when working tree has uncommitted changes and force is false', async () => {
const repoRoot = join(tmpDir, 'repo-dirty')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'dirty.txt'), 'dirty')
spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['commit', '-m', 'initial'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'dirty.txt'), 'dirty-modified')
const mockApi = {
mirrorDown: vi.fn(),
} as any
await expect(mirrorDown(1, repoRoot, mockApi, { force: false })).rejects.toThrow(MirrorAbort)
await expect(mirrorDown(1, repoRoot, mockApi, { force: false })).rejects.toThrow('working tree has uncommitted changes; rerun with --force')
})
it('preserves directory inode so relative paths work after pull from inside repo', async () => {
const repoRoot = join(tmpDir, 'repo-inode')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'original.txt'), 'original content')
const contentDir = join(tmpDir, 'content-inode')
mkdirSync(contentDir)
writeFileSync(join(contentDir, 'new-file.txt'), 'new content')
writeFileSync(join(contentDir, 'updated.txt'), 'updated content')
const tarData = createTarball(contentDir)
const mockApi = {
mirrorDown: vi.fn().mockResolvedValue(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(tarData))
controller.close()
},
})
),
} as any
const originalCwd = process.cwd()
process.chdir(repoRoot)
try {
await mirrorDown(1, repoRoot, mockApi, { force: true })
expect(existsSync(join(repoRoot, 'new-file.txt'))).toBe(true)
expect(existsSync(join(repoRoot, 'updated.txt'))).toBe(true)
expect(readFileSync(join(repoRoot, 'new-file.txt'), 'utf-8')).toBe('new content')
expect(readFileSync(join(repoRoot, 'updated.txt'), 'utf-8')).toBe('updated content')
expect(existsSync(join(repoRoot, 'original.txt'))).toBe(false)
} finally {
process.chdir(originalCwd)
}
})
it('replaces contents while keeping directory inode intact', async () => {
const repoRoot = join(tmpDir, 'repo-replace')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'old-file.txt'), 'old content')
const contentDir = join(tmpDir, 'content-replace')
mkdirSync(contentDir)
writeFileSync(join(contentDir, 'new-file.txt'), 'new content')
const tarData = createTarball(contentDir)
const mockApi = {
mirrorDown: vi.fn().mockResolvedValue(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(tarData))
controller.close()
},
})
),
} as any
await mirrorDown(1, repoRoot, mockApi, { force: true })
expect(existsSync(join(repoRoot, 'new-file.txt'))).toBe(true)
expect(existsSync(join(repoRoot, 'old-file.txt'))).toBe(false)
const entries = readdirSync(tmpDir).filter((e) => e.startsWith('repo-replace.ocm-backup-'))
expect(entries.length).toBe(0)
const stagingEntries = readdirSync(tmpDir).filter((e) => e.startsWith('repo-replace.ocm-recv-'))
expect(stagingEntries.length).toBe(0)
})
})
describe('mirrorUp with gitignore', () => {
let tmpDir: string
beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'mirror-up-test-'))
})
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true })
})
it('excludes gitignored files from tar stream', async () => {
const repoRoot = join(tmpDir, 'repo-up-gitignore')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'tracked.txt'), 'tracked content')
writeFileSync(join(repoRoot, 'secrets.env'), 'SECRET_KEY=abc123')
writeFileSync(join(repoRoot, '.gitignore'), 'secrets.env\n')
const mockApi = {
mirrorUp: vi.fn().mockResolvedValue({ repoId: 1, branch: 'main', head: 'abc123', created: false }),
} as any
const plan = {
repoRoot,
localOrigin: 'https://github.com/test/repo.git',
matched: [{ repoId: 1, name: 'test-repo', originUrl: 'https://github.com/test/repo.git', branch: 'main' }],
}
await mirrorUp(plan, { api: mockApi, force: false })
expect(mockApi.mirrorUp).toHaveBeenCalledTimes(1)
expect(mockApi.mirrorUp.mock.calls[0][0]).toBe(1)
const opts = mockApi.mirrorUp.mock.calls[0][2]
expect(opts.force).toBe(false)
})
it('excludes node_modules from tar stream', async () => {
const repoRoot = join(tmpDir, 'repo-up-node-modules')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'file.txt'), 'content')
mkdirSync(join(repoRoot, 'node_modules'))
writeFileSync(join(repoRoot, 'node_modules', 'dep.js'), 'dep content')
const mockApi = {
mirrorUp: vi.fn().mockResolvedValue({ repoId: 1, branch: 'main', head: 'abc123', created: false }),
} as any
const plan = {
repoRoot,
localOrigin: 'https://github.com/test/repo.git',
matched: [{ repoId: 1, name: 'test-repo', originUrl: 'https://github.com/test/repo.git', branch: 'main' }],
}
await mirrorUp(plan, { api: mockApi, force: false })
expect(mockApi.mirrorUp).toHaveBeenCalledTimes(1)
expect(mockApi.mirrorUp.mock.calls[0][0]).toBe(1)
expect(mockApi.mirrorUp.mock.calls[0][2].force).toBe(false)
})
it('does not create exclude file when no gitignored paths exist', async () => {
const repoRoot = join(tmpDir, 'repo-up-no-ignore')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'file.txt'), 'content')
const mockApi = {
mirrorUp: vi.fn().mockResolvedValue({ repoId: 1, branch: 'main', head: 'abc123', created: false }),
} as any
const plan = {
repoRoot,
localOrigin: 'https://github.com/test/repo.git',
matched: [{ repoId: 1, name: 'test-repo', originUrl: 'https://github.com/test/repo.git', branch: 'main' }],
}
await mirrorUp(plan, { api: mockApi, force: false })
expect(mockApi.mirrorUp).toHaveBeenCalledTimes(1)
expect(mockApi.mirrorUp.mock.calls[0][0]).toBe(1)
const opts = mockApi.mirrorUp.mock.calls[0][2]
expect(opts.force).toBe(false)
})
})
+138
View File
@@ -0,0 +1,138 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { mkdtempSync, mkdirSync, rmSync } from 'fs'
import { join } from 'path'
import { tmpdir } from 'os'
import { spawnSync } from 'child_process'
import { resolveTarget, type TargetRepo } from '../src/resolve-target'
const LAST = {
repoId: 99,
name: 'last-repo',
directory: '/manager/last',
branch: 'main',
}
function gitInit(dir: string, originUrl?: string): void {
mkdirSync(dir, { recursive: true })
spawnSync('git', ['init'], { cwd: dir, stdio: 'ignore' })
if (originUrl) {
spawnSync('git', ['remote', 'add', 'origin', originUrl], { cwd: dir, stdio: 'ignore' })
}
}
describe('resolveTarget', () => {
let tmp: string
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), 'resolve-target-'))
})
afterEach(() => {
rmSync(tmp, { recursive: true, force: true })
})
const repo = (id: number, originUrl: string, name = `repo-${id}`): TargetRepo => ({
repoId: id,
name,
branch: 'main',
directory: `/manager/${name}`,
originUrl,
})
it('returns cwd-match when $PWD origin matches exactly one Manager repo', () => {
const dir = join(tmp, 'work')
gitInit(dir, 'https://github.com/me/repo.git')
const result = resolveTarget({
cwd: dir,
repos: [repo(1, 'https://github.com/me/repo.git', 'my-repo'), repo(2, 'https://github.com/other/repo.git')],
last: LAST,
})
expect(result.kind).toBe('cwd-match')
if (result.kind === 'cwd-match') {
expect(result.repo.repoId).toBe(1)
expect(result.repo.name).toBe('my-repo')
}
})
it('returns cwd-ambiguous when multiple Manager repos match', () => {
const dir = join(tmp, 'work')
gitInit(dir, 'https://github.com/me/repo.git')
const result = resolveTarget({
cwd: dir,
repos: [
repo(1, 'https://github.com/me/repo.git', 'a'),
repo(2, 'https://github.com/me/repo.git', 'b'),
],
last: LAST,
})
expect(result.kind).toBe('cwd-ambiguous')
if (result.kind === 'cwd-ambiguous') {
expect(result.matches).toHaveLength(2)
}
})
it('returns local(no-match) when in a git repo with no origin match (even if last is set)', () => {
const dir = join(tmp, 'work')
gitInit(dir, 'https://github.com/me/repo.git')
const result = resolveTarget({
cwd: dir,
repos: [repo(1, 'https://github.com/other/repo.git')],
last: LAST,
})
expect(result.kind).toBe('local')
if (result.kind === 'local') {
expect(result.reason).toBe('no-match')
expect(result.repoRoot).toContain('work')
}
})
it('returns last when not in a git repo and last is set', () => {
const dir = join(tmp, 'not-git')
mkdirSync(dir)
const result = resolveTarget({
cwd: dir,
repos: [repo(1, 'https://github.com/me/repo.git')],
last: LAST,
})
expect(result.kind).toBe('last')
if (result.kind === 'last') {
expect(result.repo.repoId).toBe(LAST.repoId)
}
})
it('returns local(no-target) when not in a git repo and no last', () => {
const dir = join(tmp, 'not-git')
mkdirSync(dir)
const result = resolveTarget({
cwd: dir,
repos: [repo(1, 'https://github.com/me/repo.git')],
})
expect(result.kind).toBe('local')
if (result.kind === 'local') {
expect(result.reason).toBe('no-target')
expect(result.repoRoot).toBeNull()
}
})
it('normalises .git suffix when matching origin', () => {
const dir = join(tmp, 'work')
gitInit(dir, 'https://github.com/me/repo')
const result = resolveTarget({
cwd: dir,
repos: [repo(1, 'https://github.com/me/repo.git', 'my-repo')],
})
expect(result.kind).toBe('cwd-match')
})
})
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM"],
"types": ["node"],
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"include": ["src/**/*", "bin/**/*"],
"exclude": ["node_modules", "dist"]
}
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['test/**/*.test.ts'],
},
})