rust-cli-tui-developer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust CLI/TUI Developer

Rust CLI/TUI 开发者指南

Expert guidance for building modern command-line interfaces and terminal user interfaces in Rust, using the most popular libraries: clap for CLI argument parsing, inquire for interactive prompts, and ratatui for rich terminal UIs.
This skill provides structured patterns, best practices, and real implementations from the official source code of these libraries.
本指南为使用Rust构建现代命令行界面(CLI)和终端用户界面(TUI)提供专业指导,采用当下最流行的库:clap用于CLI参数解析,inquire用于交互式提示,ratatui用于构建丰富的终端UI。
本指南提供结构化开发模式、最佳实践,以及这些库官方源码中的真实实现案例。

🚀 Quick Start Library Selection

🚀 快速开始:库选择

Choose Your Library Stack

选择你的技术栈

NeedPrimary LibraryComplementaryUse Case
CLI Arguments
clap
-Command-line parsing, help generation
Interactive Prompts
inquire
-User input, menus, selections
Rich Terminal UI
ratatui
crossterm
Complex layouts, real-time updates
Full App
clap
+
inquire
+
ratatui
-Complete interactive console applications
需求核心库补充库适用场景
CLI参数解析
clap
-命令行解析、帮助文档生成
交互式提示
inquire
-用户输入、菜单选择
丰富终端UI
ratatui
crossterm
复杂布局、实时更新
完整应用
clap
+
inquire
+
ratatui
-完整交互式控制台应用

Library Integration Workflow

库集成流程

  1. Add dependencies using cargo add:
    bash
    # For CLI argument parsing
    cargo add clap --features derive
    
    # For interactive prompts and user input
    cargo add inquire
    
    # For rich terminal interfaces
    cargo add ratatui
    
    # For cross-platform terminal handling
    cargo add crossterm
  2. Explore official examples:
    • CLI patterns: See
      @source/clap/examples/
      for comprehensive usage examples
    • Interactive workflows: Check
      @source/inquire/examples/
      for prompt patterns
    • TUI patterns: Review
      @source/ratatui/examples/apps/
      for complete applications
  3. Combine libraries based on your application needs - start simple and add complexity incrementally.
  1. 使用cargo add添加依赖:
    bash
    # 用于CLI参数解析
    cargo add clap --features derive
    
    # 用于交互式提示和用户输入
    cargo add inquire
    
    # 用于构建丰富终端界面
    cargo add ratatui
    
    # 用于跨平台终端处理
    cargo add crossterm
  2. 探索官方示例:
    • CLI模式: 查看
      @source/clap/examples/
      获取全面的使用示例
    • 交互式流程: 参考
      @source/inquire/examples/
      中的提示模式
    • TUI模式: 研究
      @source/ratatui/examples/apps/
      中的完整应用案例
  3. 根据应用需求组合库 - 从简单功能开始,逐步增加复杂度。

📚 Official Resources

📚 官方资源

Primary Documentation Sources

核心文档来源

This skill includes complete official source code via git submodules in the
source/
directory:
  • @source/clap/
    - Complete clap CLI parser library with examples
  • @source/inquire/
    - Interactive prompt library with demo applications
  • @source/ratatui/
    - Rich TUI framework with example applications
本指南通过git子模块在
source/
目录中包含了完整的官方源码:
  • @source/clap/
    - 包含示例的完整clap CLI解析库
  • @source/inquire/
    - 带有演示应用的交互式提示库
  • @source/ratatui/
    - 带有示例应用的丰富TUI框架

Quick Navigation to Official Examples

官方示例快速导航

  • CLI Examples:
    @source/clap/examples/
  • Interactive Prompts:
    @source/inquire/examples/
  • TUI Applications:
    @source/ratatui/examples/
  • CLI示例:
    @source/clap/examples/
  • 交互式提示:
    @source/inquire/examples/
  • TUI应用:
    @source/ratatui/examples/

🛠️ Library-Specific Guides

🛠️ 库专属指南

1. Clap - Command Line Argument Parsing

1. Clap - 命令行参数解析

Core Capabilities
  • Derive macros for automatic argument parsing with minimal boilerplate
  • Subcommand support for complex CLI interfaces like git or cargo
  • Argument validation with custom parsers and validation functions
  • Help generation with automatic --help and --version support
  • Configuration overrides through environment variables and config files
Key Patterns to Explore
  • Basic argument parsing with derive macros:
    @source/clap/examples/derive_ref/
  • Advanced subcommand structures:
    @source/clap/examples/tutorial_derive/04_04_subcommands.rs
  • Custom validation and parsing:
    @source/clap/examples/tutorial_derive/04_02_validate.rs
  • Complex argument relationships:
    @source/clap/examples/tutorial_derive/04_03_relations.rs
