### Setup Bun Environment with Deno Task Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Prepare the project for running Bun tests. Installs Bun and its dependencies. ```bash deno task setup:bun ``` -------------------------------- ### Complete CLI Example with HelpCommand Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md This snippet demonstrates a full CLI application setup using Cliffy, including global options, commands, and the integration of the HelpCommand. It shows how to define a CLI with various subcommands and options, and how the help command is automatically included. ```typescript import { Command } from "@cliffy/command"; import { HelpCommand } from "@cliffy/command/help"; const cli = new Command() .name("todo") .description("A todo list management CLI") .version("1.0.0") .option("-v, --verbose", "Enable verbose output") .globalOption("--config ", "Config file") .command("list", new Command() .description("List all todos") .option("-s, --sort ", "Sort order", { default: "added" }) .action(({ verbose, sort }) => { console.log(`Listing todos (sorted by ${sort})`); }) ) .command("add", new Command() .description("Add a new todo") .arguments("") .option("-p, --priority ", "Priority") .action(({ priority }, text) => { console.log(`Added: ${text} (${priority})`); }) ) .command("help", new HelpCommand({ colors: true, long: true, })) .parse(Deno.args); ``` -------------------------------- ### Setup Node.js Environment with Deno Task Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Prepare the project for running Node.js tests. Installs Node.js and pnpm dependencies. ```bash deno task setup:node ``` -------------------------------- ### Run Deno Example Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Execute an example script using the Deno runtime. ```bash deno run examples/prompt/checkbox.ts ``` -------------------------------- ### Add Command Example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/command.md Use the `example` method to add usage examples to your command. This helps users understand how to invoke the command with different arguments. ```typescript new Command() .example("List todos", "$ deno run main.ts list") .example("Add todo", "$ deno run main.ts add 'buy milk'") ``` -------------------------------- ### example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/command.md Adds an example to the command, illustrating how to use it with sample commands and descriptions. ```APIDOC ## example ### Description Add an example to the command. ### Method ```typescript example(name: string, description: string): this ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (string) - Required - Example name - **description** (string) - Required - Example description and code ### Request Example ```typescript new Command() .example("List todos", "$ deno run main.ts list") .example("Add todo", "$ deno run main.ts add 'buy milk'") ``` ### Response #### Success Response (200) - **this** (this) - Returns the command builder instance for chaining. #### Response Example None provided. ``` -------------------------------- ### Run Bun Example with Deno Task Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Execute an example script within a Bun environment managed by Deno tasks. ```bash deno task bun examples/prompt/checkbox.ts ``` -------------------------------- ### Run Node.js Example with Deno Task Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Execute an example script within a Node.js environment managed by Deno tasks. ```bash deno task node examples/prompt/checkbox.ts ``` -------------------------------- ### HelpCommand Initialization Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Example of how to instantiate the HelpCommand with specific options to customize the help output. ```typescript const help = new HelpCommand({ colors: true, indent: 4, long: true, types: true, }); ``` -------------------------------- ### Complete CLI Example with Multiple Completions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md A comprehensive example demonstrating a CLI application with multiple options and commands, each featuring custom completion logic. This includes environment, region, service name, and version completions. ```typescript import { Command } from "@cliffy/command"; import { CompletionsCommand } from "@cliffy/command/completions"; const cli = new Command() .name("deploy") .description("Deployment management CLI") .option("-e, --environment ", "Environment") .complete("environment", async () => ["dev", "staging", "prod"]) .option("--region ", "AWS region") .complete("region", async () => ["us-east-1", "us-west-2", "eu-west-1"]) .option("--service ", "Service name") .complete("service", async () => { // Could fetch from API return ["api", "web", "worker"]; }) .command("deploy", new Command() .description("Deploy application") .arguments("") .complete("version", async () => ["1.0.0", "1.1.0", "2.0.0"]) .action(({ environment, region, service }, version) => { console.log(`Deploying ${service} v${version} to ${environment}/${region}`); }) ) .command("rollback", new Command() .description("Rollback deployment") .arguments("") .complete("version", async () => ["1.0.0", "1.1.0", "2.0.0"]) .action(({ environment }, version) => { console.log(`Rolling back to ${version} in ${environment}`); }) ) .command("completions", new CompletionsCommand()) .parse(Deno.args); ``` -------------------------------- ### Cliffy Command Option Examples Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/configuration.md Demonstrates how to configure various command-line options using the `option` method in Cliffy. Shows examples for setting types, defaults, dependencies, conflicts, and collection behavior. ```typescript const cmd = new Command() .option("-v, --verbose", "Verbose output", { type: "boolean", default: false, aliases: ["v"], description: "Enable verbose logging", }) .option("-o, --output ", "Output file", { type: "string", required: true, depends: ["--format"], conflicts: ["--stdout"], }) .option("-t, --tag [tags:string]", "Tags", { collect: true, variadic: true, }); ``` -------------------------------- ### Verify Completions Installation (Bash, Zsh, Fish) Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md These commands help verify if completions are correctly installed for your application in different shells. ```bash # Bash complete -p app # Zsh which _app # Fish builtin functions __fish_complete_app ``` -------------------------------- ### Volume Converter Example with Unit Selection Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/flags.md A practical example demonstrating how to parse arguments for a volume converter, allowing users to specify the unit (liters or gallons). It uses Deno.args for input and defines a default unit. ```typescript import { parseFlags } from "@cliffy/flags"; const { flags: { unit }, unknown: [volume] } = parseFlags(Deno.args, { flags: [{ name: "unit", aliases: ["u"], type: "string", default: "l", }], }); if (unit === "l") { const gallons = Number(volume) * 0.264172; console.log(`${volume} L is ${gallons.toFixed(2)} gal.`); } else { const liters = Number(volume) / 0.264172; console.log(`${volume} gal is ${liters.toFixed(2)} L.`); } ``` -------------------------------- ### Example Type Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/types.md Represents a command example, including its name and a description or the actual code for the example. ```APIDOC ## Example Type ### Description Represents a command example. ### Fields #### name (string) - Yes - Example title #### description (string) - Yes - Example code or description ``` -------------------------------- ### Configure Command Arguments Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/configuration.md Example demonstrating how to configure arguments for a command using the CommandArgumentOptions. ```typescript const cmd = new Command() .arguments(" [output:string]", { type: "string", description: "Input and optional output files", }) .arguments("", { variadic: true, description: "Multiple file paths", }); ``` -------------------------------- ### Detailed Table Example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/configuration.md Provides a concrete example of creating and configuring a Cliffy Table with specific header, body, border, padding, indentation, max width, and column settings. ```typescript const table = new Table() .header(["Name", "Value"]) .body([["Item", "100"]]) .border(border.rounded) .padding([1, 2, 1, 2]) .indent(2) .maxWidth(80) .column(0, { width: 20 }) .column(1, { align: "right" }); ``` -------------------------------- ### Generate and Install Zsh Completions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md Generate the Zsh completion script and save it to the system's Zsh site-functions directory. After installation, run `compinit` to enable Zsh completions. ```bash $ app completions zsh | sudo tee /usr/share/zsh/site-functions/_app $ compinit ``` -------------------------------- ### Install Shell Completions Script Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md A bash script to install completions for bash, zsh, and fish shells. It dynamically determines the shell and installs completions to the appropriate system directory. ```bash #!/bin/bash # install-completions.sh SHELL_NAME=${1:-bash} APP_NAME="myapp" case $SHELL_NAME in bash) myapp completions bash | sudo tee /usr/share/bash-completion/completions/myapp echo "Bash completions installed" ;; zsh) myapp completions zsh | sudo tee /usr/share/zsh/site-functions/_myapp echo "Zsh completions installed" ;; fish) myapp completions fish | sudo tee /usr/share/fish/vendor_completions.d/myapp.fish echo "Fish completions installed" ;; *) echo "Usage: $0 {bash|zsh|fish}" exit 1 ;; esac ``` -------------------------------- ### Define Command Example Type Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/types.md Represents a command example, including its name and a description which can be either text or the actual code. ```typescript interface Example { name: string; // Example name description: string; // Example description/code } ``` -------------------------------- ### Run Bun Tests with Deno Task Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Execute tests using the Bun runtime. Requires Bun setup. ```bash deno task test:bun ``` -------------------------------- ### List Prompt Example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/configuration.md Illustrates how to configure and use the List prompt, specifying the message, available options, a default selection, and enabling search functionality. ```typescript const choice = await new List({ message: "Choose", options: ["A", "B", "C"], default: 0, search: true, }).prompt(); ``` -------------------------------- ### Standard Help Output Format Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Illustrates the default, concise format for help messages, including usage, options, commands, and examples. ```text Usage: command [OPTIONS] [ARGUMENTS] Description: Command description goes here. Options: -h, --help Show help information (default: false) -v, --verbose Enable verbose output (default: false) Commands: list List all items add Add a new item Examples: $ command list $ command add "My Item" ``` -------------------------------- ### Input Prompt Example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/configuration.md Demonstrates the configuration and usage of the Input prompt, including setting a message, default value, minimum and maximum length, and a custom validation function. ```typescript const name = await new Input({ message: "Your name", default: "Anonymous", minLength: 1, maxLength: 50, validate: (v) => v.length > 0 || "Name required", }).prompt(); ``` -------------------------------- ### Example Usage of ArgumentOptions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/flags.md Shows how to configure positional arguments, specifying their names and types, and indicating if an argument's value is optional. ```typescript const { flags, unknown } = parseFlags(["file.txt"], { arguments: [ { name: "file", type: "string" }, { name: "output", type: "string", optionalValue: true }, ], }); ``` -------------------------------- ### DuplicateExampleError Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/errors.md Thrown when attempting to register an example with a name that is already in use. ```APIDOC ## DuplicateExampleError ### Description Thrown when registering an example with a name that already exists. ### Trigger Condition: An example with the same name is already registered ``` -------------------------------- ### Cleanup Node.js Setup with Deno Task Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Remove generated files and dependencies for the Node.js environment. ```bash deno task clean ``` -------------------------------- ### Parsing Flags with Configuration Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/flags.md Demonstrates how to parse command-line arguments using a defined set of flag configurations. This example shows setting up 'output' and 'verbose' flags with specific types and requirements. ```typescript const { flags } = parseFlags(["--output", "file.txt", "-v"], { flags: [ { name: "output", aliases: ["o"], type: "string", required: true, }, { name: "verbose", aliases: ["v"], type: "boolean", default: false, }, ], }); ``` -------------------------------- ### Complete CLI Application Example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/command.md Defines a complete CLI application with global options, environment variables, and multiple commands including 'add' and 'list'. Use this as a template for your own CLI applications. ```typescript import { Command } from "@cliffy/command"; import { HelpCommand } from "@cliffy/command/help"; import { CompletionsCommand } from "@cliffy/command/completions"; const cli = new Command() .name("todo") .description("A todo list management CLI") .version("1.0.0") .globalOption("--config ", "Config file path") .globalEnv("TODO_DIR=", "Todo directory") .command("add", new Command() .description("Add a todo item") .arguments("") .option("-p, --priority ", "Priority level") .action(({ config, priority }, item) => { console.log(`Adding: ${item} (Priority: ${priority})`); }) ) .command("list") .description("List all todos") .option("-s, --sort ", "Sort order") .action(({ config, sort }) => { console.log(`Listing todos (Sort: ${sort})`); }) .reset() .command("help", new HelpCommand()) .command("completions", new CompletionsCommand()) .parse(Deno.args); ``` -------------------------------- ### Help Customization Options Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Configure options like colors, indentation, long help format, and type display for the HelpCommand. Also demonstrates dynamic descriptions and adding examples. ```typescript const cli = new Command() .helpOption("-?, --help", "Show help message") .description(() => { // Dynamic description return "Generated help text"; }) .example("Basic usage", "$ app list") .example("With options", "$ app list --sort=priority") .command("help", new HelpCommand({ colors: true, indent: 4, long: true, types: true, })); ``` -------------------------------- ### Complete Table Example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/table.md Illustrates the creation of a complex table with custom column widths, alignment, padding, and indentation, using rounded borders. ```typescript import { Table, border } from "@cliffy/table"; const users = [ { name: "Alice", email: "alice@example.com", status: "Active" }, { name: "Bob", email: "bob@example.com", status: "Inactive" }, { name: "Charlie", email: "charlie@example.com", status: "Active" }, ]; const table = new Table() .header(["Name", "Email", "Status"]) .body(users.map(u => [u.name, u.email, u.status])) .border(border.rounded) .padding(1) .indent(2) .column(0, { width: 15 }) .column(1, { width: 20 }) .column(2, { width: 10, align: "center" }); console.log(table.toString()); ``` -------------------------------- ### Implementing Keyboard Shortcuts Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keypress.md This example shows how to define and handle keyboard shortcuts using a map of key combinations to functions. It processes modifier keys to construct the shortcut string. ```typescript import { keypress } from "@cliffy/keypress"; const listener = keypress(); const shortcuts = { "ctrl+s": () => console.log("Save"), "ctrl+z": () => console.log("Undo"), "ctrl+y": () => console.log("Redo"), "ctrl+c": () => { console.log("Exit"); process.exit(0); }, }; function getShortcutKey(event: any): string { const mods = []; if (event.ctrlKey) mods.push("ctrl"); if (event.shiftKey) mods.push("shift"); if (event.altKey) mods.push("alt"); if (event.metaKey) mods.push("meta"); return `${mods.join("+")}${mods.length ? "+" : ""}${event.key.toLowerCase()}`; } for await (const event of listener) { const key = getShortcutKey(event); const action = shortcuts[key as keyof typeof shortcuts]; if (action) { action(); } } ``` -------------------------------- ### Interactive Configuration with Cliffy Prompts Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md Guides the user through configuring a project by collecting project name, framework, server port, and TypeScript preference using Input, List, Number, and Confirm prompts. Supports searching within list options. ```typescript import { Input, List, Confirm, Number as NumberPrompt } from "@cliffy/prompt"; const config = { name: await new Input({ message: "Project name", default: "my-project", }).prompt(), framework: await new List({ message: "Choose framework", options: ["React", "Vue", "Svelte"], search: true, }).prompt(), port: await new NumberPrompt({ message: "Server port", default: 3000, min: 1000, max: 65535, }).prompt(), typescript: await new Confirm({ message: "Use TypeScript?", default: true, }).prompt(); }; console.log("Configuration:", config); ``` -------------------------------- ### Run Node.js Tests with Deno Task Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Execute tests using the Node.js environment. Requires Node.js and pnpm setup. ```bash deno task test:node ``` -------------------------------- ### Generate and Install Fish Completions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md Generate the Fish completion script and save it to the system's Fish vendor completions directory. This will automatically enable Fish completions for your application. ```bash $ app completions fish | sudo tee /usr/share/fish/vendor_completions.d/app.fish ``` -------------------------------- ### Handling Keypress Events Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keypress.md Demonstrates how to listen for and react to keypress events using the Keypress class. This example logs a message when Ctrl+C is detected. ```typescript import { Keypress, KeyPressEvent } from "@cliffy/keypress"; const keypress = new Keypress(); keypress.addEventListener("keypress", (event: KeyPressEvent) => { if (event.key === "c" && event.ctrlKey) { console.log("Ctrl+C pressed"); } }); ``` -------------------------------- ### Configure Core Command Options Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/configuration.md Set core command properties like name, description, version, usage, examples, and metadata using chainable methods. ```typescript const cmd = new Command() .name(string) // Set command name .description(string | Description) // Set description .version(string | VersionHandler) // Set version .usage(string) // Set custom usage text .example(name: string, description: string) // Add example .meta(key: string, value: string) // Set metadata ``` -------------------------------- ### Generate and Install Bash Completions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md Generate the Bash completion script and pipe it to a file in the system's bash completion directory. Sourcing this file enables Bash completions for your application. ```bash $ app completions bash | sudo tee /usr/share/bash-completion/completions/app $ source /usr/share/bash-completion/completions/app ``` ```bash $ app completions bash | sudo tee $(brew --prefix)/etc/bash_completion.d/app ``` -------------------------------- ### Configure List Prompt Options Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md Customize list prompts using ListOptions, including enabling search functionality. This example demonstrates setting a message, options, and enabling search. ```typescript const color = await new List({ message: "Choose a color", options: [ "Red", "Green", "Blue", { name: "Custom", value: "custom" }, ], search: true, }).prompt(); ``` -------------------------------- ### Menu Navigation with Arrow Keys Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keypress.md This example implements a simple menu navigation system using arrow keys to move up and down through options. Pressing Enter selects an option, and Ctrl+C cancels the operation. ```typescript import { keypress } from "@cliffy/keypress"; const listener = keypress(); let selected = 0; const options = ["Option 1", "Option 2", "Option 3"]; function render() { console.clear(); options.forEach((opt, i) => { const marker = i === selected ? "> " : " "; console.log(`${marker}${opt}`); }); } render(); for await (const event of listener) { if (event.key === "ArrowDown") { selected = (selected + 1) % options.length; render(); } else if (event.key === "ArrowUp") { selected = (selected - 1 + options.length) % options.length; render(); } else if (event.key === "Enter") { console.log(`Selected: ${options[selected]}`); break; } else if (event.key === "c" && event.ctrlKey) { console.log("Cancelled"); break; } } ``` -------------------------------- ### Create a Secret Prompt for API Key Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md This example shows how to create a secret prompt specifically for inputting an API key. The input will be masked. ```typescript const apiKey = await new Secret({ message: "API Key", }).prompt(); ``` -------------------------------- ### Implement Cached Completions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md This example demonstrates caching completion results to improve performance. It fetches regions only if they are not already present in the cache. ```typescript const completionCache = new Map(); const cmd = new Command() .option("--region ", "Region") .complete("region", async () => { if (!completionCache.has("regions")) { const regions = await fetchRegions(); completionCache.set("regions", regions); } return completionCache.get("regions") || []; }); ``` -------------------------------- ### Loading Animation with ANSI Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/ansi.md This example demonstrates creating a simple command-line loading animation using ANSI escape codes to control the cursor and erase lines. ```typescript import { ansi } from "@cliffy/ansi"; const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; for (let i = 0; i < 20; i++) { console.log(ansi.cursorLeft.eraseLine()( `${frames[i % frames.length]} Loading...` )); await new Promise(r => setTimeout(r, 100)); } ``` -------------------------------- ### Command Constructor Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/command.md Creates a new Command instance with type-safe support for options, arguments, and globals. It's the starting point for building your CLI application. ```APIDOC ## Constructor ```typescript constructor() ``` ### Description Creates a new Command instance with full type-safe support for options, arguments, and globals. ### Parameters None (uses generic type parameters for type inference) ### Returns `Command` ### Example ```typescript const cli = new Command() .name("myapp") .description("My CLI application") .version("1.0.0"); await cli.parse(Deno.args); ``` ``` -------------------------------- ### Display Prompt and Get Input Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md This method displays the configured prompt to the user and returns their input as a Promise. It is common to all prompt types. ```typescript const name = await new Input({ message: "Your name", }).prompt(); ``` -------------------------------- ### Input with Suggestions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md Provide a list of suggestions to guide user input using the `suggestions` option. This enhances usability by offering common choices. ```typescript import { Input } from "@cliffy/prompt"; const framework = await new Input({ message: "Framework", suggestions: [ "React", "Vue", "Angular", "Svelte", "Next.js", ], }).prompt(); ``` -------------------------------- ### Table Headers with Background Styling Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/ansi.md This example shows how to create styled table headers using the `colors` module, applying bold white text on a blue background for each header cell. ```typescript import { colors } from "@cliffy/ansi/colors"; function formatHeader(text: string): string { return colors.bold.white.bgBlue(` ${text} `); } console.log(formatHeader("Name") + " " + formatHeader("Age") + " " + formatHeader("City")); console.log("Alice 28 New York"); console.log("Bob 34 London"); ``` -------------------------------- ### Create a Number Prompt with Float Option Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md This example demonstrates creating a numeric prompt that allows decimal numbers by setting the 'float' option to true. It also includes min/max value constraints. ```typescript const percentage = await new NumberPrompt({ message: "Progress percentage", default: 0, min: 0, max: 100, }).prompt(); ``` -------------------------------- ### Example Usage of ParseFlagsOptions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/flags.md Demonstrates how to use the ParseFlagsOptions to define flags and enable specific parsing behaviors like allowing empty arguments and dotted flag names. ```typescript const { flags, unknown } = parseFlags(Deno.args, { flags: [ { name: "config", aliases: ["c"], type: "string" }, ], allowEmpty: true, dotted: true, }); ``` -------------------------------- ### Initialize and Parse Command Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/command.md Create a new Command instance, configure its name, description, and version, and then parse the command-line arguments. ```typescript const cli = new Command() .name("myapp") .description("My CLI application") .version("1.0.0"); await cli.parse(Deno.args); ``` -------------------------------- ### Create a Command with Options Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/INDEX.md Create a command-line application that accepts options, such as verbose output and an output file path. ```typescript await new Command() .name("app") .option("-v, --verbose", "Verbose output") .option("-o, --output ", "Output file") .action(({ verbose, output }) => { if (verbose) console.log(`Output: ${output}`); }) .parse(Deno.args); ``` -------------------------------- ### Parse Tab Key Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keycode.md Parse the tab character to get the KeyCode object for the Tab key. ```typescript import { parse } from "@cliffy/keycode";\n\nconst tab = parse("\ ");\nconsole.log(tab);\n// { key: "Tab", code: "Tab" } ``` -------------------------------- ### Build a Command with Options, Arguments, and Actions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/INDEX.md Construct a command-line application using a chainable API, defining its name, description, version, options, arguments, and actions. ```typescript const cmd = new Command() .name("app") .description("My app") .version("1.0.0") .option("--verbose", "Verbose") .arguments("") .action((opts, file) => {}) .command("sub") .action(() => {}) .reset() .command("other"); ``` -------------------------------- ### Table.toString() Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/table.md Renders the table as a formatted string. This method is used to get the string representation of the table for display. ```APIDOC ## toString() ### Description Render the table as a string. ### Method `toString(): string` ### Parameters None ### Returns `string` - The formatted table ### Example ```typescript const table = new Table() .header(["Name", "Age"]) .body([["Alice", "28"]]); console.log(table.toString()); ``` ``` -------------------------------- ### Keypress Constructor Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keypress.md Create a new keypress listener instance. This is the entry point for using the Keypress API. ```APIDOC ## Keypress Constructor ### Description Create a new keypress listener instance. ### Method ```typescript constructor() ``` ### Parameters None ### Returns `Keypress` ### Example ```typescript import { Keypress } from "@cliffy/keypress"; const keypress = new Keypress(); ``` ``` -------------------------------- ### Parse Escape Character Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keycode.md Parse the escape character (U+001B) to get the KeyCode object for the Escape key. ```typescript import { parse } from "@cliffy/keycode";\n\nconst esc = parse("");\nconsole.log(esc);\n// { key: "Escape", code: "Escape" } ``` -------------------------------- ### Parse Enter Key Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keycode.md Parse the carriage return character to get the KeyCode object for the Enter key. ```typescript import { parse } from "@cliffy/keycode";\n\nconst enter = parse("\ ");\nconsole.log(enter);\n// { key: "Enter", code: "Enter" } ``` -------------------------------- ### Create and Render a Basic Table Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/table.md Instantiate a Table, set its header and body, and render it to a string. ```typescript import { Table } from "@cliffy/table"; const table = new Table() .header(["Name", "Age", "City"]) .body([ ["Alice", "28", "New York"], ["Bob", "34", "London"], ]); console.log(table.toString()); ``` -------------------------------- ### Import Command Class Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/command.md Import the Command class from the @cliffy/command package to start building your CLI application. ```typescript import { Command } from "@cliffy/command"; ``` -------------------------------- ### TooManyArgumentsError Example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/errors.md This error occurs when more arguments are provided than the command is defined to accept. This does not apply if the command uses a variadic argument. ```typescript const cmd = new Command() .arguments(""); // Throws if two arguments are provided await cmd.parse(["file1.txt", "file2.txt"]); ``` -------------------------------- ### Generate Fish Completions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md Generates a Fish completion script for the application. This script can be installed to enable tab completion in Fish. ```APIDOC ## Generate Fish Completions ```bash $ app completions fish # Output: Fish completion script ``` Install the completions: ```bash $ app completions fish | sudo tee /usr/share/fish/vendor_completions.d/app.fish ``` ``` -------------------------------- ### Generate Zsh Completions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md Generates a Zsh completion script for the application. This script can be installed to enable tab completion in Zsh. ```APIDOC ## Generate Zsh Completions ```bash $ app completions zsh # Output: Zsh completion script (_app) ``` Install the completions: ```bash $ app completions zsh | sudo tee /usr/share/zsh/site-functions/_app $ compinit ``` ``` -------------------------------- ### Generate Bash Completions Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/completions.md Generates a Bash completion script for the application. This script can be installed to enable tab completion in Bash. ```APIDOC ## Generate Bash Completions ```bash $ app completions bash # Output: Bash completion script ``` Install the completions: ```bash $ app completions bash | sudo tee /usr/share/bash-completion/completions/app $ source /usr/share/bash-completion/completions/app ``` Or for Homebrew: ```bash $ app completions bash | sudo tee $(brew --prefix)/etc/bash_completion.d/app ``` ``` -------------------------------- ### HelpCommand Constructor Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Creates an instance of the HelpCommand, which can be registered as a subcommand to provide auto-generated help text. It accepts optional configuration options. ```APIDOC ## HelpCommand Constructor ### Description Creates a help command instance that can be registered as a subcommand. ### Method ```typescript constructor(options?: HelpOptions) ``` ### Parameters #### Path Parameters * **options** (HelpOptions) - Optional - Help configuration ### Request Example ```typescript import { Command } from "@cliffy/command"; import { HelpCommand } from "@cliffy/command/help"; const cli = new Command() .name("myapp") .command("help", new HelpCommand()) .parse(Deno.args); ``` ### Response #### Success Response - **HelpCommand** (`HelpCommand extends Command`) - An instance of the HelpCommand class. ``` -------------------------------- ### Basic HelpGenerator Usage Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Demonstrates how to instantiate and use the HelpGenerator to create help text for a command. Ensure the Command and HelpGenerator are imported. ```typescript import { HelpGenerator } from "@cliffy/command/help"; import { Command } from "@cliffy/command"; const cmd = new Command() .name("app") .description("My application") .option("--verbose", "Verbose output"); const generator = new HelpGenerator(cmd, { colors: true, long: true, }); const helpText = generator.generate(); console.log(helpText); ``` -------------------------------- ### Wait for Specific Keypress Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keypress.md This example demonstrates how to iterate over keypress events and break the loop when a specific key combination (Ctrl+C) is detected. ```typescript import { keypress } from "@cliffy/keypress"; const listener = keypress(); for await (const event of listener) { if (event.key === "c" && event.ctrlKey) { console.log("Interrupted"); break; } console.log("Key:", event.key); } ``` -------------------------------- ### Register HelpCommand with Other Commands Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Register the HelpCommand alongside other commands in your CLI application. This enables users to get help for specific subcommands. ```typescript const cli = new Command() .name("app") .command("help", new HelpCommand()) .command("list", "List items") .command("add", "Add item"); // Users can now run: // app help // app help list // app help add // app --help (if helpOption is enabled) ``` -------------------------------- ### Registering HelpCommand Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Demonstrates how to register the HelpCommand as a subcommand within a Cliffy Command instance, allowing users to access help via `app help` or `app help `. ```APIDOC ## Registering HelpCommand ### Description Register the HelpCommand as a subcommand to provide help text for other commands. ### Usage ```typescript const cli = new Command() .name("app") .command("help", new HelpCommand()) .command("list", "List items") .command("add", "Add item"); // Users can now run: // app help // app help list // app help add // app --help (if helpOption is enabled) ``` ``` -------------------------------- ### Flags Parsing Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/README.md Documentation for the `parseFlags()` function, which handles argument parsing. Includes details on type handlers, option interfaces, and usage examples. ```APIDOC ## parseFlags() Function ### Description The `parseFlags()` function is the core utility for parsing command-line arguments and flags. It supports various type handlers for different data types and allows for complex configurations including argument dependencies and conflicts. ### Parameters - `argv`: An array of strings representing the command-line arguments to parse. - `options`: An object containing `ParseFlagsOptions` to configure the parsing behavior. ### Type Handlers Supports built-in type handlers for: - `string` - `number` - `integer` - `boolean` Custom type handlers can also be registered. ### Interfaces - `FlagOptions`: Defines the structure for command-line flags. - `ParseFlagsOptions`: Configures the overall parsing process, including argument definitions and validation rules. - `ArgumentOptions`: Defines the structure for positional arguments. ### Usage Examples - Volume converter - Handling multiple values for a flag - Defining flag dependencies and conflicts ### Error Handling Provides patterns for handling parsing errors and validation issues. ``` -------------------------------- ### Input Prompt Constructor Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md Creates a text input prompt with customizable options. ```APIDOC ## Input Prompt ### Constructor ```typescript constructor(options?: InputOptions) ``` Create a text input prompt. **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | InputOptions | No | — | Input configuration | **Returns:** `Input` **Example:** ```typescript import { Input } from "@cliffy/prompt"; const name = await new Input({ message: "Enter your name", default: "Anonymous", }).prompt(); ``` ### InputOptions ```typescript interface InputOptions { message: string; // Prompt message default?: string; // Default value minLength?: number; // Minimum input length maxLength?: number; // Maximum input length list?: boolean; // Allow comma-separated values validate?: (value: string) => boolean | string; // Validation function suggestions?: string[]; // Auto-suggestions } ``` **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | message | string | Yes | — | Prompt message | | default | string | No | — | Default value | | minLength | number | No | — | Minimum input length | | maxLength | number | No | — | Maximum input length | | list | boolean | No | false | Allow comma-separated values | | validate | function | No | — | Validation function | | suggestions | string[] | No | [] | Auto-suggestion options | **Example:** ```typescript const email = await new Input({ message: "Email address", validate: (value) => { return value.includes("@") || "Invalid email address"; }, suggestions: ["user@example.com"], }).prompt(); ``` ``` -------------------------------- ### Create a Simple Command Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/INDEX.md Create a basic command-line application that performs a simple action, like printing a message. ```typescript import { Command } from "@cliffy/command"; await new Command() .name("hello") .action(() => console.log("Hello, World!")) .parse(Deno.args); ``` -------------------------------- ### Styling Help Text with Colors Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Illustrates how to style help text using the colors module from Cliffy. This allows for more visually appealing and organized help messages. ```typescript import { colors } from "@cliffy/ansi/colors"; const customHelp = () => { return ` ${colors.bold.blue("Usage:")} command [OPTIONS] ${colors.bold("Options:")} ${colors.cyan("-h, --help")} Show help ${colors.cyan("-v, --verbose")} Verbose output `; }; const cmd = new Command() .help(customHelp); ``` -------------------------------- ### MissingRequiredOptionError Example Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/errors.md This error is thrown when a required option is not provided on the command line. Ensure all options marked as 'required: true' are supplied during execution. ```typescript const cmd = new Command() .option("--output ", "Output file", { required: true }); // Throws if --output is not provided await cmd.parse([]); ``` -------------------------------- ### HelpOptions Interface Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Defines the configuration options for the HelpCommand, allowing customization of output. ```APIDOC ## HelpOptions Interface This interface defines the configuration options available for the HelpCommand. ### Properties - **colors** (boolean) - Optional - Enable colored output. Defaults to `true`. - **indent** (number) - Optional - Set the indentation level for sections. Defaults to `2`. - **long** (boolean) - Optional - Enable the long format for detailed help output. Defaults to `false`. - **types** (boolean) - Optional - Display argument types in the help output. Defaults to `false`. ### Example ```typescript const help = new HelpCommand({ colors: true, indent: 4, long: true, types: true, }); ``` ``` -------------------------------- ### Lint Code Changes with Deno Task Source: https://github.com/c4spar/cliffy/blob/main/CONTRIBUTING.md Run the linter to ensure code quality. This command follows Deno's style guide. ```bash deno task lint ``` -------------------------------- ### Import HelpCommand Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Import the HelpCommand class from the Cliffy library. ```typescript import { HelpCommand } from "@cliffy/command/help"; ``` -------------------------------- ### Table Configuration Methods Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/configuration.md Demonstrates the various methods available for configuring a Cliffy Table, such as setting headers, body, borders, padding, indentation, max width, and individual column options. ```typescript const table = new Table() .header(cells) // Set header row .body(rows) // Set body rows .border(boolean | BorderOptions) // Configure borders .padding(number | number[]) // Set cell padding .indent(number) // Set table indent .maxWidth(width) // Set max width .column(index, ColumnOptions) // Configure column ``` -------------------------------- ### Handling UnknownTypeError during Flag Parsing Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/errors.md This example shows how to catch UnknownTypeError if a flag is defined with a type that Cliffy does not recognize. It's useful for debugging type definitions. ```typescript parseFlags(["--value", "5"], { flags: [{ name: "value", type: "unknown-type" }], }); // Throws UnknownTypeError ``` -------------------------------- ### Manually Display Help Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/help-command.md Instantiate a HelpCommand and use its parse method to manually display help text for specific arguments. This is useful for custom help implementations. ```typescript import { HelpCommand } from "@cliffy/command/help"; const help = new HelpCommand(); const result = await help.parse(["list"]); ``` -------------------------------- ### Select Prompt Constructor Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md Creates a multi-select dropdown prompt. Allows users to choose multiple options from a dropdown list. ```APIDOC ## Select Prompt ### Constructor ```typescript constructor(options?: SelectOptions) ``` Create a multi-select dropdown prompt. **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | SelectOptions | No | — | Select configuration | **Returns:** `Select` **Example:** ```typescript import { Select } from "@cliffy/prompt"; const items = await new Select({ message: "Choose items", options: [ "Item 1", "Item 2", "Item 3", ], maxRows: 5, }).prompt(); ``` ``` -------------------------------- ### List Prompt Constructor Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/prompt.md Creates a single-selection list prompt. Users can configure the prompt's message, options, default selection, and display settings. ```APIDOC ## new List() ### Description Creates a single-selection list prompt. Users can configure the prompt's message, options, default selection, and display settings. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (ListOptions) - Optional - List configuration ### Request Example ```typescript import { List } from "@cliffy/prompt"; const selection = await new List({ message: "Choose an option", options: [ { name: "Option 1", value: "opt1" }, { name: "Option 2", value: "opt2" }, ], }).prompt(); ``` ### Response #### Success Response (200) * **selection** (string) - The selected value from the list. #### Response Example ```typescript // Example selection value "opt1" ``` ### ListOptions Interface #### Parameters * **message** (string) - Required - Prompt message * **options** (array) - Required - List of options or OptionSettings * **default** (string | number) - Optional - Default option index or value (defaults to 0) * **maxRows** (number) - Optional - Maximum visible rows * **search** (boolean) - Optional - Enable search functionality (defaults to false) * **info** (boolean) - Optional - Show info message (defaults to false) * **indent** (string) - Optional - Indentation string (defaults to " ") ``` -------------------------------- ### EventTarget API for Keypress Events Source: https://github.com/c4spar/cliffy/blob/main/_autodocs/api-reference/keypress.md This example shows how to use the EventTarget API to add and remove event listeners for keypress events. The listener is active for 5 seconds before being removed. ```typescript import { keypress } from "@cliffy/keypress"; const listener = keypress(); const handler = (event: any) => { console.log(`${event.key} pressed`); }; // Add listener listener.addEventListener("keypress", handler); // Wait a bit, then remove setTimeout(() => { listener.removeEventListener("keypress", handler); console.log("Listener removed"); process.exit(0); }, 5000); ```