Building clis

From ancoleman/ai-design-components · View interactive version

Building clis is an AI agent skill from the GitHub repository ancoleman/ai-design-components. 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.

How to use this skill

Skill file

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:

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:

Go Projects:

Rust Projects:

For detailed framework comparison and selection criteria, see references/framework-selection.md.

Core Patterns

Arguments vs. Options vs. Flags

Positional Arguments:

Options:

Flags:

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 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 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:

See 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:

See references/output-formatting.md for formatting strategies.

Language-Specific Quick Starts

Python with Typer

Installation:

pip install "typer[all]"  # Includes rich for colored output

Basic Example:

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:

See examples/python/ for complete working examples including subcommands, config management, and interactive features.

Go with Cobra

Installation:

go get -u github.com/spf13/cobra@latest

Basic Example:

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:

See examples/go/ for complete working examples including Viper config and multi-level subcommands.

Rust with clap

Installation (Cargo.toml):

[dependencies]
clap = { version = "4.5", features = ["derive"] }

Basic Example (Derive API):

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:

See examples/rust/ for complete working examples including subcommands and builder API patterns.

Interactive Features

Progress Indicators

Python (rich):

from rich.progress import track
for _ in track(range(100), description="Processing..."):
    time.sleep(0.01)

Go (progressbar):

import "github.com/schollz/progressbar/v3"
bar := progressbar.Default(100)
for i := 0; i < 100; i++ {
    bar.Add(1)
}

Rust (indicatif):

use indicatif::ProgressBar;
let bar = ProgressBar::new(100);
for _ in 0..100 {
    bar.inc(1);
}

Prompts and Confirmations

Python:

confirm = typer.confirm("Are you sure?")
if not confirm:
    raise typer.Abort()

Go:

reader := bufio.NewReader(os.Stdin)
fmt.Print("Are you sure? (y/n): ")
response, _ := reader.ReadString('\n')

Rust:

use dialoguer::Confirm;
if Confirm::new().with_prompt("Are you sure?").interact()? {
    // Proceed
}

Shell Completion

Generating Completions

Python (Typer):

_MYAPP_COMPLETE=bash_source myapp > ~/.myapp-complete.bash
_MYAPP_COMPLETE=zsh_source myapp > ~/.myapp-complete.zsh

Go (Cobra):

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)
        }
    },
})

Rust (clap):

use clap_complete::{generate, shells::Bash};
generate(Bash, &mut Cli::command(), "myapp", &mut io::stdout())

See references/shell-completion.md for installation instructions.

Distribution and Packaging

Python (PyPI)

pyproject.toml:

[project]
name = "myapp"
version = "1.0.0"
scripts = { myapp = "myapp.cli:app" }

Publish:

pip install build twine
python -m build
twine upload dist/*

Go (Homebrew)

Formula:

class Myapp < Formula
  desc "My CLI application"
  url "https://github.com/user/myapp/archive/v1.0.0.tar.gz"

  def install
    system "go", "build", "-o", bin/"myapp"
  end
end

Rust (Cargo)

Publish:

cargo login
cargo publish

Installation:

cargo install myapp

See references/distribution.md for comprehensive packaging strategies including binary releases.

Best Practices

Universal CLI Conventions

Always Provide:

Argument Handling:

Error Handling:

Interactivity:

Configuration Best Practices

File Formats:

Secret Management:

Precedence:

Integration with Other Skills

testing-strategies:

building-ci-pipelines:

api-patterns:

secret-management:

Reference Files

Decision Frameworks:

Implementation Guides:

Code Examples:

Quick Reference

Framework Recommendations:

Common Patterns:

Output Standards:

Distribution:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.