building-clis
Build professional command-line interfaces in Python, Go, and Rust using modern frameworks like Typer, Cobra, and clap. Use when creating developer tools, automation scripts, or infrastructure management CLIs with robust argument parsing, interactive features, and multi-platform distribution.
What this skill does
# Building CLIs
Build professional command-line interfaces across Python, Go, and Rust using modern frameworks with robust argument parsing, configuration management, and shell integration.
## When to Use This Skill
Use this skill when:
- Building developer tooling or automation CLIs
- Creating infrastructure management tools (deployment, monitoring)
- Implementing API client command-line tools
- Adding CLI capabilities to existing projects
- Packaging utilities for distribution (PyPI, Homebrew, binary releases)
Common triggers: "create a CLI tool", "build a command-line interface", "add CLI arguments", "parse command-line options", "generate shell completions"
## Framework Selection
### Quick Decision Guide
**Python Projects:**
- **Typer** (recommended): Modern type-safe CLIs with minimal boilerplate
- **Click**: Mature, flexible CLIs for complex command hierarchies
**Go Projects:**
- **Cobra** (recommended): Industry standard for enterprise tools (Kubernetes, Docker, GitHub CLI)
- **urfave/cli**: Lightweight alternative for simple CLIs
**Rust Projects:**
- **clap v4** (recommended): Type-safe with derive API or builder API for runtime flexibility
For detailed framework comparison and selection criteria, see [references/framework-selection.md](references/framework-selection.md).
## Core Patterns
### Arguments vs. Options vs. Flags
**Positional Arguments:**
- Primary input, identified by position
- Use for required inputs (max 2-3 arguments)
- Example: `convert input.jpg output.png`
**Options:**
- Named parameters with values
- Use for configuration and optional inputs
- Example: `--output file.txt`, `--config app.yaml`
**Flags:**
- Boolean options (presence = true)
- Use for switches and toggles
- Example: `--verbose`, `--dry-run`, `--force`
**Decision Matrix:**
| Use Case | Type | Example |
|----------|------|---------|
| Primary required input | Positional Argument | `git commit -m "message"` |
| Optional configuration | Option | `--config app.yaml` |
| Boolean setting | Flag | `--verbose`, `--force` |
| Multiple values | Variadic Argument | `files...` |
See [references/argument-patterns.md](references/argument-patterns.md) for comprehensive parsing patterns.
### Subcommand Organization
**Flat Structure (1 Level):**
```
app command1 [args]
app command2 [args]
```
Use for: Small CLIs with 5-10 operations
**Grouped Structure (2 Levels):**
```
app group subcommand [args]
```
Use for: Medium CLIs with logical groupings (10-30 commands)
Example: `kubectl get pods`, `kubectl create deployment`
**Nested Structure (3+ Levels):**
```
app group subgroup command [args]
```
Use for: Large CLIs with deep hierarchies (30+ commands)
Example: `gcloud compute instances create`
See [references/subcommand-design.md](references/subcommand-design.md) for structuring strategies.
### Configuration Management
**Standard Precedence (Highest to Lowest):**
1. CLI Arguments/Flags (explicit user input)
2. Environment Variables (session overrides)
3. Config File - Local (`./config.yaml`)
4. Config File - User (`~/.config/app/config.yaml`)
5. Config File - System (`/etc/app/config.yaml`)
6. Built-in Defaults (hardcoded)
**Best Practices:**
- Document precedence in `--help`
- Validate config files before execution
- Provide `--print-config` to show effective configuration
- Use XDG Base Directory (`~/.config/app/`) for config files
See [references/configuration-management.md](references/configuration-management.md) for implementation patterns across languages.
### Output Formatting
**Format Selection:**
| Use Case | Format | When |
|----------|--------|------|
| Human consumption | Colored text, tables | Default interactive mode |
| Machine consumption | JSON, YAML | `--output json`, piping |
| Logging/debugging | Plain text | `--verbose`, stderr |
| Progress tracking | Progress bars, spinners | Long operations |
**Best Practices:**
- Default to human-readable output
- Provide `--output` flag (json, yaml, table)
- Use stderr for logs, stdout for data
- Auto-detect TTY (disable colors if not interactive)
- Use exit codes: 0 = success, 1 = error, 2 = usage error
See [references/output-formatting.md](references/output-formatting.md) for formatting strategies.
## Language-Specific Quick Starts
### Python with Typer
**Installation:**
```bash
pip install "typer[all]" # Includes rich for colored output
```
**Basic Example:**
```python
import typer
from typing import Annotated
app = typer.Typer()
@app.command()
def greet(
name: Annotated[str, typer.Argument(help="Name to greet")],
formal: Annotated[bool, typer.Option(help="Use formal greeting")] = False
):
"""Greet someone with a message."""
greeting = "Good day" if formal else "Hello"
typer.echo(f"{greeting}, {name}!")
if __name__ == "__main__":
app()
```
**Key Features:**
- Type hints for automatic validation
- Minimal boilerplate with decorators
- Auto-generated help text
- Rich integration for colored output
See [examples/python/](examples/python/) for complete working examples including subcommands, config management, and interactive features.
### Go with Cobra
**Installation:**
```bash
go get -u github.com/spf13/cobra@latest
```
**Basic Example:**
```go
var rootCmd = &cobra.Command{
Use: "greet [name]",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello, %s!\n", args[0])
},
}
rootCmd.Flags().Bool("formal", false, "Use formal greeting")
rootCmd.Execute()
```
**Key Features:**
- POSIX-compliant flags
- Viper integration for configuration
- Subcommand architecture
- Shell completion generation
See [examples/go/](examples/go/) for complete working examples including Viper config and multi-level subcommands.
### Rust with clap
**Installation (Cargo.toml):**
```toml
[dependencies]
clap = { version = "4.5", features = ["derive"] }
```
**Basic Example (Derive API):**
```rust
use clap::Parser;
#[derive(Parser)]
#[command(about = "Greet someone")]
struct Cli {
/// Name to greet
name: String,
/// Use formal greeting
#[arg(long)]
formal: bool,
}
fn main() {
let cli = Cli::parse();
let greeting = if cli.formal { "Good day" } else { "Hello" };
println!("{}, {}!", greeting, cli.name);
}
```
**Key Features:**
- Compile-time type safety
- Derive API (declarative) or Builder API (programmatic)
- Comprehensive validation
- Performance optimized
See [examples/rust/](examples/rust/) for complete working examples including subcommands and builder API patterns.
## Interactive Features
### Progress Indicators
**Python (rich):**
```python
from rich.progress import track
for _ in track(range(100), description="Processing..."):
time.sleep(0.01)
```
**Go (progressbar):**
```go
import "github.com/schollz/progressbar/v3"
bar := progressbar.Default(100)
for i := 0; i < 100; i++ {
bar.Add(1)
}
```
**Rust (indicatif):**
```rust
use indicatif::ProgressBar;
let bar = ProgressBar::new(100);
for _ in 0..100 {
bar.inc(1);
}
```
### Prompts and Confirmations
**Python:**
```python
confirm = typer.confirm("Are you sure?")
if not confirm:
raise typer.Abort()
```
**Go:**
```go
reader := bufio.NewReader(os.Stdin)
fmt.Print("Are you sure? (y/n): ")
response, _ := reader.ReadString('\n')
```
**Rust:**
```rust
use dialoguer::Confirm;
if Confirm::new().with_prompt("Are you sure?").interact()? {
// Proceed
}
```
## Shell Completion
### Generating Completions
**Python (Typer):**
```bash
_MYAPP_COMPLETE=bash_source myapp > ~/.myapp-complete.bash
_MYAPP_COMPLETE=zsh_source myapp > ~/.myapp-complete.zsh
```
**Go (Cobra):**
```go
rootCmd.AddCommand(&cobra.Command{
Use: "completion [bash|zsh|fish|powershell]",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
rootCmd.GenBashCompletion(os.Stdout)
case "zsh":
rootCmd.GenZshCompletion(os.Stdout)
}
},Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.