From 9b7f5d6194abefec8aaadbfff758f3ce3e7e0414 Mon Sep 17 00:00:00 2001 From: ZTatman Date: Mon, 13 Apr 2026 13:51:55 -0400 Subject: [PATCH] fix(cli): atomic config writes, validate subcommands and reject positionals --- packages/cli/src/cli-router.ts | 28 +++++++++++++++++------- packages/cli/src/commands/config/init.ts | 24 ++++++++++++++------ 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/packages/cli/src/cli-router.ts b/packages/cli/src/cli-router.ts index ce1ed84..9e180a2 100644 --- a/packages/cli/src/cli-router.ts +++ b/packages/cli/src/cli-router.ts @@ -191,7 +191,11 @@ export async function runCli( // If help is requested for a specific command, show command-specific help if (wantsCommandHelp) { - const actualSubcommand = isHelpFlag(subcommand) ? undefined : subcommand; + const subcommands = cmdConf.subcommands; + const actualSubcommand = + subcommand && subcommands && subcommand in subcommands + ? subcommand + : undefined; showCommandHelp(command, cmdConf, actualSubcommand); return; } @@ -233,14 +237,22 @@ export async function runCli( ? [subcommand, ...remainingArgs] : remainingArgs; - // Parse target command options - const { values: cmdOpts } = parseArgs({ - args: argsForOptions, - options: targetCmdConf.options || {}, - allowPositionals: true, - }); - try { + // Parse target command options + const { values: cmdOpts, positionals } = parseArgs({ + args: argsForOptions, + options: targetCmdConf.options || {}, + allowPositionals: true, + }); + + if (positionals.length > 0) { + process.stderr.write( + `${c.red("Error:")} Unexpected argument: ${positionals[0]}\n`, + ); + process.exitCode = 1; + return; + } + // Execute the target command handler await targetCmdConf.handler(cmdOpts); } catch (error) { diff --git a/packages/cli/src/commands/config/init.ts b/packages/cli/src/commands/config/init.ts index 54f8267..52b61f2 100644 --- a/packages/cli/src/commands/config/init.ts +++ b/packages/cli/src/commands/config/init.ts @@ -115,7 +115,6 @@ async function init(opts: { output?: string }) { } if (choice === "overwrite") { - await fs.unlink(envPath); break; } } @@ -174,7 +173,6 @@ async function init(opts: { output?: string }) { onCancel: () => { p.cancel("\nOperation cancelled."); process.exitCode = 0; - throw new Error("Operation cancelled"); }, }, ); @@ -200,11 +198,23 @@ async function init(opts: { output?: string }) { publicUrl, }); - await fs.writeFile(envPath, envContent, { - encoding: "utf8", - flag: "wx", - mode: 0o600, - }); + if (envExists) { + const tempPath = envPath + ".tmp"; + await fs.writeFile(tempPath, envContent, { + encoding: "utf8", + flag: "wx", + mode: 0o600, + }); + + await fs.unlink(envPath).catch(() => {}); + await fs.rename(tempPath, envPath); + } else { + await fs.writeFile(envPath, envContent, { + encoding: "utf8", + flag: "wx", + mode: 0o600, + }); + } s.stop(c.yellow(`.env created at ${envPath}`)); p.note(