Skip to content

feat: support lazy command for entry - #116

Merged
kazupon merged 3 commits into
mainfrom
feat/entry-lazy-loading
May 9, 2025
Merged

feat: support lazy command for entry#116
kazupon merged 3 commits into
mainfrom
feat/entry-lazy-loading

Conversation

@kazupon

@kazupon kazupon commented May 9, 2025

Copy link
Copy Markdown
Owner

Description

Linked Issues

Additional context

Summary by CodeRabbit

  • New Features
    • Added support for lazy commands in the CLI, enabling dynamic loading and resolution of commands.
  • Tests
    • Added new test cases to ensure lazy commands are correctly invoked in different usage contexts.

@coderabbitai

coderabbitai Bot commented May 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The CLI module was updated to support a new LazyCommand type, modifying the command resolution logic and function signatures accordingly. Additional tests were added to verify the correct behavior of lazy commands in various scenarios. No existing exports were removed or altered, but function signatures were extended to accept LazyCommand.

Changes

File(s) Change Summary
src/cli.ts Updated CLI logic and function signatures to support LazyCommand; refactored command resolution flow to handle lazy commands distinctly.
src/cli.test.ts Added tests for lazy command behavior, including entry and sub-command scenarios; imported lazy function for testing.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant LazyCommand
    participant Command
    participant SubCommands

    User->>CLI: Invoke CLI with argv and entry (could be LazyCommand)
    CLI->>CLI: resolveCommandOptions(entry)
    alt entry is LazyCommand
        CLI->>SubCommands: Add LazyCommand to subCommands map
    end
    CLI->>CLI: resolveCommand(sub, entry, options)
    alt sub matches LazyCommand
        CLI->>LazyCommand: Invoke lazy command
    else sub matches Command
        CLI->>Command: Invoke command
    end
Loading

Poem

🐇
A lazy command hops into view,
Now CLI resolves it, clever and new!
With tests to ensure it works just right,
Subcommands and entries both take flight.
The code now welcomes a lazier friend—
Onward, the rabbit’s journey won’t end!
🌱

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bfc4c10 and 8f0ba48.

📒 Files selected for processing (2)
  • src/cli.test.ts (2 hunks)
  • src/cli.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/cli.test.ts
  • src/cli.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kazupon kazupon added the feature Includes new features label May 9, 2025
@pkg-pr-new

pkg-pr-new Bot commented May 9, 2025

Copy link
Copy Markdown

Open in StackBlitz

@gunshi/bone

npm i https://pkg.pr.new/@gunshi/bone@116

@gunshi/definition

npm i https://pkg.pr.new/@gunshi/definition@116

gunshi

npm i https://pkg.pr.new/gunshi@116

@gunshi/plugin

npm i https://pkg.pr.new/@gunshi/plugin@116

@gunshi/plugin-completion

npm i https://pkg.pr.new/@gunshi/plugin-completion@116

@gunshi/plugin-dryrun

npm i https://pkg.pr.new/@gunshi/plugin-dryrun@116

@gunshi/plugin-global

npm i https://pkg.pr.new/@gunshi/plugin-global@116

@gunshi/plugin-i18n

npm i https://pkg.pr.new/@gunshi/plugin-i18n@116

@gunshi/plugin-renderer

npm i https://pkg.pr.new/@gunshi/plugin-renderer@116

@gunshi/resources

npm i https://pkg.pr.new/@gunshi/resources@116

@gunshi/shared

npm i https://pkg.pr.new/@gunshi/shared@116

commit: ae034c8

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented May 9, 2025

Copy link
Copy Markdown

Deploying gunshi with  Cloudflare Pages  Cloudflare Pages

Latest commit: 8f0ba48
Status: ✅  Deploy successful!
Preview URL: https://c839aa92.gunshi.pages.dev
Branch Preview URL: https://feat-entry-lazy-loading.gunshi.pages.dev

View logs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (7)
src/cli.ts (5)

30-33: Update JSDoc to reflect new LazyCommand parameter

The function signature now accepts LazyCommand, but the JSDoc above (lines 25-27) still only mentions Command and CommandRunner.
Keeping docs in sync avoids confusion for downstream users and IDEs.

- * @param entry A {@link Command | entry command} or an {@link CommandRunner | inline command runner}
+ * @param entry A {@link Command | entry command},
+ *             an {@link CommandRunner | inline command runner},
+ *             or a {@link LazyCommand | lazily-loaded command}

