Skip to content

fix(main): allow user-defined -h, --help, -v, --version args - #234

Merged
pi0 merged 1 commit into
mainfrom
fix/h-alias
Mar 15, 2026
Merged

pi0 merged 1 commit into
mainfrom
fix/h-alias

Conversation

@pi0

@pi0 pi0 commented Mar 15, 2026 •

Copy link
Copy Markdown
Member

Summary

When user args conflict with built-in flags, citty yields gracefully:

  • -h taken (e.g. --host -h) → only --help triggers built-in help
  • --help taken → built-in help fully disabled
  • -v taken (e.g. --verbose -v) → only --version triggers built-in version
  • --version taken → built-in version fully disabled

Closes #232

Test plan

  • -h alias passes through to user's --host arg
  • --help still triggers built-in help when only -h is taken
  • Built-in help fully disabled when user defines --help arg
  • -v alias passes through to user's --verbose arg
  • --version still triggers built-in version when only -v is taken
  • Built-in version fully disabled when user defines --version arg
  • All existing tests pass (63/63)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved help and version flag handling so built-in help/version remain available when user-defined flags conflict with -h/-v or --help/--version.
  • Tests

    • Added comprehensive tests for help/version flag conflicts, covering cases where short or long flags are overridden by user arguments and ensuring correct behavior for usage and version output.

@coderabbitai

coderabbitai Bot commented Mar 15, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Replaces static help/version flag detection with dynamic resolution that inspects command argument names and aliases to decide which builtin help/version flags to reserve or expose; runMain now uses the computed builtin flags to decide printing usage/version or delegating to runCommand.

Changes

Cohort / File(s) Summary
Flag resolution logic
src/main.ts
Adds _resolveBuiltinFlags(cmd) and _getBuiltinFlags(...) to compute available builtin help and version flags by inspecting cmd.args (via resolveValue) and user-defined names/aliases; replaces direct rawArgs checks with builtin-flag-aware logic in runMain.
Builtin flag conflict tests
test/main.test.ts
Adds "builtin flag conflicts" test suite covering help and version flag interactions (e.g., user-defined -h/-v aliases, --help/--version disabling builtins); mocks process exit and verifies usage/version output and command invocation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through flags both grand and small,
Checking names and aliases, one and all.
If -h is yours, I'll let it be—
Else help or version, I'll show with glee.
Hooray for careful flag discovery! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: allowing user-defined -h, --help, -v, --version args instead of being reserved for builtins.
Linked Issues check ✅ Passed The PR fully addresses issue #232 by allowing users to assign -h and --help as aliases for their own flags through dynamic flag resolution logic.
Out of Scope Changes check ✅ Passed All changes are directly scoped to resolving flag conflicts: helper functions for builtin flag detection and comprehensive tests for -h, --help, -v, --version scenarios.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/h-alias
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/main.test.ts (1)

169-230: Add a regression test for an argument key named h.

Current tests cover alias "h" and arg key "help", but not arg key "h" itself, which follows a separate branch in _resolveHelpFlags().

