### Quick Start: Basic CLI with @truyman/cli Source: https://github.com/bentruyman/cli/blob/main/README.md A minimal example demonstrating how to create a simple command-line interface that accepts a string argument and prints a greeting. It shows the basic structure of defining a command and running it. ```typescript import { command, run } from "@truyman/cli"; const greet = command({ name: "greet", args: [{ name: "name", type: "string" }], handler: ([name]) => console.log(`Hello, ${name}!`), }); run(greet, process.argv.slice(2)); ``` -------------------------------- ### Full Example: Advanced CLI with @truyman/cli Source: https://github.com/bentruyman/cli/blob/main/README.md An example showcasing more advanced features like descriptions, versions, options (boolean and numeric), and looping output. This demonstrates how to define richer command structures. ```typescript import { command, run } from "@truyman/cli"; const greet = command({ name: "greet", description: "A friendly greeting CLI", version: "1.0.0", args: [ { name: "name", type: "string", description: "Who to greet" }, ], options: { shout: { type: "boolean", long: "shout", short: "s", description: "LOUD MODE", }, times: { type: "number", long: "times", short: "n", description: "Repeat N times", }, }, handler: ([name], { shout, times }) => { let msg = `Hello, ${name}!`; if (shout) msg = msg.toUpperCase(); for (let i = 0; i < (times || 1); i++) { console.log(msg); } }, }); run(greet, process.argv.slice(2)); ``` -------------------------------- ### Install @truyman/cli Source: https://github.com/bentruyman/cli/blob/main/README.md Installs the @truyman/cli package using npm. This is the first step to using the library in your project. ```bash npm i @truyman/cli ``` -------------------------------- ### API: Define Command Options Source: https://github.com/bentruyman/cli/blob/main/README.md Example of defining options (flags) for a command. It shows how to specify the type, long and short flags, and a description for each option. ```typescript { verbose: { type: "boolean", long: "verbose", short: "v", description: "Extra output" } } ``` -------------------------------- ### Execute Commands with Built-in Help and Error Handling using run() in TypeScript Source: https://context7.com/bentruyman/cli/llms.txt Illustrates how to use the `run()` function from @truyman/cli as the top-level entry point for executing commands. It automatically handles `--help`, `--version`, and provides formatted error messages with context, simplifying command-line application development. This example uses TypeScript. ```typescript import { command, run } from "@truyman/cli"; const deploy = command({ name: "deploy", description: "Deploy application", args: [ { name: "environment", type: "string", description: "Target environment" }, ] as const, options: { force: { type: "boolean", short: "f", description: "Skip confirmation prompts", }, region: { type: "string", short: "r", required: true, description: "AWS region", }, }, handler: ([environment], { force, region }) => { console.log(`Deploying to ${environment} in ${region}`); if (force) console.log("Force mode enabled"); }, }); run(deploy, process.argv.slice(2)); // Usage: // $ deploy --help // Usage: deploy [options] // // Deploy application // // Arguments: // environment Target environment // // Options: // -f, --force Skip confirmation prompts // -r, --region= AWS region (required) // -h, --help Show this help message // // $ deploy production // Error: Missing required option: --region // // Usage: deploy [options] // ... // // $ deploy production --region us-east-1 // Deploying to production in us-east-1 ``` -------------------------------- ### Create Type-Safe CLI Command with @truyman/cli Source: https://context7.com/bentruyman/cli/llms.txt Defines a leaf command named 'greet' with positional arguments and options using the `command()` factory function. The handler function receives arguments and options with inferred types, simplifying development and eliminating the need for manual type checking. This example demonstrates how to define arguments, boolean and number options, and a custom greeting option. ```typescript import { command, run } from "@truyman/cli"; const greet = command({ name: "greet", description: "A friendly greeting CLI", version: "1.0.0", args: [ { name: "name", description: "Name of the person to greet", type: "string", }, ] as const, options: { shout: { type: "boolean", short: "s", description: "Print the greeting in uppercase", }, times: { type: "number", short: "n", description: "Number of times to repeat the greeting", }, greeting: { type: "string", short: "g", description: "Custom greeting to use instead of 'Hello'", }, }, handler: ([name], { shout, times, greeting }) => { // name is typed as string // shout is typed as boolean // times is typed as number | undefined // greeting is typed as string | undefined const word = greeting || "Hello"; let message = `${word}, ${name} চাঁ`; if (shout) { message = message.toUpperCase(); } const count = times || 1; for (let i = 0; i < count; i++) { console.log(message); } }, }); run(greet, process.argv.slice(2)); // Usage: // $ bun greet.ts World // Hello, World! // // $ bun greet.ts Ada --shout -n 3 // HELLO, ADA! // HELLO, ADA! // HELLO, ADA! // // $ bun greet.ts Bob -g "Howdy" --shout // HOWDY, BOB! ``` -------------------------------- ### Define Parent Commands with Subcommands using command() in TypeScript Source: https://context7.com/bentruyman/cli/llms.txt Demonstrates how to create a parent command that routes to subcommands. Parent commands can define options inherited by all subcommands. Subcommands can define their own specific options and arguments. This example uses TypeScript and the @truyman/cli library. ```typescript import { command, run } from "@truyman/cli"; import type { Options } from "@truyman/cli"; // Define global options shared across all subcommands export const GlobalOptions = { verbose: { type: "boolean", long: "verbose", short: "v", description: "Enable verbose output", }, config: { type: "string", long: "config", short: "c", description: "Path to config file", }, } as const satisfies Options; // Subcommand that inherits global options const add = command({ name: "add", description: "Add a new note", inherits: GlobalOptions, args: [{ name: "content", type: "string", description: "Note content" }] as const, options: { tag: { type: "string", long: "tag", short: "t", description: "Tag for the note", }, }, handler: ([content], { verbose, config, tag }) => { // verbose and config are inherited from parent // tag is defined on this command // All are properly typed if (verbose) { console.log(`[verbose] Config: ${config ?? "default"}`); console.log(`[verbose] Adding note...`); } console.log(`Added note: "${content}"${tag ? ` [${tag}]` : ""}`); }, }); const list = command({ name: "list", description: "List all notes", inherits: GlobalOptions, options: { tag: { type: "string", long: "tag", short: "t", description: "Filter by tag", }, limit: { type: "number", long: "limit", short: "n", description: "Max notes to show", }, }, handler: (_, { verbose, config, tag, limit }) => { if (verbose) { console.log(`[verbose] Config: ${config ?? "default"}`); console.log(`[verbose] Fetching notes...`); } console.log("Listing notes..."); if (tag) console.log(` Filtered by tag: ${tag}`); if (limit) console.log(` Limited to: ${limit}`); }, }); // Parent command with subcommands const notes = command({ name: "notes", description: "A simple notes manager", version: "1.0.0", options: GlobalOptions, subcommands: [add, list], }); run(notes, process.argv.slice(2)); // Usage: // $ notes add "Buy groceries" --tag shopping --verbose // [verbose] Config: default // [verbose] Adding note... // Added note: "Buy groceries" [shopping] // // $ notes list --config ./config.json --limit 10 // Listing notes... // Limited to: 10 ``` -------------------------------- ### API: Define Positional Arguments Source: https://github.com/bentruyman/cli/blob/main/README.md Example of defining a positional argument for a command. It specifies the argument's name, type (string, number, boolean), optionality, and description. ```typescript { name: "file", type: "string", optional: true, description: "Input file" } ``` -------------------------------- ### run() - Execute Commands with Built-in Help and Error Handling Source: https://context7.com/bentruyman/cli/llms.txt The main entry point for executing CLI commands, automatically managing help messages, version information, and formatted error reporting. ```APIDOC ## run() - Execute Commands with Built-in Help and Error Handling ### Description The top-level entry point for running commands. Automatically handles `--help`, `--version`, and provides formatted error messages with context. ### Method `run()` ### Endpoint N/A (CLI command execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Not applicable for command execution. ### Request Example ```typescript import { command, run } from "@truyman/cli"; const deploy = command({ name: "deploy", description: "Deploy application", args: [ { name: "environment", type: "string", description: "Target environment" }, ] as const, options: { force: { type: "boolean", short: "f", description: "Skip confirmation prompts", }, region: { type: "string", short: "r", required: true, description: "AWS region", }, }, handler: ([environment], { force, region }) => { console.log(`Deploying to ${environment} in ${region}`); if (force) console.log("Force mode enabled"); }, }); run(deploy, process.argv.slice(2)); ``` ### Response N/A (CLI command execution) ### Response Example ``` Usage: $ deploy --help Usage: deploy [options] Deploy application Arguments: environment Target environment Options: -f, --force Skip confirmation prompts -r, --region= AWS region (required) -h, --help Show this help message $ deploy production Error: Missing required option: --region Usage: deploy [options] ... $ deploy production --region us-east-1 Deploying to production in us-east-1 ``` ``` -------------------------------- ### Subcommands: Create a Command with Inherited Options Source: https://github.com/bentruyman/cli/blob/main/README.md Shows how to create a specific command (e.g., 'add') that inherits global options. This ensures that options like '--verbose' are correctly parsed and available within the command's handler. ```typescript // commands/add.ts import { command } from "@truyman/cli"; import { GlobalOptions } from "../options"; export const add = command({ name: "add", inherits: GlobalOptions, args: [{ name: "url", type: "string" }] as const, handler: ([url], { verbose }) => { if (verbose) console.log("[verbose] Adding remote..."); console.log(`Added ${url}`); }, }); ``` -------------------------------- ### Generate CLI Help Text with TypeScript Source: https://context7.com/bentruyman/cli/llms.txt This snippet demonstrates how to use the @truyman/cli library to define a command-line interface command and programmatically access its generated help text. It showcases defining command name, description, version, arguments, and options, then utilizing the `help()` method for output. ```typescript import { command } from "@truyman/cli"; const cmd = command({ name: "server", description: "Start development server", version: "2.0.0", args: [{ name: "port", type: "number", optional: true }] as const, options: { host: { type: "string", short: "h", default: "localhost", description: "Host to bind to", }, watch: { type: "boolean", short: "w", description: "Watch for file changes", }, }, handler: () => {}, }); console.log(cmd.help()); ``` -------------------------------- ### Subcommands: Nest Commands with @truyman/cli Source: https://github.com/bentruyman/cli/blob/main/README.md Illustrates how to build a nested command structure (e.g., 'git remote add'). It shows how to define parent commands with options and subcommands, enabling complex CLI architectures. ```typescript // index.ts import { command, run } from "@truyman/cli"; import { GlobalOptions } from "./options"; import { add } from "./commands/add"; const remote = command({ name: "remote", options: GlobalOptions, subcommands: [add], }); const git = command({ name: "git", subcommands: [remote], }); run(git, process.argv.slice(2)); ``` -------------------------------- ### Subcommands: Define Global Options with @truyman/cli Source: https://github.com/bentruyman/cli/blob/main/README.md Demonstrates how to define shared options that can be inherited by subcommands. This promotes code reuse and consistency in CLI argument parsing. ```typescript // options.ts import type { Options } from "@truyman/cli"; export const GlobalOptions = { verbose: { type: "boolean", long: "verbose", short: "v" }, } as const satisfies Options; ``` -------------------------------- ### Configure Advanced Option Types for CLI Commands (TypeScript) Source: https://context7.com/bentruyman/cli/llms.txt Illustrates advanced option configurations for command-line interfaces using @truyman/cli. This includes setting default values, allowing multiple values for an option, enabling negatable booleans, and defining required options with custom placeholders. The handler function receives destructured options with correct types. ```typescript import { command, run } from "@truyman/cli"; const build = command({ name: "build", description: "Build project", options: { // Boolean with negatable flag colors: { type: "boolean", negatable: true, default: true, description: "Colorize output", }, // Multiple string values exclude: { type: "string", multiple: true, short: "e", description: "Patterns to exclude", }, // Number with default workers: { type: "number", short: "w", default: 4, description: "Number of worker threads", }, // Required string with custom placeholder output: { type: "string", short: "o", required: true, placeholder: "path", description: "Output directory", }, }, handler: (_, { colors, exclude, workers, output }) => { // colors is typed as boolean (never undefined due to default) // exclude is typed as string[] // workers is typed as number (never undefined due to default) // output is typed as string (never undefined due to required) console.log(`Building to ${output}`); console.log(`Workers: ${workers}`); console.log(`Colors: ${colors ? "enabled" : "disabled"}`); if (exclude.length > 0) { console.log(`Excluding: ${exclude.join(", ")}`); } }, }); run(build, ["--output", "dist", "--exclude", "*.test.ts", "-e", "*.spec.ts", "--no-colors"]); // Building to dist // Workers: 4 // Colors: disabled // Excluding: *.test.ts, *.spec.ts ``` -------------------------------- ### Define Positional Arguments: Optional and Variadic CLI Commands (TypeScript) Source: https://context7.com/bentruyman/cli/llms.txt Demonstrates defining command-line interfaces with positional arguments that can be optional or variadic. This allows for flexible command signatures, where arguments can be omitted or multiple values can be accepted for a single argument. It uses the @truyman/cli library. ```typescript import { command, run } from "@truyman/cli"; const copy = command({ name: "copy", description: "Copy files", args: [ { name: "source", type: "string", description: "Source file" }, { name: "dest", type: "string", description: "Destination", optional: true }, ] as const, handler: ([source, dest]) => { // source is typed as string // dest is typed as string | undefined console.log(`Copying ${source} to ${dest ?? "current directory"}`); }, }); const concat = command({ name: "concat", description: "Concatenate files", args: [ { name: "files", type: "string", description: "Files to concatenate", variadic: true }, ] as const, handler: ([files]) => { // files is typed as string[] if (files.length === 0) { console.log("No files specified"); } else { console.log(`Concatenating ${files.length} files: ${files.join(", ")}`); } }, }); run(copy, ["file.txt"]); // Copying file.txt to current directory run(copy, ["file.txt", "backup.txt"]); // Copying file.txt to backup.txt run(concat, ["a.txt", "b.txt", "c.txt"]); // Concatenating 3 files: a.txt, b.txt, c.txt ``` -------------------------------- ### command() - Parent Commands with Subcommands Source: https://context7.com/bentruyman/cli/llms.txt Defines a parent command that routes to subcommands, allowing for shared options and a hierarchical command structure. ```APIDOC ## command() - Parent Commands with Subcommands ### Description Creates a parent command that routes to subcommands. Parent commands cannot have handlers or positional arguments, but can define options that are passed to all subcommands. ### Method `command()` ### Endpoint N/A (CLI command definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Not applicable for command definition. ### Request Example ```typescript import { command, run } from "@truyman/cli"; import type { Options } from "@truyman/cli"; export const GlobalOptions = { verbose: { type: "boolean", long: "verbose", short: "v", description: "Enable verbose output", }, config: { type: "string", long: "config", short: "c", description: "Path to config file", }, } as const satisfies Options; const add = command({ name: "add", description: "Add a new note", inherits: GlobalOptions, args: [{ name: "content", type: "string", description: "Note content" }] as const, options: { tag: { type: "string", long: "tag", short: "t", description: "Tag for the note", }, }, handler: ([content], { verbose, config, tag }) => { if (verbose) { console.log(`[verbose] Config: ${config ?? "default"}`); console.log(`[verbose] Adding note...`); } console.log(`Added note: "${content}"${tag ? ` [${tag}]` : ""}`); }, }); const list = command({ name: "list", description: "List all notes", inherits: GlobalOptions, options: { tag: { type: "string", long: "tag", short: "t", description: "Filter by tag", }, limit: { type: "number", long: "limit", short: "n", description: "Max notes to show", }, }, handler: (_, { verbose, config, tag, limit }) => { if (verbose) { console.log(`[verbose] Config: ${config ?? "default"}`); console.log(`[verbose] Fetching notes...`); } console.log("Listing notes..."); if (tag) console.log(` Filtered by tag: ${tag}`); if (limit) console.log(` Limited to: ${limit}`); }, }); const notes = command({ name: "notes", description: "A simple notes manager", version: "1.0.0", options: GlobalOptions, subcommands: [add, list], }); run(notes, process.argv.slice(2)); ``` ### Response N/A (CLI command definition) ### Response Example ``` Usage: $ notes add "Buy groceries" --tag shopping --verbose [verbose] Config: default [verbose] Adding note... Added note: "Buy groceries" [shopping] $ notes list --config ./config.json --limit 10 Listing notes... Limited to: 10 ``` ``` -------------------------------- ### Implement Error Handling for CLI Commands with Custom Errors (TypeScript) Source: https://context7.com/bentruyman/cli/llms.txt Showcases the built-in error handling mechanisms of the @truyman/cli library. It demonstrates how various errors like missing arguments, invalid types, missing options, and unknown subcommands are caught and handled automatically by the `run()` function, often displaying helpful error messages and automatically showing the command's help text. ```typescript import { command, run, MissingArgumentError, InvalidArgumentError, MissingOptionError, InvalidOptionError, MissingSubcommandError, UnknownSubcommandError, } from "@truyman/cli"; const calculate = command({ name: "calculate", args: [ { name: "operation", type: "string" }, { name: "value", type: "number" }, ] as const, options: { precision: { type: "number", required: true, description: "Decimal precision", }, }, handler: ([operation, value], { precision }) => { console.log(`${operation}(${value}) with precision ${precision}`); }, }); // Missing required argument run(calculate, []); // Throws MissingArgumentError: Missing required argument: operation // Displays help text automatically // Invalid argument type run(calculate, ["sqrt", "not-a-number"]); // Throws InvalidArgumentError: value must be a number // Displays error message and help text // Missing required option run(calculate, ["sqrt", "16"]); // Throws MissingOptionError: Missing required option: --precision // Displays error message and help text // Invalid option type run(calculate, ["sqrt", "16", "--precision", "abc"]); // Throws InvalidOptionError: precision must be a number // Displays error message and help text // For parent commands: const cli = command({ name: "cli", subcommands: [calculate], }); // Missing subcommand run(cli, []); // Throws MissingSubcommandError: Missing subcommand for 'cli'. Available: calculate // Unknown subcommand run(cli, ["unknown"]); // Throws UnknownSubcommandError: Unknown subcommand 'unknown'. Available: calculate ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.