104-115: Consider always augmenting subCommands, even when the caller did not supply any

Currently the entry command is only injected when options.subCommands is truthy.
If the caller provides no sub-commands but still wishes to invoke the entry by name (e.g. cli(['lazy'], entry)), the map remains empty and the token is treated as a positional argument with callMode = 'entry'.

That may be acceptable, but it differs from the behaviour when any sub-commands are present, where callMode = 'subCommand'.
If you want consistent semantics, populate the map unconditionally.


177-178: Define CANNOT_RESOLVE_COMMAND as a typed const tuple

Without as const, TypeScript widens the array to (string | undefined)[], triggering an extra cast later and losing tuple length guarantees.

-const CANNOT_RESOLVE_COMMAND = [undefined, undefined, 'unexpected']
+const CANNOT_RESOLVE_COMMAND = [
+  undefined,
+  undefined,
+  'unexpected'
+] as const satisfies [undefined, undefined, CommandCallMode]

187-209: Minor typing / readability tweaks for doResolveCommand

  1. typeof entry === 'object' is true for null; add a null-guard.
  2. Repeated await resolveLazyCommand(_, '', needRunResolving) – consider extracting common helper to DRY.
  3. The inner if ('commandName' in entry) check reads better with a user-defined type-guard.

No functional bug, but worth a cleanup pass.


211-216: Branch duplication – consolidate early-return paths

The if (omitted) and if (options.subCommands == null || …) blocks both return doResolveCommand().
Pull the sub-command lookup into a single guard to reduce cognitive load:

if (omitted || options.subCommands?.size === 0) {
  return doResolveCommand()
}
src/cli.test.ts (2)

68-76: Edge-case test uses empty positional token

Passing an empty string (['']) is not something Node/Jest normally produces from process.argv.
The test is valuable for coverage, but please add a short comment explaining the intent to future readers.


88-112: Test covers the happy path – add a failure assertion

You exercise both lazy and a real sub-command, great!
It would be useful to assert that invoking an unknown sub-command (e.g. cli(['unknown'], …)) still throws, ensuring the insertion of lazy into subCommands doesn’t loosen validation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b9d6ac and dea3384.

📒 Files selected for processing (2)
  • src/cli.test.ts (2 hunks)
  • src/cli.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (3)
src/cli.ts (1)

18-20: Type import looks good

Adding LazyCommand to the type-import list is required for the new feature and does not introduce any problems.

src/cli.test.ts (2)

4-4: Import path sanity check

lazy is imported from './definition.ts'.
If that module re-exports lazy from elsewhere this is fine, otherwise ensure the path is correct to avoid circular-import surprises.


78-86: Partial sub-command name may mask real typos

The test intentionally uses 'laz' (truncated) to verify fallback to the entry command.
Consider adding a negative test (['la']) or documenting that only exact matches are resolved when sub-commands exist, to avoid surprising users.

Comment thread src/cli.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

110-112: commandName may be undefined – guard before inserting into the map

If a consumer creates a lazy command without specifying commandName, the ! assertion bypasses safety and injects undefined as a key:

lazy(() => fn)          // no name supplied

This will silently store the command under an undefined key, making it impossible to retrieve later.