Common Use Cases
  • Simple flag-based tools (similar to
    ls
    ,
    grep
    )
  • Package managers with subcommands (similar to
    cargo
    ,
    npm
    )
  • Configuration-driven applications
  • Data processing pipelines with multiple input sources
核心功能
  • 派生宏:通过极少的样板代码实现自动参数解析
  • 子命令支持:构建类似git或cargo的复杂CLI界面
  • 参数验证:支持自定义解析器和验证函数
  • 帮助文档生成:自动支持--help和--version命令
  • 配置覆盖:通过环境变量和配置文件覆盖默认配置
重点探索模式
  • 使用派生宏的基础参数解析:
    @source/clap/examples/derive_ref/
  • 高级子命令结构:
    @source/clap/examples/tutorial_derive/04_04_subcommands.rs
  • 自定义验证与解析:
    @source/clap/examples/tutorial_derive/04_02_validate.rs
  • 复杂参数关联:
    @source/clap/examples/tutorial_derive/04_03_relations.rs
常见适用场景
  • 简单的基于标志的工具(类似
    ls
    grep
  • 带有子命令的包管理器(类似
    cargo
    npm
  • 配置驱动型应用
  • 多输入源的数据处理流水线

2. Inquire - Interactive Prompts

2. Inquire - 交互式提示

Interactive Input Capabilities
  • Text input with validation, placeholders, and help messages
  • Single selection from predefined options with search functionality
  • Multi-selection with checkbox-style interface
  • Confirmation prompts for yes/no decisions
  • Custom types with validation and formatting
  • Form builders for complex multi-field input flows
Key Patterns to Explore
  • Basic input types and validation:
    @source/inquire/examples/text_simple.rs
    ,
    @source/inquire/examples/select.rs
  • Multi-select and complex selections:
    @source/inquire/examples/multiselect.rs
    ,
    @source/inquire/examples/enum_comprehensive.rs
  • Custom validation and types:
    @source/inquire/examples/custom_type.rs
    ,
    @source/inquire/examples/date.rs
  • Complex form workflows:
    @source/inquire/examples/form.rs
    ,
    @source/inquire/examples/expense_tracker.rs
  • Password and secure input:
    @source/inquire/examples/password_simple.rs
    ,
    @source/inquire/examples/password_full_featured.rs
Common Use Cases
  • Configuration wizards and setup flows
  • Database connection configuration
  • API client initialization
  • User onboarding sequences
  • Data filtering and selection interfaces
交互式输入功能
  • 文本输入:支持验证、占位符和帮助信息
  • 单选选择:从预定义选项中选择,支持搜索功能
  • 多选选择:复选框式界面
  • 确认提示:用于是/否决策
  • 自定义类型:支持验证和格式化
  • 表单构建器:用于复杂的多字段输入流程
重点探索模式
  • 基础输入类型与验证:
    @source/inquire/examples/text_simple.rs
    @source/inquire/examples/select.rs
  • 多选与复杂选择:
    @source/inquire/examples/multiselect.rs
    @source/inquire/examples/enum_comprehensive.rs
  • 自定义验证与类型:
    @source/inquire/examples/custom_type.rs
    @source/inquire/examples/date.rs
  • 复杂表单流程:
    @source/inquire/examples/form.rs
    @source/inquire/examples/expense_tracker.rs
  • 密码与安全输入:
    @source/inquire/examples/password_simple.rs
    @source/inquire/examples/password_full_featured.rs
常见适用场景
  • 配置向导与设置流程
  • 数据库连接配置
  • API客户端初始化
  • 用户引导序列
  • 数据过滤与选择界面

3. Ratatui - Terminal User Interfaces

3. Ratatui - 终端用户界面

Rich Terminal UI Capabilities
  • Layout system with flexible constraints and responsive design
  • Widget library for common UI components (lists, tables, charts, etc.)
  • Event handling with keyboard and mouse support
  • Real-time updates with animation and progress indicators
  • Cross-platform terminal management with crossterm backend
  • Custom widgets through extensible widget traits
Key Patterns to Explore
  • Basic layout and widget usage:
    @source/ratatui/examples/apps/advanced-widget-impl/
  • Complex application structure:
    @source/ratatui/examples/apps/async-github/
  • Data visualization and charts:
    @source/ratatui/examples/apps/chart/
  • Custom drawing and graphics:
    @source/ratatui/examples/apps/canvas/
  • Color themes and styling:
    @source/ratatui/examples/apps/color-explorer/
  • Constraint-based layouts:
    @source/ratatui/examples/apps/constraint-explorer/
  • Real-time data display:
    @source/ratatui/examples/apps/calendar-explorer/
Common Use Cases
  • System monitoring dashboards
  • Log viewers and search interfaces
  • Database query tools
  • File managers and explorers
  • Development IDEs and editors
  • Data analysis and visualization tools
  • Game interfaces and interactive applications
丰富终端UI功能
  • 布局系统:支持灵活的约束条件和响应式设计
  • 组件库:包含常见UI组件(列表、表格、图表等)
  • 事件处理:支持键盘和鼠标操作
  • 实时更新:带有动画和进度指示器
  • 跨平台:基于crossterm后端的终端管理
  • 自定义组件:通过可扩展的组件特性实现
重点探索模式
  • 基础布局与组件使用:
    @source/ratatui/examples/apps/advanced-widget-impl/
  • 复杂应用结构:
    @source/ratatui/examples/apps/async-github/
  • 数据可视化与图表:
    @source/ratatui/examples/apps/chart/
  • 自定义绘图与图形:
    @source/ratatui/examples/apps/canvas/
  • 颜色主题与样式:
    @source/ratatui/examples/apps/color-explorer/
  • 基于约束的布局:
    @source/ratatui/examples/apps/constraint-explorer/
  • 实时数据展示:
    @source/ratatui/examples/apps/calendar-explorer/
常见适用场景
  • 系统监控仪表盘
  • 日志查看器与搜索界面
  • 数据库查询工具
  • 文件管理器与浏览器
  • 开发IDE与编辑器
  • 数据分析与可视化工具
  • 游戏界面与交互式应用

🏗️ Complete Application Patterns

🏗️ 完整应用模式

Application Architecture Overview

应用架构概述

CLI App with Configuration
  • Structure: Main CLI with subcommands for different operations
  • Configuration: JSON/TOML config files with CLI overrides
  • Features: Logging, error handling, validation
  • Examples: Study
    @source/clap/examples/cargo-example.rs
    for patterns
Interactive CLI with Prompts
  • Flow: CLI args → interactive prompts → confirmation → execution
  • Features: Progressive disclosure, validation, defaults, help text
  • State Management: Collect information step-by-step with back/forward navigation
  • Examples: Explore
    @source/inquire/examples/form.rs
    for complex flows
Full TUI Application
  • Architecture: Event loop with state management and UI rendering
  • Components: Multiple screens/widgets with navigation between them
  • State: Application state separated from rendering logic
  • Examples: Study
    @source/ratatui/examples/apps/async-github/
    for async patterns
带配置的CLI应用
  • 结构:包含子命令的主CLI,用于不同操作
  • 配置:JSON/TOML配置文件,支持CLI参数覆盖
  • 特性:日志、错误处理、验证
  • 示例:研究
    @source/clap/examples/cargo-example.rs
    中的模式
带提示的交互式CLI
  • 流程:CLI参数 → 交互式提示 → 确认 → 执行
  • 特性:渐进式披露、验证、默认值、帮助文本
  • 状态管理:逐步收集信息,支持前后导航
  • 示例:探索
    @source/inquire/examples/form.rs
    中的复杂流程
完整TUI应用
  • 架构:包含状态管理和UI渲染的事件循环
  • 组件:多个屏幕/组件,支持导航切换
  • 状态:应用状态与渲染逻辑分离
  • 示例:研究
    @source/ratatui/examples/apps/async-github/
    中的异步模式

Integration Patterns

集成模式

Library Combination Strategies
  1. CLI-first: Start with clap, add inquire for interactive configuration
  2. Progressive Enhancement: CLI → CLI + prompts → full TUI
  3. Hybrid Apps: CLI for automation, interactive mode for manual use
Common Integration Points
  • Configuration validation (clap + inquire)
  • Progress indication (clap + ratatui)
  • Setup wizards (inquire + ratatui)
  • Admin interfaces (clap + ratatui)
库组合策略
  1. CLI优先:从clap开始,添加inquire实现交互式配置
  2. 渐进增强:CLI → CLI+提示 → 完整TUI
  3. 混合应用:CLI用于自动化,交互式模式用于手动操作
常见集成点
  • 配置验证(clap + inquire)
  • 进度指示(clap + ratatui)
  • 设置向导(inquire + ratatui)
  • 管理界面(clap + ratatui)

Development Workflow

开发流程

Start Simple, Add Complexity
  1. Phase 1: Basic CLI with clap
  2. Phase 2: Add interactive prompts where needed
  3. Phase 3: Add TUI for complex operations
  4. Phase 4: Advanced features (async, plugins, etc.)
Example-Based Learning
  • Study
    @source/clap/examples/
    for CLI patterns
  • Review
    @source/inquire/examples/
    for interaction flows
  • Analyze
    @source/ratatui/examples/apps/
    for complete applications
从简到繁,逐步迭代
  1. 阶段1:基于clap的基础CLI
  2. 阶段2:在需要的地方添加交互式提示
  3. 阶段3:为复杂操作添加TUI
  4. 阶段4:高级特性(异步、插件等)
基于示例的学习
  • 研究
    @source/clap/examples/
    中的CLI模式
  • 参考
    @source/inquire/examples/
    中的交互流程
  • 分析
    @source/ratatui/examples/apps/
    中的完整应用

Real-World Application Types

真实世界应用类型

Development Tools
  • Package managers (cargo, npm-style)
  • Build systems and generators
  • Code analysis and linting tools
  • Database migration tools
System Administration
  • Log analysis and filtering tools
  • Configuration management utilities
  • System monitoring dashboards
  • Deployment automation tools
Data Processing
  • ETL pipelines with interactive configuration
  • Data validation and cleaning tools
  • Report generation utilities
  • File processing batch tools
Interactive Applications
  • Text editors and IDEs
  • File managers
  • Game interfaces
  • Educational tools
Focus on understanding the patterns from the official examples rather than copying specific implementations. The source code provides the most up-to-date and comprehensive examples of best practices.
开发工具
  • 包管理器(类似cargo、npm)
  • 构建系统与生成器
  • 代码分析与 linting 工具
  • 数据库迁移工具
系统管理
  • 日志分析与过滤工具
  • 配置管理实用程序
  • 系统监控仪表盘
  • 部署自动化工具
数据处理
  • 带交互式配置的ETL流水线
  • 数据验证与清理工具
  • 报告生成实用程序
  • 文件批处理工具
交互式应用
  • 文本编辑器与IDE
  • 文件管理器
  • 游戏界面
  • 教育工具
重点在于理解官方示例中的模式,而非复制特定实现。官方源码提供了最新、最全面的最佳实践示例。

🎯 Best Practices

🎯 最佳实践

CLI Design Principles

CLI设计原则

  1. Follow POSIX conventions: Use
    -
    for short options,
    --
    for long options
  2. Provide helpful defaults: Make reasonable default choices
  3. Clear help text: Explain what each option does
  4. Consistent interface: Follow established patterns from tools like
    git
    ,
    cargo
  5. Error handling: Provide clear error messages and exit codes
  1. 遵循POSIX规范:短选项使用
    -
    ,长选项使用
    --
  2. 提供合理默认值:设置符合预期的默认选项
  3. 清晰的帮助文本:解释每个选项的作用
  4. 一致的界面:遵循git、cargo等成熟工具的模式
  5. 错误处理:提供清晰的错误信息和退出码

Interactive Prompt Guidelines

交互式提示指南

  1. Progressive disclosure: Start simple, add complexity as needed
  2. Provide defaults: Make it easy to accept reasonable choices
  3. Validation: Give immediate feedback on invalid input
  4. Escape hatches: Always allow users to exit or skip
  5. Context preservation: Remember previous answers when possible
  1. 渐进式披露:从简单开始,按需增加复杂度
  2. 提供默认值:简化用户接受合理选项的操作
  3. 即时验证:对无效输入提供即时反馈
  4. 退出机制:始终允许用户退出或跳过
  5. 上下文保留:尽可能记住用户之前的输入

TUI Development Tips

TUI开发技巧

  1. Responsive layouts: Handle terminal resizing gracefully
  2. Keyboard shortcuts: Provide intuitive key bindings
  3. Visual hierarchy: Use colors and borders to organize information
  4. Performance: Update efficiently, don't block the main thread
  5. Accessibility: Consider users with different needs
  1. 响应式布局:优雅处理终端窗口大小变化
  2. 键盘快捷键:提供直观的按键绑定
  3. 视觉层次:使用颜色和边框组织信息
  4. 性能优化:高效更新,避免阻塞主线程
  5. 可访问性:考虑不同用户的需求

🔧 Development Workflow

🔧 开发流程

Setting Up Your Development Environment

搭建开发环境

bash
undefined
bash
undefined

Create new Rust project

创建新的Rust项目

cargo new my-cli-app cd my-cli-app
cargo new my-cli-app cd my-cli-app

Add dependencies to Cargo.toml

向Cargo.toml添加依赖

cargo add clap --features derive cargo add inquire cargo add ratatui crossterm
cargo add clap --features derive cargo add inquire cargo add ratatui crossterm

For development

开发依赖

cargo add --dev anyhow # Better error handling cargo add --dev pretty_assertions # Better test output
undefined
cargo add --dev anyhow # 更友好的错误处理 cargo add --dev pretty_assertions # 更美观的测试输出
undefined

Testing Your CLI

测试你的CLI

rust
#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    #[test]
    fn test_cli_parsing() {
        let cli = Cli::try_parse_from(&["my-app", "--verbose", "build"]).unwrap();
        assert!(matches!(cli.command, Commands::Build { .. }));
        assert_eq!(cli.verbose, 1);
    }

    #[test]
    fn test_help_generation() {
        // This tests that help doesn't panic
        let _ = Cli::try_parse_from(&["my-app", "--help"]);
    }
}
rust
#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    #[test]
    fn test_cli_parsing() {
        let cli = Cli::try_parse_from(&["my-app", "--verbose", "build"]).unwrap();
        assert!(matches!(cli.command, Commands::Build { .. }));
        assert_eq!(cli.verbose, 1);
    }

    #[test]
    fn test_help_generation() {
        // 测试帮助命令不会 panic
        let _ = Cli::try_parse_from(&["my-app", "--help"]);
    }
}

