Domain Cli

作者 actionbook5c40d3ad7851無授權條款1.5K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫6 週前更新

Use when building CLI tools. Keywords: CLI, command line, terminal, clap, structopt, argument parsing, subcommand, interactive, TUI, ratatui, crossterm, indicatif, progress bar, colored output, shell completion, config file, environment variable, 命令行, 终端应用, 参数解析

AI 產生的概覽

為使用 clap、設定分層、進度條與終端介面打造 Rust 命令列工具提供指引。

功能
這個技能為以 Rust 建置命令列應用提供領域限制與設計指引。內容涵蓋使用 clap 衍生巨集進行參數解析、子命令、設定優先順序(命令列高於環境變數高於設定檔)、結束碼、標準輸出與標準錯誤的區分,以及進度條等使用者回饋方式。它也列出相關 crate 與一個 CLI 結構範例,並指向錯誤處理、型別驅動設計、生命週期與並行等相關技能。
適用情境
在設計或實作 Rust 命令列工具時使用,尤其是在決定如何解析參數、分層載入設定、處理錯誤與結束碼,或加入互動式提示、進度顯示與終端介面時。它也可作為避免常見 CLI 錯誤的檢查清單。
執行需求
這個技能不附帶指令碼或資源,僅為說明性內容。實際套用時假定已有 Rust 專案,並可取得 clap、dialoguer、indicatif、colored、ratatui、crossterm 或 console 等 crate。

CLI Domain

Layer 3: Domain Constraints

Domain Constraints → Design Implications

Domain RuleDesign ConstraintRust Implication
User ergonomicsClear help, errorsclap derive macros
Config precedenceCLI > env > fileLayered config loading
Exit codesNon-zero on errorProper Result handling
Stdout/stderrData vs errorseprintln! for errors
InterruptibleHandle Ctrl+CSignal handling

Critical Constraints

User Communication

RULE: Errors to stderr, data to stdoutWHY: Pipeable output, scriptabilityRUST: eprintln! for errors, println! for data

Configuration Priority

RULE: CLI args > env vars > config file > defaultsWHY: User expectation, override capabilityRUST: Layered config with clap + figment/config

Exit Codes

RULE: Return non-zero on any errorWHY: Script integration, automationRUST: main() -> Result<(), Error> or explicit exit()

Trace Down ↓

From constraints to design (Layer 2):

"Need argument parsing"    ↓ m05-type-driven: Derive structs for args    ↓ clap: #[derive(Parser)]
"Need config layering"    ↓ m09-domain: Config as domain object    ↓ figment/config: Layer sources
"Need progress display"    ↓ m12-lifecycle: Progress bar as RAII    ↓ indicatif: ProgressBar

Key Crates

PurposeCrate
Argument parsingclap
Interactive promptsdialoguer
Progress barsindicatif
Colored outputcolored
Terminal UIratatui
Terminal controlcrossterm
Console utilitiesconsole

Design Patterns

PatternPurposeImplementation
Args structType-safe args#[derive(Parser)]
SubcommandsCommand hierarchy#[derive(Subcommand)]
Config layersOverride precedenceCLI > env > file
ProgressUser feedbackProgressBar::new(len)

Code Pattern: CLI Structure

rust
use clap::{Parser, Subcommand};
#[derive(Parser)]#[command(name = "myapp", about = "My CLI tool")]struct Cli {    /// Enable verbose output    #[arg(short, long)]    verbose: bool,
    #[command(subcommand)]    command: Commands,}
#[derive(Subcommand)]enum Commands {    /// Initialize a new project    Init { name: String },    /// Run the application    Run {        #[arg(short, long)]        port: Option<u16>,    },}
fn main() -> anyhow::Result<()> {    let cli = Cli::parse();    match cli.command {        Commands::Init { name } => init_project(&name)?,        Commands::Run { port } => run_server(port.unwrap_or(8080))?,    }    Ok(())}

Common Mistakes

MistakeDomain ViolationFix
Errors to stdoutBreaks pipingeprintln!
No help textPoor UX#[arg(help = "...")]
Panic on errorBad exit codeResult + proper handling
No progress for long opsUser uncertaintyindicatif

Trace to Layer 1

ConstraintLayer 2 PatternLayer 1 Implementation
Type-safe argsDerive macrosclap Parser
Error handlingResult propagationanyhow + exit codes
User feedbackProgress RAIIindicatif ProgressBar
Config precedenceBuilder patternLayered sources

Related Skills

WhenSee
Error handlingm06-error-handling
Type-driven argsm05-type-driven
Progress lifecyclem12-lifecycle
Async CLIm07-concurrency

來源與署名

來源:actionbook/rust-skills位於skills/domain-cli提交5c40d3a

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架