import { resolve } from "path"; import { existsSync, statSync } from "fs"; import { saveConfig, findConfigPath } from "../config/loader.ts"; import { formatError, formatInfo, formatSuccess } from "./formatters.ts"; import type { CLIOptions } from "./index.ts"; /** * Handle config commands */ export async function handleConfigCommand( subcommand: string, args: string[], options: CLIOptions ): Promise { switch (subcommand) { case "add-dir": await handleAddDir(args, options); break; default: console.error(formatError(`Unknown config subcommand: ${subcommand}`)); console.log(formatInfo("Available commands: add-dir")); process.exit(1); } } /** * Handle 'add-dir' command */ async function handleAddDir(args: string[], options: CLIOptions): Promise { const { config } = options; if (args.length === 0) { console.error(formatError("Missing directory path")); console.log(formatInfo("Usage: gitforest config add-dir [--max-depth ]")); process.exit(1); } const rawPath = args[0]!; const absPath = resolve(process.cwd(), rawPath); // Validate path if (!existsSync(absPath)) { console.error(formatError(`Directory does not exist: ${absPath}`)); process.exit(1); } if (!statSync(absPath).isDirectory()) { console.error(formatError(`Not a directory: ${absPath}`)); process.exit(1); } // Parse options const maxDepth = options.maxDepth ?? 2; // Check if directory is already in config const existingIndex = config.directories.findIndex((d) => { const dPath = d.path.replace(/^~/, process.env.HOME || ""); return resolve(dPath) === absPath; }); if (existingIndex >= 0) { console.log(formatInfo(`Directory already in config: ${absPath}`)); // Update maxDepth config.directories[existingIndex]!.maxDepth = maxDepth; console.log(formatInfo(`Updated max-depth to ${maxDepth}`)); } else { config.directories.push({ path: absPath, maxDepth, }); console.log(formatInfo(`Added directory: ${absPath} (max-depth: ${maxDepth})`)); } try { const configPath = findConfigPath(); // Note: loadConfig loads and expands env vars. // We shouldn't save the expanded version ideally, but `loader.ts` implementation of `loadConfig` // returns a resolved config. If we save this, we might lose env var tokens if the user had them. // However, the `createDefaultConfig` creates simple yaml. // For this feature, we accept overwriting with resolved values or we should reload raw first. // `saveConfig` in previous step takes the full GitforestConfig object. // Let's proceed with saving the modified config object we have. await saveConfig(config, configPath || undefined); console.log(formatSuccess("Configuration saved.")); } catch (error) { console.error(formatError(`Failed to save config: ${error instanceof Error ? error.message : String(error)}`)); process.exit(1); } }