Building for Distribution

构建发布版本

toml
undefined
toml
undefined

Cargo.toml release profile

Cargo.toml 发布配置

[profile.release] opt-level = 3 lto = true codegen-units = 1 panic = "abort" strip = true

```bash
[profile.release] opt-level = 3 lto = true codegen-units = 1 panic = "abort" strip = true

```bash

Build optimized binary

构建优化后的二进制文件

cargo build --release
cargo build --release

Cross-compile for different targets (requires target toolchains)

交叉编译到不同目标平台(需要对应工具链)

cargo build --target x86_64-unknown-linux-musl --release cargo build --target aarch64-apple-darwin --release
undefined
cargo build --target x86_64-unknown-linux-musl --release cargo build --target aarch64-apple-darwin --release
undefined

🚀 Deployment and Distribution

🚀 部署与分发

Installation Options

安装选项

bash
undefined
bash
undefined

Install from crates.io

从crates.io安装

cargo install my-cli-app
cargo install my-cli-app

Install from git repository

从Git仓库安装

Local development installation

本地开发安装

cargo install --path .
undefined
cargo install --path .
undefined

Distribution with GitHub Actions

使用GitHub Actions分发

yaml
undefined
yaml
undefined

.github/workflows/release.yml

.github/workflows/release.yml