-  if (typeof entry === 'function' && 'commandName' in entry && entry.commandName) {
-    // eslint-disable-next-line @typescript-eslint/no-explicit-any
-    subCommands.set(entry.commandName!, entry as LazyCommand<any>)
+  if (
+    typeof entry === 'function' &&
+    'commandName' in entry &&
+    entry.commandName
+  ) {
+    subCommands.set(entry.commandName, entry as LazyCommand<any>)
🧹 Nitpick comments (4)
src/cli.ts (4)

177-177: Define explicit type for the constant

The constant CANNOT_RESOLVE_COMMAND is using an implicit type that's later cast when used. It would be clearer to explicitly type it.

-const CANNOT_RESOLVE_COMMAND = [undefined, undefined, 'unexpected']
+const CANNOT_RESOLVE_COMMAND: [undefined, undefined, CommandCallMode] = [undefined, undefined, 'unexpected']

189-208: Consider simplifying the conditional logic for better type safety

The current implementation uses nested if-else conditionals and type assertions. Consider rewriting for better type safety and readability:

  async function doResolveCommand(): Promise<
    [string | undefined, Command<A> | undefined, CommandCallMode]
  > {
-    if (typeof entry === 'function') {
-      // eslint-disable-next-line unicorn/prefer-ternary
-      if ('commandName' in entry) {
-        // lazy command
-        return [entry.commandName, await resolveLazyCommand(entry, '', needRunResolving), 'entry']
-      } else {
-        // inline command (command runner)
-        return [undefined, { run: entry as CommandRunner<A> }, 'entry']
-      }
-    } else if (typeof entry === 'object') {
-      // command object
-      return [
-        resolveEntryName(entry),
-        await resolveLazyCommand(entry, '', needRunResolving),
-        'entry'
-      ]
-    } else {
-      return CANNOT_RESOLVE_COMMAND as [string | undefined, Command<A> | undefined, CommandCallMode]
-    }
+    // Handle lazy command
+    if (typeof entry === 'function' && 'commandName' in entry) {
+      return [
+        entry.commandName, 
+        await resolveLazyCommand(entry, '', needRunResolving), 
+        'entry'
+      ]
+    }
+    
+    // Handle inline command runner
+    if (typeof entry === 'function') {
+      return [
+        undefined, 
+        { run: entry as CommandRunner<A> }, 
+        'entry'
+      ]
+    }
+    
+    // Handle command object
+    if (typeof entry === 'object' && entry !== null) {
+      return [
+        resolveEntryName(entry),
+        entry, // No need to resolve a command object that's already resolved
+        'entry'
+      ]
+    }
+    
+    // Cannot resolve
+    return CANNOT_RESOLVE_COMMAND
  }

211-223: Simplify control flow logic

The current control flow can be simplified for better readability:

-  if (omitted) {
-    return doResolveCommand()
-  } else {
-    if (options.subCommands == null || options.subCommands.size === 0) {
-      return doResolveCommand()
-    } else {
-      const cmd = options.subCommands?.get(sub)
-      if (cmd == null) {
-        return [sub, undefined, 'unexpected']
-      }
-      return [sub, await resolveLazyCommand(cmd, sub, needRunResolving), 'subCommand']
-    }
-  }
+  // If command is omitted or there are no subcommands, resolve the entry
+  if (omitted || options.subCommands == null || options.subCommands.size === 0) {
+    return doResolveCommand()
+  }
+  
+  // Otherwise, try to resolve the subcommand
+  const cmd = options.subCommands?.get(sub)
+  if (cmd == null) {
+    return [sub, undefined, 'unexpected']
+  }
+  
+  return [sub, await resolveLazyCommand(cmd, sub, needRunResolving), 'subCommand']

31-31: Update JSDoc to include LazyCommand

The function signature was updated to include LazyCommand, but the JSDoc comment above hasn't been updated to reflect this.

/**
 * Run the command.
 * @param args Command line arguments
- * @param entry A {@link Command | entry command} or an {@link CommandRunner | inline command runner}
+ * @param entry A {@link Command | entry command}, an {@link CommandRunner | inline command runner}, or a {@link LazyCommand | lazy command}
 * @param opts A {@link CommandOptions | command options}
 * @returns A rendered usage or undefined. if you will use {@link CommandOptions.usageSilent} option, it will return rendered usage string.
 */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dea3384 and bfc4c10.

📒 Files selected for processing (1)
  • src/cli.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (1)
src/cli.ts (1)

203-203:

Details

❌ Incorrect review comment

Review the use of resolveLazyCommand with command objects

You're calling resolveLazyCommand on a command object, but based on the name and context, this function is meant for lazy commands (functions). It's unclear if this is intentional or if the command object should be used directly.


🏁 Script executed:

#!/bin/bash
# Let's examine how resolveLazyCommand is implemented
cat src/utils.ts | grep -A 15 "export async function resolveLazyCommand"

Length of output: 559


🏁 Script executed:

#!/bin/bash
# Find all occurrences of resolveLazyCommand in the codebase
rg "resolveLazyCommand" -n .

Length of output: 627


resolveLazyCommand usage is correct

The resolveLazyCommand helper is designed to accept both lazy command functions and fully constructed command objects. When passed an object, it simply returns it unchanged (aside from setting the provided name). Your calls on entry and cmd are valid—no changes needed.

Likely an incorrect or invalid review comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature Includes new features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant