/** * Generic JSON-config setup runner shared by `ccl setup ` subcommands. * * Each host adapter only supplies: * - resolveConfigPath(): where the host stores its global JSON config * - computePatch(current, opts): pure function returning the desired next config + change/warning notes * * The runner handles dry-run, diff, atomic write, and timestamped backup uniformly, * so adding a new host (gemini, claude-code, ...) is ~30 lines of glue. */ import { existsSync, readFileSync, renameSync, copyFileSync, writeFileSync } from 'fs'; export interface HostConfigPatcher> { hostName: string; resolveConfigPath: () => string; computePatch: (current: unknown, opts: Opts) => HostPatchResult; } export interface HostPatchResult { next: unknown; changes: string[]; warnings: string[]; } export interface RunHostSetupFlags { yes?: boolean; print?: boolean; configPath?: string; backup?: boolean; } export interface RunHostSetupResult { exitCode: number; output: string[]; } export function runHostConfigSetup( patcher: HostConfigPatcher, hostOpts: Opts, flags: RunHostSetupFlags, ): RunHostSetupResult { const out: string[] = []; const configPath = flags.configPath ?? patcher.resolveConfigPath(); if (flags.print) { const sample = patcher.computePatch({}, hostOpts); out.push(`# Recommended ${patcher.hostName} config patch:`); out.push(JSON.stringify(sample.next, null, 2)); return { exitCode: 0, output: out }; } if (!existsSync(configPath)) { out.push(`${patcher.hostName} config not found at: ${configPath}`); out.push(`Initialize it first (e.g. \`openclaw doctor\` for OpenClaw), then re-run.`); return { exitCode: 0, output: out }; } let raw: string; try { raw = readFileSync(configPath, 'utf-8'); } catch (err: any) { out.push(`Failed to read ${configPath}: ${err?.message ?? err}`); return { exitCode: 1, output: out }; } let current: unknown; try { current = JSON.parse(raw); } catch (err: any) { out.push(`Failed to parse JSON at ${configPath}: ${err?.message ?? err}`); out.push(`Fix the JSON manually first; this tool does not edit malformed files.`); return { exitCode: 1, output: out }; } const { next, changes, warnings } = patcher.computePatch(current, hostOpts); for (const w of warnings) out.push(`warning: ${w}`); if (changes.length === 0) { out.push(`${patcher.hostName} config already up to date at ${configPath}.`); return { exitCode: 0, output: out }; } if (!flags.yes) { out.push(`Pending changes to ${configPath}:`); for (const c of changes) out.push(` - ${c}`); out.push(``); out.push(diffJson(current, next)); out.push(``); out.push(`Dry-run only. Re-run with -y to apply.`); return { exitCode: 2, output: out }; } let backupPath: string | undefined; if (flags.backup !== false) { const ts = new Date().toISOString().replace(/[:.]/g, '-'); backupPath = `${configPath}.bak.${ts}`; try { copyFileSync(configPath, backupPath); } catch (err: any) { out.push(`Failed to back up ${configPath} → ${backupPath}: ${err?.message ?? err}`); return { exitCode: 1, output: out }; } } const tmpPath = `${configPath}.tmp.${process.pid}`; try { const eol = raw.includes('\r\n') ? '\r\n' : '\n'; const serialized = JSON.stringify(next, null, 2).replace(/\n/g, eol) + eol; writeFileSync(tmpPath, serialized, 'utf-8'); renameSync(tmpPath, configPath); } catch (err: any) { out.push(`Failed to write ${configPath}: ${err?.message ?? err}`); return { exitCode: 1, output: out }; } out.push(`Updated ${configPath}:`); for (const c of changes) out.push(` - ${c}`); if (backupPath) out.push(`Backup: ${backupPath}`); return { exitCode: 0, output: out }; } /** Minimal line-level JSON diff for the dry-run preview. Self-contained, zero deps. */ export function diffJson(before: unknown, after: unknown): string { const a = JSON.stringify(before, null, 2).split('\n'); const b = JSON.stringify(after, null, 2).split('\n'); const aSet = new Set(a); const bSet = new Set(b); const lines: string[] = []; const max = Math.max(a.length, b.length); for (let i = 0; i < max; i++) { const ax = a[i]; const bx = b[i]; if (ax === bx) { lines.push(` ${ax ?? ''}`); } else { if (ax !== undefined && !bSet.has(ax)) lines.push(`- ${ax}`); if (bx !== undefined && !aSet.has(bx)) lines.push(`+ ${bx}`); } } return lines.join('\n'); } /** Shared helper for hosts: add an entry to an array field, returning a new array (Set union). */ export function unionArrayField(arr: unknown, entry: string): { next: string[]; added: boolean } | { warning: string } { if (arr === undefined) return { next: [entry], added: true }; if (!Array.isArray(arr)) return { warning: `existing value is not an array, refusing to overwrite` }; if (arr.includes(entry)) return { next: arr.slice() as string[], added: false }; return { next: [...(arr as string[]), entry], added: true }; }