name: Release on: push: tags: - 'v*'
jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: toolchain: stable
  - name: Build binary
    run: cargo build --release --target x86_64-unknown-linux-musl

  - name: Upload release asset
    uses: actions/upload-release-asset@v1
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    with:
      upload_url: ${{ steps.create_release.outputs.upload_url }}
      asset_path: target/x86_64-unknown-linux-musl/release/my-cli-app
      asset_name: my-cli-app-linux
      asset_content_type: application/octet-stream
undefined
name: Release on: push: tags: - 'v*'
jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: toolchain: stable
  - name: Build binary
    run: cargo build --release --target x86_64-unknown-linux-musl

  - name: Upload release asset
    uses: actions/upload-release-asset@v1
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    with:
      upload_url: ${{ steps.create_release.outputs.upload_url }}
      asset_path: target/x86_64-unknown-linux-musl/release/my-cli-app
      asset_name: my-cli-app-linux
      asset_content_type: application/octet-stream
undefined

📖 Learning Resources

📖 学习资源

Official Documentation Paths

官方文档路径

  • Clap Guide:
    @source/clap/docs/guide/
  • Clap Examples:
    @source/clap/examples/
  • Inquire Examples:
    @source/inquire/examples/
  • Ratatui Examples:
    @source/ratatui/examples/
  • Clap指南:
    @source/clap/docs/guide/
  • Clap示例:
    @source/clap/examples/
  • Inquire示例:
    @source/inquire/examples/
  • Ratatui示例:
    @source/ratatui/examples/

Community Resources

社区资源


This skill provides comprehensive guidance for Rust CLI and TUI development. Start with the 🚀 Quick Start Library Selection section to choose the right libraries for your use case, then explore the detailed examples from the official source code included in the
source/
directory.

本指南为Rust CLI和TUI开发提供全面指导。从🚀 快速开始:库选择部分入手,为你的使用场景选择合适的库,然后探索
source/
目录中包含的官方源码示例。