Suggested test addition
 describe("help flag conflicts", () => {
   vi.spyOn(process, "exit").mockImplementation(() => 0 as never);

   const runMock = vi.fn();

+  it("keeps builtin --help when user defines arg key h", async () => {
+    const consoleMock = vi.spyOn(console, "log").mockImplementation(() => undefined);
+    const command = defineCommand({
+      meta: { name: "test", description: "Test" },
+      args: {
+        h: {
+          type: "boolean",
+          description: "Custom h flag",
+        },
+      },
+    });
+
+    await runMain(command, { rawArgs: ["--help"] });
+
+    const usage = await renderUsage(command);
+    expect(consoleMock).toHaveBeenCalledWith(usage + "\n");
+    consoleMock.mockRestore();
+  });
+
   it("allows -h alias to be used by user args (e.g. --host)", async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/main.test.ts` around lines 169 - 230, Add a regression test that covers
when a user defines an argument whose key is literally "h" (not an alias or
"help") because _resolveHelpFlags() treats that case differently; create a test
in the "help flag conflicts" suite using defineCommand with an args entry named
"h" (e.g., type: "boolean" or "string") and assert behavior via runMain and/or
renderUsage similar to the other cases so the code path for arg key "h" is
exercised and verified.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main.ts`:
- Around line 55-60: The code incorrectly marks builtin help flags as reserved
by setting hasHelp when encountering the short name "h" and by treating
positional args named "help"/"h" as flag conflicts; update the detection logic
in the loop over argsDef so that hasHelp is set only when name === "help" and
the arg is a flag/option (not positional), hasH is set only when name === "h"
and the arg is a flag/option, and skip names when def indicates a positional arg
(e.g., def.positional or def.type === "positional"); apply the same fix to the
corresponding check block that mirrors this logic elsewhere (the later block
around the other check).

---

Nitpick comments:
In `@test/main.test.ts`:
- Around line 169-230: Add a regression test that covers when a user defines an
argument whose key is literally "h" (not an alias or "help") because
_resolveHelpFlags() treats that case differently; create a test in the "help
flag conflicts" suite using defineCommand with an args entry named "h" (e.g.,
type: "boolean" or "string") and assert behavior via runMain and/or renderUsage
similar to the other cases so the code path for arg key "h" is exercised and
verified.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d302b00f-f861-4b33-b72c-4950a2af4a25

📥 Commits

Reviewing files that changed from the base of the PR and between 0228318 and 32c38e5.

📒 Files selected for processing (2)
  • src/main.ts
  • test/main.test.ts

Comment thread src/main.ts Outdated
Comment on lines +55 to +60
for (const [name, def] of Object.entries(argsDef)) {
if (name === "help" || name === "h") {
hasHelp = true;
}
if (name === "h") {
hasH = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Refine help-conflict detection to avoid over-disabling builtin help.

name === "h" currently sets hasHelp = true, which disables both builtin help flags ([]). That makes --help unavailable in cases that should only reserve -h. Also, positional args named help/h should not be considered flag conflicts.

Proposed fix
 async function _resolveHelpFlags<T extends ArgsDef>(cmd: CommandDef<T>): Promise<string[]> {
   const argsDef = await resolveValue(cmd.args || ({} as ArgsDef));
   let hasH = false;
   let hasHelp = false;
   for (const [name, def] of Object.entries(argsDef)) {
-    if (name === "help" || name === "h") {
-      hasHelp = true;
-    }
-    if (name === "h") {
-      hasH = true;
-    }
+    if ((def as any).type === "positional") {
+      continue;
+    }
+    if (name === "help") {
+      hasHelp = true;
+    } else if (name === "h") {
+      hasH = true;
+    }
     const aliases = toArray((def as any).alias);
     for (const alias of aliases) {
       if (alias === "h") {
         hasH = true;
       }

Also applies to: 72-77

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main.ts` around lines 55 - 60, The code incorrectly marks builtin help
flags as reserved by setting hasHelp when encountering the short name "h" and by
treating positional args named "help"/"h" as flag conflicts; update the
detection logic in the loop over argsDef so that hasHelp is set only when name
=== "help" and the arg is a flag/option (not positional), hasH is set only when
name === "h" and the arg is a flag/option, and skip names when def indicates a
positional arg (e.g., def.positional or def.type === "positional"); apply the
same fix to the corresponding check block that mirrors this logic elsewhere (the
later block around the other check).

When user args conflict with built-in flags, citty yields gracefully:
- `-h` taken (e.g. `--host -h`) → only `--help` triggers built-in help
- `--help` taken → built-in help fully disabled
- `-v` taken (e.g. `--verbose -v`) → only `--version` triggers built-in version
- `--version` taken → built-in version fully disabled

Closes #232

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@pi0 pi0 changed the title fix(main): allow user-defined -h and --help args fix(main): allow user-defined -h, --help, -v, --version args Mar 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
src/main.ts (1)

51-67: ⚠️ Potential issue | 🟡 Minor

Positional args named help or version incorrectly disable builtin flags.

The current implementation adds all argument names to userNames without checking if they are positional. According to the type definitions, positional args shouldn't conflict with builtin flag names since they're not prefixed with --. A positional named help should not disable --help.

Proposed fix to skip positional args
 async function _resolveBuiltinFlags<T extends ArgsDef>(
   cmd: CommandDef<T>,
 ): Promise<{ help: string[]; version: string[] }> {
   const argsDef = await resolveValue(cmd.args || ({} as ArgsDef));
   const userNames = new Set<string>();
   const userAliases = new Set<string>();
   for (const [name, def] of Object.entries(argsDef)) {
+    if ((def as any).type === "positional") {
+      continue;
+    }
     userNames.add(name);
     for (const alias of toArray((def as any).alias)) {
       userAliases.add(alias);
     }
   }
   return {
     help: _getBuiltinFlags("help", "h", userNames, userAliases),
     version: _getBuiltinFlags("version", "v", userNames, userAliases),
   };
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main.ts` around lines 51 - 67, _resolveBuiltinFlags is adding every
argument name (from argsDef) into userNames/userAliases, which incorrectly
blocks builtin flags when an argument is positional; update the loop to skip
positional arguments by checking the arg definition (e.g., (def as
any).positional === true or (def as any).type === 'positional') before adding
its name/alias, so only non-positional (flag) args are inserted into
userNames/userAliases and _getBuiltinFlags("help", "h", ...) and
_getBuiltinFlags("version", "v", ...) behave correctly.
🧹 Nitpick comments (1)
test/main.test.ts (1)

169-173: Consider resetting runMock between tests to avoid cross-test pollution.

The shared runMock isn't cleared between tests. If tests run in sequence, earlier calls persist and could cause confusion when debugging failures. Using beforeEach to reset or toHaveBeenLastCalledWith for assertions would improve test isolation.

Proposed fix
 describe("builtin flag conflicts", () => {
   vi.spyOn(process, "exit").mockImplementation(() => 0 as never);

   const runMock = vi.fn();
+
+  beforeEach(() => {
+    runMock.mockClear();
+  });

You'll also need to import beforeEach from vitest:

-import { describe, it, expect, vi, afterAll } from "vitest";
+import { describe, it, expect, vi, afterAll, beforeEach } from "vitest";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/main.test.ts` around lines 169 - 173, The shared runMock in the "builtin
flag conflicts" suite is not reset between tests, causing cross-test pollution;
add a beforeEach hook (imported from vitest) inside that describe block to call
runMock.mockClear() or runMock.mockReset() so each test starts with a fresh
mock, ensuring assertions against runMock reflect only the current test's calls.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/main.ts`:
- Around line 51-67: _resolveBuiltinFlags is adding every argument name (from
argsDef) into userNames/userAliases, which incorrectly blocks builtin flags when
an argument is positional; update the loop to skip positional arguments by
checking the arg definition (e.g., (def as any).positional === true or (def as
any).type === 'positional') before adding its name/alias, so only non-positional
(flag) args are inserted into userNames/userAliases and _getBuiltinFlags("help",
"h", ...) and _getBuiltinFlags("version", "v", ...) behave correctly.

---

Nitpick comments:
In `@test/main.test.ts`:
- Around line 169-173: The shared runMock in the "builtin flag conflicts" suite
is not reset between tests, causing cross-test pollution; add a beforeEach hook
(imported from vitest) inside that describe block to call runMock.mockClear() or
runMock.mockReset() so each test starts with a fresh mock, ensuring assertions
against runMock reflect only the current test's calls.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2d90cef4-2ebf-496d-987f-e0dc9d202360

📥 Commits

Reviewing files that changed from the base of the PR and between 32c38e5 and b7225fd.

📒 Files selected for processing (2)
  • src/main.ts
  • test/main.test.ts

@pi0
pi0 merged commit 3c190d6 into main Mar 15, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Regression: -h alias not working

1 participant