### Manual LLM-Assisted Development Setup Source: https://gunshi.dev/guide/introduction/setup Install the documentation package as a dev dependency for manual configuration. ```sh npm install --save-dev @gunshi/docs ``` ```sh pnpm add -D @gunshi/docs ``` ```sh yarn add -D @gunshi/docs ``` ```sh bun add -D @gunshi/docs ``` -------------------------------- ### Install and Configure @gunshi/bone Source: https://gunshi.dev/release/v0.27 Install the minimal CLI package and initialize it without default plugins. ```sh npm install @gunshi/bone ``` ```js import { cli } from '@gunshi/bone' import customPlugin from './my-custom-plugin.js' // No default plugins - you have full control await cli(process.argv.slice(2), command, { name: 'my-minimal-cli', plugins: [customPlugin()] // Only the plugins you need }) ``` -------------------------------- ### Implement Plugin Setup Logic Source: https://gunshi.dev/guide/plugin/lifecycle Use the setup function to register global options, sub-commands, and command decorators. ```js import { plugin } from 'gunshi/plugin' const myPlugin = plugin({ id: 'my-plugin', setup: ctx => { // This runs during Setup Phase console.log('Plugin setting up') // Add global options ctx.addGlobalOption('verbose', { type: 'boolean', description: 'Verbose output' }) // Register sub-commands ctx.addCommand('plugin-cmd', { name: 'plugin-cmd', run: ctx => console.log('Plugin command') }) // Add decorators (they stack in LIFO order) ctx.decorateCommand(baseRunner => async ctx => { console.log('Before command (from plugin)') const result = await baseRunner(ctx) console.log('After command (from plugin)') return result }) } }) ``` -------------------------------- ### Install optional plugins Source: https://gunshi.dev/release/v0.27 Commands to install the internationalization and shell completion plugins. ```sh npm install @gunshi/plugin-i18n ``` ```sh npm install @gunshi/plugin-completion ``` -------------------------------- ### Install minimal dependencies Source: https://gunshi.dev/guide/essentials/plugin-system Install the bare-bones foundation and required plugins using your preferred package manager. ```sh npm install --save @gunshi/bone @gunshi/plugin-global @gunshi/plugin-renderer ``` ```sh pnpm add @gunshi/bone @gunshi/plugin-global @gunshi/plugin-renderer ``` ```sh yarn add @gunshi/bone @gunshi/plugin-global @gunshi/plugin-renderer ``` -------------------------------- ### Define asynchronous CLI examples Source: https://gunshi.dev/guide/essentials/declarative Return a Promise from the examples function to load or generate examples asynchronously. ```js import { define } from 'gunshi' const command = define({ name: 'config', description: 'Manage configuration', args: { set: { type: 'string', description: 'Set configuration value' }, get: { type: 'string', description: 'Get configuration value' } }, examples: async ctx => { // Could load examples from external source const examples = await loadExamplesFromFile('config-examples.txt') return ( examples || ` # Set a configuration value config --set "api.key=abc123" # Get a configuration value config --get "api.key" `.trim() ) }, run: ctx => { // Implementation } }) ``` -------------------------------- ### Define a basic CLI example Source: https://gunshi.dev/guide/essentials/declarative Provide a single usage example as a simple string within the command definition. ```js import { define } from 'gunshi' const command = define({ name: 'copy', description: 'Copy files', args: { source: { type: 'positional', description: 'Source file' }, destination: { type: 'positional', description: 'Destination file' }, recursive: { type: 'boolean', short: 'r', description: 'Copy recursively' } }, examples: 'copy file1.txt file2.txt', run: ctx => { // Implementation } }) ``` -------------------------------- ### Comprehensive CLI Help with Examples Source: https://gunshi.dev/guide/essentials/auto-usage Displays generated help for commands with complex arguments and examples, including automatically generated negatable boolean flags. ```sh app (app v1.0.0) USAGE: app OPTIONS: -p, --path File or directory path to operate on -r, --recursive Operate recursively on directories --no-recursive Negatable of -r, --recursive -o, --operation Operation to perform: list, copy, move, or delete -h, --help Display this help message -v, --version Display this version EXAMPLES: # List files in current directory $ app --operation list # Copy files recursively $ app --operation copy --path ./source --recursive # Delete files $ app --operation delete --path ./temp ``` -------------------------------- ### Define multiple CLI examples Source: https://gunshi.dev/guide/essentials/declarative Use a multi-line string to provide several usage examples for a command. ```js import { define } from 'gunshi' const command = define({ name: 'deploy', description: 'Deploy application', args: { environment: { type: 'string', short: 'e', required: true, description: 'Target environment' }, tag: { type: 'string', short: 't', description: 'Version tag' }, dryRun: { type: 'boolean', description: 'Perform a dry run' } }, examples: ` # Deploy to production with a specific tag deploy --environment production --tag v1.2.3 # Deploy to staging with dry run deploy -e staging --dry-run # Deploy to development (using short option) deploy -e development # Deploy with multiple options deploy --environment production --tag latest --dry-run `.trim(), run: ctx => { // Implementation } }) ``` -------------------------------- ### Define dynamic CLI examples Source: https://gunshi.dev/guide/essentials/declarative Use a function to generate examples dynamically based on the command context. ```js import { define } from 'gunshi' const command = define({ name: 'serve', description: 'Start development server', args: { port: { type: 'number', short: 'p', default: 3000, description: 'Port number' }, host: { type: 'string', short: 'h', default: 'localhost', description: 'Host address' } }, examples: ctx => { // Generate examples dynamically based on context const appName = ctx.name || 'serve' return ` # Start server with default settings ${appName} # Start server on custom port ${appName} --port 8080 # Start server on all interfaces ${appName} --host 0.0.0.0 --port 3000 # Using short options ${appName} -h 192.168.1.100 -p 8080 `.trim() }, run: ctx => { console.log(`Server starting on ${ctx.values.host}:${ctx.values.port}`) } }) ``` -------------------------------- ### Initialize @gunshi/docs Source: https://gunshi.dev/release/v0.27 Run the experimental documentation configuration tool or install it as a dev dependency. ```sh npx @gunshi/docs ``` ```sh npm install --save-dev @gunshi/docs ``` -------------------------------- ### Standard Plugin README Structure Source: https://gunshi.dev/guide/plugin/guidelines A template for plugin README files, including installation instructions, usage examples, and links to API documentation. ```md # @yourorg/gunshi-plugin-{name} > Brief description of what your plugin does. ## Installation ```sh ### npm npm install --save @yourorg/gunshi-plugin-{name} ``` For other package managers, see [installation guide](./docs/install.md). ## Usage ```ts import { cli, define } from 'gunshi' import myPlugin from '@yourorg/gunshi-plugin-{name}' const command = define({ name: 'example', run: ctx => { ctx.extensions['yourorg:{name}'].someMethod() } }) await cli(process.argv.slice(2), command, { plugins: [myPlugin({ /* options */ })] }) ``` ## Plugin Options See [API documentation](./docs/api.md) for complete options. ## Examples See the [examples directory](./examples) for usage examples. ## License [MIT](http://opensource.org/licenses/MIT) ``` -------------------------------- ### Setup Bash Completion Source: https://gunshi.dev/guide/essentials/plugin-system Generate and source the completion script for Bash users. ```sh # Generate completion script and save it deploy-cli complete bash > ~/.local/share/bash-completion/completions/deploy-cli # Reload your shell configuration source ~/.bashrc # Now tab completion works! deploy-cli dep # Completes to: deploy-cli deploy ``` -------------------------------- ### Install Suggestion Plugin Source: https://gunshi.dev/guide/essentials/plugin-system Install the suggestion plugin using your preferred package manager. ```npm npm install --save @gunshi/plugin-suggestion ``` ```pnpm pnpm add @gunshi/plugin-suggestion ``` ```yarn yarn add @gunshi/plugin-suggestion ``` ```deno deno add jsr:@gunshi/plugin-suggestion ``` ```bun bun add @gunshi/plugin-suggestion ``` -------------------------------- ### Install Completion Plugin Source: https://gunshi.dev/guide/essentials/plugin-system Install the shell completion plugin using your preferred package manager. ```npm npm install --save @gunshi/plugin-completion ``` ```pnpm pnpm add @gunshi/plugin-completion ``` ```yarn yarn add @gunshi/plugin-completion ``` -------------------------------- ### Create a command instance Source: https://gunshi.dev/api/definition/functions/define Example of defining a command with a name, description, arguments, and a run function. ```ts const command = define({ name: 'test', description: 'A test command', args: { debug: { type: 'boolean', description: 'Enable debug mode', default: false } }, run: ctx => { if (ctx.values.debug) { console.debug('Debug mode is enabled'); } } }) ``` -------------------------------- ### View Installed Man Pages Source: https://gunshi.dev/guide/advanced/docs-gen Command to display a specific man page after installation. ```sh man my-tool ``` -------------------------------- ### Suggestion Plugin Output Examples Source: https://gunshi.dev/guide/essentials/plugin-system Example validation outputs provided by the suggestion plugin. ```txt Unknown option: --alow-reload Did you mean --allow-reload? ``` ```txt Command not found: rn Did you mean run? ``` -------------------------------- ### Install @gunshi/plugin Source: https://gunshi.dev/guide/plugin/introduction Commands to install the plugin development kit using various package managers. ```npm npm install --save @gunshi/plugin ``` ```pnpm pnpm add @gunshi/plugin ``` ```yarn yarn add @gunshi/plugin ``` ```deno deno add jsr:@gunshi/plugin ``` ```bun bun add @gunshi/plugin ``` -------------------------------- ### Register global options via plugin setup Source: https://gunshi.dev/guide/plugin/introduction Use addGlobalOption within the setup function to expose new flags to all commands. ```js setup: ctx => { ctx.addGlobalOption('debug', { type: 'boolean', description: 'Enable debug mode' }) } ``` -------------------------------- ### Test Setup Function Behavior Source: https://gunshi.dev/guide/plugin/testing Unit tests for the setup function using a mocked PluginContext to verify global option registration. ```typescript import { createCommandContext } from 'gunshi/plugin' import { describe, expect, test, vi } from 'vitest' import { debuggablePlugin } from './plugin.ts' // Mockup PluginContext function mockPluginContext(): PluginContext { return { subCommands: new Map(), globalOptions: new Map(), addGlobalOption: vi.fn(), addCommand: vi.fn(), hasCommand: vi.fn(), decorateCommand: vi.fn(), decorateUsageRenderer: vi.fn(), decorateHeaderRenderer: vi.fn(), decorateValidationErrorsRenderer: vi.fn() } } describe('debuggable plugin', () => { test('enable debug option', async () => { const mockPluginCtx = mockPluginContext() const plugin = debuggablePlugin({ enable: true }) // Run the plugin setup plugin(mockPluginCtx) expect(mockPluginCtx.addGlobalOption).toHaveBeenCalledWith( 'debug', expect.objectContaining({ type: 'boolean', description: 'Enable debug mode', default: false }) ) }) test('disable debug option', () => { const mockPluginCtx = mockPluginContext() const plugin = debuggablePlugin({ enable: false }) plugin(mockPluginCtx) expect(mockPluginCtx.addGlobalOption).not.toHaveBeenCalledWith( 'debug', expect.objectContaining({ type: 'boolean', description: 'Enable debug mode', default: false }) ) }) }) ``` -------------------------------- ### Register sub-commands via plugin setup Source: https://gunshi.dev/guide/plugin/introduction Use addCommand within the setup function to dynamically add new commands to the CLI. ```js setup: ctx => { ctx.addCommand('plugin-command', { name: 'plugin-command', run: ctx => console.log('Plugin command executed') }) } ``` -------------------------------- ### Define a plugin with global options Source: https://gunshi.dev/guide/plugin/getting-started Use the setup context to register global options available to all commands. ```js import { plugin } from 'gunshi/plugin' export default plugin({ id: 'debug', name: 'Debug Plugin', setup: ctx => { // Add a global option available to all commands ctx.addGlobalOption('debug', { type: 'boolean', short: 'd', description: 'Enable debug output' }) } }) ``` -------------------------------- ### Install @gunshi/definition Source: https://gunshi.dev/release/v0.27 Install the standalone package for creating reusable commands. ```sh npm install @gunshi/definition ``` -------------------------------- ### Positional Arguments Help Display Source: https://gunshi.dev/guide/essentials/auto-usage Example showing how positional arguments are documented in the help output. ```sh resource-manager (resource-manager v1.0.0) Manage resources USAGE: resource-manager manage ARGUMENTS: resource Type of resource to manage (e.g., user, project) OPTIONS: -h, --help Display this help message -v, --version Display this version ``` -------------------------------- ### Example Help Output with Option Types Source: https://gunshi.dev/guide/essentials/auto-usage The resulting help output when usageOptionType is enabled, showing type annotations for each option. ```sh OPTIONS: -p, --path [string] File or directory path to operate on -r, --recursive [boolean] Operate recursively on directories --no-recursive [boolean] Negatable of -r, --recursive -o, --operation [string] Operation to perform: list, copy, move, or delete -h, --help [boolean] Display this help message -v, --version [boolean] Display this version ``` -------------------------------- ### Generated help output Source: https://gunshi.dev/guide/essentials/getting-started Example of the formatted help message provided by the built-in renderer plugin. ```sh USAGE: COMMAND OPTIONS: -h, --help Display this help message -v, --version Display this version -n, --name Name to greet -u, --uppercase Convert greeting to uppercase ``` -------------------------------- ### Install i18n Plugin Source: https://gunshi.dev/guide/essentials/plugin-system Commands to install the internationalization plugin using various package managers. ```sh npm install --save @gunshi/plugin-i18n ``` ```sh pnpm add @gunshi/plugin-i18n ``` ```sh yarn add @gunshi/plugin-i18n ``` ```sh # For Deno projects, you can add Gunshi from JSR: deno add jsr:@gunshi/plugin-i18n ``` ```sh bun add @gunshi/plugin-i18n ``` -------------------------------- ### Define formatted examples with descriptions Source: https://gunshi.dev/guide/essentials/declarative Include descriptive text and notes within the example string to improve user readability. ```js import { define } from 'gunshi' const command = define({ name: 'git-flow', description: 'Git flow commands', args: { feature: { type: 'string', description: 'Feature name' }, hotfix: { type: 'string', description: 'Hotfix name' }, release: { type: 'string', description: 'Release version' } }, examples: ` Examples: # Start a new feature $ git-flow --feature user-authentication # Create a hotfix for production $ git-flow --hotfix critical-bug-fix # Prepare a new release $ git-flow --release 2.0.0 Notes: - Feature branches are created from develop - Hotfixes are created from master - Releases merge into both master and develop `.trim(), run: ctx => { // Implementation } }) ``` -------------------------------- ### CLI Command Execution Examples Source: https://gunshi.dev/guide/essentials/composable Demonstrates how the CLI behaves with valid sub-commands, unknown sub-commands, and help flags when fallbackToEntry is enabled. ```sh # Runs the create sub-command npx tsx src/cli.ts create --name resource resource-manager (resource-manager v1.0.0) Creating default resource: resource # Runs the list sub-command npx tsx src/cli.ts list --filter active resource-manager (resource-manager v1.0.0) Listing resources with filter: active # Falls back to main command when "unknown" sub-command is not found npx tsx src/cli.ts unknown --flag value resource-manager (resource-manager v1.0.0) Use a sub-command Run "resource-manager --help" for available commands # Runs the main command directly npx tsx src/cli.ts --help resource-manager (resource-manager v1.0.0) USAGE: resource-manager [COMMANDS] COMMANDS: [manage] Manage resources create Create a new resource list List all resources For more info, run any command with the `--help` flag: resource-manager --help resource-manager create --help resource-manager list --help OPTIONS: -h, --help Display this help message -v, --version Display this version ``` -------------------------------- ### CLI usage examples Source: https://gunshi.dev/guide/experimentals/parser-combinators Common command-line invocations for the defined serve CLI. ```sh # Basic usage with required entry file $ serve index.html # Specify host and port $ serve index.html --host localhost --port 8080 # Production mode with HTTPS $ serve dist/index.html --mode production --secure # Watch multiple directories with custom timeout $ serve src/index.js --watch src --watch public --timeout 1m # Add custom headers $ serve index.html --headers "Cache-Control: no-cache" --headers "X-Custom: value" # Verbose output $ serve index.html -v ``` -------------------------------- ### Execute and inspect nested sub-commands Source: https://gunshi.dev/guide/advanced/nested-sub-commands Examples of running nested commands and accessing help documentation for specific command levels. ```sh # Execute nested sub-command $ npx tsx cli.ts remote add --url https://example.com Adding remote: https://example.com # Show help for intermediate command $ npx tsx cli.ts remote --help Manage remotes USAGE: git remote [COMMANDS] COMMANDS: [remote] Manage remotes add Add a remote remove Remove a remote For more info, run any command with the `--help` flag: git remote --help git remote add --help git remote remove --help # Show help for leaf command $ npx tsx cli.ts remote add --help Add a remote USAGE: git remote add OPTIONS: --url Remote URL ``` -------------------------------- ### Install gunshi package Source: https://gunshi.dev/guide/advanced/ai-agent-detection The utility is included in the main gunshi package. ```sh npm install gunshi ``` -------------------------------- ### Main Command Help Output Source: https://gunshi.dev/guide/essentials/auto-usage Example of the hierarchical help structure generated for a main command with sub-commands. ```sh resource-manager (resource-manager v1.0.0) USAGE: resource-manager [COMMANDS] COMMANDS: [manage] Manage resources create Create a new resource list List all resources For more info, run any command with the `--help` flag: resource-manager --help resource-manager create --help resource-manager list --help OPTIONS: -h, --help Display this help message -v, --version Display this version ``` -------------------------------- ### Install Man Pages on Unix-like Systems Source: https://gunshi.dev/guide/advanced/docs-gen Provides commands for local and system-wide installation of man pages, including updating the man database. ```sh # Copy to your local man pages directory cp my-tool.1 ~/.local/share/man/man1/ # Update the man database mandb ``` ```sh # Copy to the system man pages directory (requires sudo) sudo cp my-tool.1 /usr/local/share/man/man1/ # Update the man database sudo mandb ``` -------------------------------- ### Implement a Theme Plugin Source: https://gunshi.dev/guide/advanced/custom-rendering A comprehensive example of a theme plugin that decorates headers, usage sections, and error displays. ```js import { plugin } from 'gunshi/plugin' const oceanTheme = plugin({ id: 'themes:ocean', name: 'Ocean Theme', setup(context) { const colors = { header: '\x1b[36m', // Cyan usage: '\x1b[34m', // Blue error: '\x1b[31m', // Red reset: '\x1b[0m' } // Add wave decoration to headers context.decorateHeaderRenderer(async (baseRenderer, ctx) => { const output = await baseRenderer(ctx) if (!output) return '' const waves = '~~~~~' return `${colors.header}${waves}\n${output}\n${waves}${colors.reset}` }) // Style usage sections context.decorateUsageRenderer(async (baseRenderer, ctx) => { const output = await baseRenderer(ctx) if (!output) return '' return output.replace(/^([A-Z][A-Z\s]+:)$/gm, `${colors.usage}$1${colors.reset}`) }) // Enhance error display context.decorateValidationErrorsRenderer(async (baseRenderer, ctx, error) => { const output = await baseRenderer(ctx, error) if (!output) return '' return `${colors.error}⚠️ ERROR\n${output}${colors.reset}` }) } }) ``` -------------------------------- ### Execute CLI Command Source: https://gunshi.dev/guide/plugin/type-system Example shell commands to execute the CLI application. ```sh API_TOKEN=xxx npx tsx cli.ts fetch --endpoint /users my-cli (my-cli v1.0.0) [LOG] GET https://api.example.com/users [ { "id": 1, "name": "Alice" }, { "id": 2, "name": "Bob" } ] API_TOKEN=xxx npx tsx cli.ts fetch --endpoint /users/1 my-cli (my-cli v1.0.0) [LOG] GET https://api.example.com/users/1 { "id": 1, "name": "Alice" } ``` -------------------------------- ### Viewing Custom Header Output Source: https://gunshi.dev/guide/advanced/custom-rendering Example of the rendered output when running the CLI with a custom header. ```sh ╔═════════════════════════════════════════╗ ║ MY-APP ║ ╚═════════════════════════════════════════╝ A CLI application with custom usage generation Version: 1.0.0 USAGE: my-app OPTIONS: -n, --name Name to use -h, --help Display this help message -v, --version Display this version ``` -------------------------------- ### Create a Domain-Specific Plugin Source: https://gunshi.dev/guide/plugin/introduction Example of extending plugin functionality with custom domain logic. ```ts // Domain-specific plugin for your application export default plugin({ id: 'api', extension: () => ({ client: new ApiClient(), authenticate: async (token: string) => { // Custom authentication logic } }) }) ``` -------------------------------- ### Optional Elements Usage Example Source: https://gunshi.dev/guide/essentials/auto-usage Demonstrates the use of square brackets to denote optional commands and parameters with default values. ```sh USAGE: app [COMMANDS] COMMANDS: [manage] Default command for managing resources OPTIONS: -t, --type [type] Resource type (default: standard) ``` -------------------------------- ### Sub-command Specific Help Output Source: https://gunshi.dev/guide/essentials/auto-usage Example of help output generated for a specific sub-command. ```sh resource-manager (resource-manager v1.0.0) Create a new resource USAGE: resource-manager create OPTIONS: -h, --help Display this help message -v, --version Display this version -n, --name Name of the resource -t, --type [type] Type of resource (default: default) ``` -------------------------------- ### Automatic LLM-Assisted Development Setup Source: https://gunshi.dev/guide/introduction/setup Use the CLI tool to automatically configure Claude Code skills for your project. ```sh npx @gunshi/docs ``` ```sh pnpm dlx @gunshi/docs ``` ```sh yarn dlx @gunshi/docs ``` ```sh bun x @gunshi/docs ``` -------------------------------- ### Displaying Help Messages in Different Locales Source: https://gunshi.dev/guide/advanced/internationalization Examples of how help messages appear when executed with different locale settings. ```sh USAGE: COMMAND OPTIONS: -n, --name Name to greet -f, --formal Use formal greeting -h, --help Display this help message -v, --version Display version ``` ```sh 使用法: COMMAND <オプション> オプション: -n, --name 挨拶する相手の名前 -f, --formal 丁寧な挨拶を使用する -h, --help このヘルプメッセージを表示 -v, --version バージョンを表示 ``` -------------------------------- ### Resolve arguments usage example Source: https://gunshi.dev/api/default/functions/resolveArgs Demonstrates parsing tokens against a schema and checking which values were explicitly provided. ```typescript // passed tokens: --port 3000 const { values, explicit } = resolveArgs({ port: { type: 'number', default: 8080 }, host: { type: 'string', default: 'localhost' } }, parsedTokens) values.port // 3000 values.host // 'localhost' explicit.port // true (explicitly provided) explicit.host // false (not provided, fallback to default) ``` -------------------------------- ### Required Elements Usage Example Source: https://gunshi.dev/guide/essentials/auto-usage Demonstrates the use of angle brackets to denote required options and parameters in generated help text. ```sh USAGE: app OPTIONS: -n, --name Name to use (required) ``` -------------------------------- ### Execution Output Examples Source: https://gunshi.dev/guide/plugin/decorators Expected console logs and final rendered output when running the CLI with decorators. ```sh [custom-a] Decorating usage // Logs after its baseRenderer returns [custom-b] Decorating usage // Logs after its baseRenderer returns ``` ```sh USAGE: my-cli OPTIONS: -h, --help Display this help message -v, --version Display this version 📦 Enhanced by Plugin A 🎨 Styled by Plugin B ``` -------------------------------- ### Registering Sub-Commands in a Plugin Source: https://gunshi.dev/guide/plugin/getting-started Use the plugin function to define an ID, name, and setup function that registers sub-commands via ctx.addCommand. ```js import { plugin } from 'gunshi/plugin' export default plugin({ id: 'tools', name: 'Developer Tools Plugin', setup: ctx => { // Add a new sub-command ctx.addCommand('clean', { name: 'clean', description: 'Clean build artifacts', args: { cache: { type: 'boolean', description: 'Also clear cache', default: false } }, run: ctx => { console.log('Cleaning build artifacts...') if (ctx.values.cache) { console.log('Clearing cache...') } console.log('Clean complete!') } }) // Add another sub-command ctx.addCommand('lint', { name: 'lint', description: 'Run linter', run: ctx => { console.log('Running linter...') console.log('No issues found!') } }) } }) ``` -------------------------------- ### Define a plugin with multiple dependencies Source: https://gunshi.dev/guide/plugin/dependencies Require multiple plugins to be loaded before this plugin's setup runs. ```js import { plugin } from 'gunshi/plugin' // Plugin with multiple dependencies export default plugin({ id: 'auth', dependencies: ['logger', 'cache'], setup: ctx => { console.log('3. Auth plugin loaded (depends on logger, cache)') }, extension: ctx => ({ isAuthenticated: () => { ctx.extensions.logger.log('Checking authentication') ctx.extensions.cache.get('auth-token') return true } }) }) ``` -------------------------------- ### Install Gunshi Source: https://gunshi.dev/guide/introduction/setup Install the stable version of Gunshi using your preferred package manager. ```sh npm install --save gunshi ``` ```sh pnpm add gunshi ``` ```sh yarn add gunshi ``` ```sh # For deno projects, you can add Gunshi from JSR: deno add jsr:@gunshi/gunshi ``` ```sh bun add gunshi ``` -------------------------------- ### Install Dry Run Plugin Source: https://gunshi.dev/guide/essentials/plugin-system Install the dry-run plugin using your preferred package manager. ```npm npm install --save @gunshi/plugin-dryrun ``` ```pnpm pnpm add @gunshi/plugin-dryrun ``` ```yarn yarn add @gunshi/plugin-dryrun ``` ```deno deno add jsr:@gunshi/plugin-dryrun ``` ```bun bun add @gunshi/plugin-dryrun ``` -------------------------------- ### Initialize minimal CLI Source: https://gunshi.dev/guide/essentials/plugin-system Use @gunshi/bone to explicitly define which plugins are included in your CLI. ```js import { cli } from '@gunshi/bone' import global from '@gunshi/plugin-global' import renderer from '@gunshi/plugin-renderer' // Only includes plugins you explicitly add await cli(process.argv.slice(2), command, { name: 'minimal-cli', plugins: [ global(), // Adds --help and --version options renderer() // Adds help text formatting ] }) ``` -------------------------------- ### Install std-env dependency Source: https://gunshi.dev/guide/advanced/ai-agent-detection Install the std-env package to access the underlying agent detection utilities. ```sh npm install std-env ``` -------------------------------- ### Run application and verify output Source: https://gunshi.dev/guide/plugin/dependencies Execute the CLI to observe the resolved load order and plugin interaction. ```sh node cli.js 1. Logger plugin loaded 2. Cache plugin loaded (depends on logger) 3. Auth plugin loaded (depends on logger, cache) 4. Metrics plugin loaded (depends on logger, optionally cache) 5. API plugin loaded (depends on auth, metrics) === Command execution starts === [LOG] Command running [LOG] Checking authentication [LOG] Cache get: auth-token [LOG] Tracking: api:/users [LOG] Cache get: metrics:api:/users === Command execution ends === ``` -------------------------------- ### Install i18n plugin dependencies Source: https://gunshi.dev/guide/advanced/internationalization Install the required i18n plugin and optional resource packages via npm. ```sh npm install @gunshi/plugin-i18n @gunshi/resources ``` -------------------------------- ### Configure CLI with Plugins and Hooks Source: https://gunshi.dev/guide/plugin/lifecycle Demonstrates defining a command and running the CLI with lifecycle hooks for error handling and cleanup. ```js import { cli, define } from 'gunshi' import logger from './logger.js' import lifecycle from './lifecycle.js' // Command definition const command = define({ name: 'build', args: { fail: { type: 'boolean' } }, run: ctx => { console.log('6. Actual command execution') console.log('Extension says:', ctx.extensions['lifecycle'].demo()) // Simulate an error for demonstration if (ctx.values.fail) { throw new Error('Build failed!') } } }) // Running the CLI with Command Hooks await cli(process.argv.slice(2), command, { // Plugin installation plugins: [logger, lifecycle], // Command Hooks are defined at CLI level onBeforeCommand: ctx => { console.log('4.5. onBeforeCommand hook') }, onAfterCommand: ctx => { console.log('8. onAfterCommand hook') // Cleanup can be done here ctx.extensions['lifecycle'].cleanup() }, onErrorCommand: (ctx, error) => { console.log('8. onErrorCommand hook:', error.message) // Error recovery or cleanup ctx.extensions['lifecycle'].cleanup() } }) ``` -------------------------------- ### Initialize CLI with plugins Source: https://gunshi.dev/guide/plugin/introduction Pass an array of plugin instances to the plugins configuration option when initializing the CLI. ```js import { cli } from 'gunshi' import i18n from '@gunshi/plugin-i18n' import custom from './plugins/custom.js' const entry = ctx => {} await cli(args, entry, { plugins: [i18n({ locale: 'en-US' }), custom()] }) ``` -------------------------------- ### Initialize CLI with a plugin Source: https://gunshi.dev/guide/plugin/getting-started Register a plugin within the Gunshi CLI entry point. ```js import { cli } from 'gunshi' import hello from './plugin.js' const entry = () => {} await cli(process.argv.slice(2), entry, { plugins: [hello] }) ``` -------------------------------- ### Define and Use a Plugin Extension Source: https://gunshi.dev/guide/plugin/extensions Demonstrates how to provide an extension via a plugin and access it within a command using the plugin ID. ```javascript import { plugin } from 'gunshi/plugin' import { define } from 'gunshi' // Plugin provides an extension const loggerPlugin = plugin({ id: 'logger', extension: () => ({ log: msg => console.log(msg), error: msg => console.error(msg) }) }) // Commands can use the extension const command = define({ name: 'deploy', run: ctx => { // Access extension via plugin ID ctx.extensions.logger.log('Starting deployment...') } }) ``` -------------------------------- ### Create a Hello World CLI with Gunshi Source: https://gunshi.dev/guide/essentials/getting-started Initializes a basic CLI application that executes a simple greeting function. ```js import { cli } from 'gunshi' // Run a simple command await cli(process.argv.slice(2), () => { console.log('Hello, World!') }) ``` -------------------------------- ### Implement a complete declarative CLI command Source: https://gunshi.dev/guide/essentials/declarative A full implementation of a greeting command demonstrating argument parsing, default values, and execution logic. ```js import { cli, define } from 'gunshi' // Define a command with declarative configuration const command = define({ // Command metadata name: 'greet', description: 'A greeting command with declarative configuration', // Command arguments with descriptions args: { name: { type: 'string', short: 'n', description: 'Name to greet', default: 'World' }, greeting: { type: 'string', short: 'g', default: 'Hello', description: 'Greeting to use' }, uppercase: { type: 'boolean', short: 'u', description: 'Display greeting in uppercase' } }, // Command examples examples: ` # Basic usage with default values $ node cli.js # Specify a name $ node cli.js --name Alice # Use custom greeting and name $ node cli.js -n Bob -g "Good morning" # Display in uppercase $ node cli.js --name Charlie --uppercase `, // Command execution function run: ctx => { const { name, greeting, uppercase } = ctx.values let message = `${greeting}, ${name}!` if (uppercase) { message = message.toUpperCase() } console.log(message) } }) // Run the command with the declarative configuration await cli(process.argv.slice(2), command, { name: 'greet-cli', version: '1.0.0', description: 'A simple greeting CLI' }) ``` -------------------------------- ### Usage of withDefault() Source: https://gunshi.dev/api/combinators/functions/withDefault Example showing how to apply a default value to an integer schema. ```ts const args = { port: withDefault(integer({ min: 1, max: 65535 }), 8080) } ``` -------------------------------- ### Get Resource Method Source: https://gunshi.dev/api/default/classes/DefaultTranslation Retrieves the entire resource object for a specified locale. ```ts getResource(locale: string): Record | undefined; ``` -------------------------------- ### Execute CLI with Plugins Source: https://gunshi.dev/guide/plugin/decorators Initializes the Gunshi CLI with the plugin containing the decorators. ```js import { cli } from 'gunshi' import lifo from './plugin.js' await cli( process.argv.slice(2), () => { console.log('Original command execution') }, { plugins: [lifo] } ) ``` -------------------------------- ### Dry Run Output Source: https://gunshi.dev/guide/essentials/plugin-system Example output when a command is executed with the --dry-run flag. ```sh [dryrun] publish package ``` -------------------------------- ### Displaying CLI Help Source: https://gunshi.dev/guide/essentials/composable Commands to view help documentation for the main CLI and specific sub-commands. ```sh # Show main command help $ npx tsx cli.ts --help # Show sub-command help $ npx tsx cli.ts create --help ``` ```sh node --experimental-strip-types cli.ts --help ``` -------------------------------- ### Initialize CLI application with plugins Source: https://gunshi.dev/guide/plugin/dependencies Register plugins with the CLI; Gunshi will automatically resolve the correct loading order regardless of the input array order. ```js import { cli, define } from 'gunshi' import logger from './logger.js' import cache from './cache.js' import auth from './auth.js' import metrics from './metrics.js' import api from './api.js' // Command to demonstrate plugin loading const command = define({ name: 'demo', run: ctx => { console.log('\n=== Command execution starts ===') // Use various plugin extensions ctx.extensions.logger.log('Command running') ctx.extensions.api.request('/users') console.log('=== Command execution ends ===') } }) // Run with plugins in random order - Gunshi will resolve correct order await cli(process.argv.slice(2), command, { plugins: [ // Intentionally provide in wrong order api, // Depends on auth, metrics auth, // Depends on logger, cache metrics, // Depends on logger, optionally cache logger, // No dependencies cache // Depends on logger ] }) ``` -------------------------------- ### Define locale JSON files Source: https://gunshi.dev/guide/advanced/internationalization Example structure for translation files used by the application. ```json { "description": "Greeting application", "arg:name": "Name to greet", "arg:formal": "Use formal greeting", "informal_greeting": "Hello", "formal_greeting": "Good day" } ``` ```json { "description": "挨拶アプリケーション", "arg:name": "挨拶する相手の名前", "arg:formal": "丁寧な挨拶を使用する", "informal_greeting": "こんにちは", "formal_greeting": "はじめまして" } ``` -------------------------------- ### Configure CLI Entry Point Source: https://gunshi.dev/guide/advanced/advanced-lazy-loading Initialize the CLI with lazy-loaded command definitions. ```ts import { cli } from 'gunshi' import { commandALazy, commandBLazy } from './commands.ts' async function main() { // Load package.json for version info const { default: pkgJsonModule } = await import('./package.json', { with: { type: 'json' } }) // Run the CLI with lazy-loaded commands await cli(process.argv.slice(2), commandALazy, { name: 'my-cli', version: pkgJson.version, description: 'My CLI application', subCommands: { [commandALazy.commandName]: commandALazy, [commandBLazy.commandName]: commandBLazy } }) } await main() ``` -------------------------------- ### Usage example for merge() Source: https://gunshi.dev/api/combinators/functions/merge Demonstrates combining two argument schemas into a single schema. ```ts const common = args({ verbose: boolean() }) const network = args({ host: required(string()), port: withDefault(integer(), 8080) }) const schema = merge(common, network) ``` -------------------------------- ### Access built-in help Source: https://gunshi.dev/guide/essentials/getting-started Invoke the help flag to view automatically generated command documentation. ```sh node cli.js --help ``` -------------------------------- ### Usage example of map() Source: https://gunshi.dev/api/combinators/functions/map Demonstrates applying a transformation to an integer schema to double its value. ```ts const args = { doubled: map(integer(), n => n * 2) } ``` -------------------------------- ### Report Unknown Option Error Source: https://gunshi.dev/guide/essentials/declarative Example of the error output generated when strict validation fails. ```txt Unknown option: --alow-reload ``` -------------------------------- ### Declare dependencies using string and object formats Source: https://gunshi.dev/guide/plugin/dependencies Demonstrates the two syntax options for defining plugin dependencies in the configuration. ```js // Simple string format for required dependencies dependencies: ['logger', 'auth'] // Object format for optional dependencies dependencies: [ 'logger', // Required dependency { id: 'cache', optional: true } // Optional dependency ] ``` -------------------------------- ### Recommended Project Structure Source: https://gunshi.dev/guide/essentials/composable A directory layout for organizing CLI commands into separate files for better maintainability. ```sh my-cli/ ├── src/ │ ├── commands/ │ │ ├── create.ts # Create command implementation │ │ └── list.ts # List command implementation │ ├── main.ts # Main command definition │ └── cli.ts # CLI entry point ├── package.json └── tsconfig.json ``` -------------------------------- ### Define GunshiParams types Source: https://gunshi.dev/guide/advanced/type-system Examples of defining command parameters with arguments only or with additional plugin extensions. ```ts // Simple usage - just arguments type SimpleParams = GunshiParams<{ args: { port: { type: 'number' } } }> // With extensions from plugins type FullParams = GunshiParams<{ args: { port: { type: 'number' } } extensions: { logger: Logger } }> ``` -------------------------------- ### Initialize CLI with Built-in Plugins Source: https://gunshi.dev/guide/essentials/plugin-system The cli() function automatically includes the global plugin, providing --help and --version support. ```js import { cli, define } from 'gunshi' const command = define({ name: 'app', description: 'My CLI application', run: ctx => { console.log('Running application') } }) await cli(process.argv.slice(2), command, { name: 'my-app', version: '1.0.0' }) ``` -------------------------------- ### Detecting Multi-Way Circular Dependencies Source: https://gunshi.dev/guide/plugin/dependencies Example of a three-way circular dependency chain that prevents plugin initialization. ```javascript import { plugin } from 'gunshi/plugin' // Three-way circular dependency const pluginX = plugin({ id: 'X', dependencies: ['Y'], setup: ctx => {} }) const pluginY = plugin({ id: 'Y', dependencies: ['Z'], setup: ctx => {} }) const pluginZ = plugin({ id: 'Z', dependencies: ['X'], // Creates cycle: X → Y → Z → X setup: ctx => {} }) // Circular dependency detected: `x -> y -> z -> x` ``` -------------------------------- ### Viewing Customized CLI Output Source: https://gunshi.dev/guide/plugin/decorators Execute the CLI with the help flag to verify the applied renderer decorations. ```sh node cli.js --help 🚀 My CLI v1.0.0 my-cli (my-cli v1.0.0) USAGE: my-cli OPTIONS: -h, --help Display this help message -v, --version Display this version --output Generated: 2025-08-15T14:26:43.121Z ``` -------------------------------- ### CommandExamplesFetcher Signature Source: https://gunshi.dev/api/default/type-aliases/CommandExamplesFetcher Defines the function signature for fetching command examples based on the provided command context. ```ts export type CommandExamplesFetcher = (ctx: Readonly>) => Awaitable ``` -------------------------------- ### Define a Gunshi Plugin Source: https://gunshi.dev/guide/plugin/lifecycle Implements the plugin lifecycle including setup, extension creation, and command decoration. ```js import { plugin } from 'gunshi/plugin' export default plugin({ id: 'lifecycle', dependencies: ['logger'], // Step C: Dependency resolution // Step D: Setup execution setup: ctx => { console.log('1. lifecycle plugin setup phase started') // Register global option ctx.addGlobalOption('verbose', { type: 'boolean', alias: 'v', description: 'Verbose output' }) // Add sub-command ctx.addCommand('status', { name: 'status', run: ctx => console.log('Status: OK') }) // Register decorators (LIFO order) ctx.decorateCommand(runner => async ctx => { console.log('5. Command decorator (before)') const result = await runner(ctx) console.log('7. Command decorator (after)') return result }) console.log('2. Setup phase completed') }, // Step H: Extension creation (during CommandContext creation) extension: (ctx, cmd) => { console.log('3. Extension created for:', cmd.name) return { demo: () => 'Hello from extension', cleanup: () => console.log('9. Extension cleanup') } }, // Step H: Post-extension callback (immediately after extension creation) onExtension: (ctx, cmd) => { console.log('4. All extensions ready') } }) ``` -------------------------------- ### Decorate renderers via plugin setup Source: https://gunshi.dev/guide/plugin/introduction Use decorateUsageRenderer to wrap or modify the output of existing renderers. ```js setup: ctx => { ctx.decorateUsageRenderer(async (baseRenderer, ctx) => { const base = await baseRenderer(ctx) return `${base}\n\nEnhanced by plugin` }) } ``` -------------------------------- ### Configure CLI with metadata Source: https://gunshi.dev/guide/essentials/declarative Pass an options object to the cli function to define application metadata like name, version, and description. ```js await cli(process.argv.slice(2), command, { name: 'app-name', version: '1.0.0', description: 'Application description' // Additional configuration options }) ```