rust-clap

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust Clap Best Practices

Rust Clap最佳实践

Comprehensive best practices guide for building CLI applications in Rust using clap. Contains 42 rules across 8 categories, prioritized by impact to guide CLI design, argument parsing, and testing.
本指南是使用clap构建Rust CLI应用的综合最佳实践手册,包含8个类别下的42条规则,按影响程度排序,可为CLI设计、参数解析和测试提供指导。

When to Apply

适用场景

Reference these guidelines when:
  • Designing new Rust CLI applications
  • Adding arguments or subcommands to existing CLIs
  • Validating and parsing command-line input
  • Writing integration tests for CLI tools
  • Improving help text and user experience
在以下场景中可参考本指南:
  • 设计新的Rust CLI应用
  • 为现有CLI添加参数或子命令
  • 验证和解析命令行输入
  • 为CLI工具编写集成测试
  • 优化帮助文本和用户体验

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Type-Driven DesignCRITICAL
type-
2Derive API PatternsCRITICAL
derive-
3Argument ConfigurationHIGH
arg-
4Validation & ParsingHIGH
valid-
5Subcommand ArchitectureMEDIUM-HIGH
subcmd-
6Help & DocumentationMEDIUM
help-
7Error HandlingMEDIUM
error-
8Testing PatternsLOW-MEDIUM
test-
优先级类别影响程度前缀
1类型驱动设计关键
type-
2Derive API模式关键
derive-
3参数配置
arg-
4验证与解析
valid-
5子命令架构中高
subcmd-
6帮助与文档中等
help-
7错误处理中等
error-
8测试模式中低
test-

Quick Reference

快速参考

1. Type-Driven Design (CRITICAL)

1. 类型驱动设计(关键)

  • type-valueenum-enums
    - Use ValueEnum for enumerated arguments
  • type-option-optional
    - Use Option for truly optional arguments
  • type-pathbuf-files
    - Use PathBuf for file system arguments
  • type-vec-multiple
    - Use Vec for multiple value arguments
  • type-newtype-semantic
    - Use newtypes for semantic distinction
  • type-bool-flags
    - Use bool for simple flags
  • type-valueenum-enums
    - 对枚举类型参数使用ValueEnum
  • type-option-optional
    - 对真正可选的参数使用Option
  • type-pathbuf-files
    - 对文件系统相关参数使用PathBuf
  • type-vec-multiple
    - 对多值参数使用Vec
  • type-newtype-semantic
    - 使用newtype实现语义区分
  • type-bool-flags
    - 对简单标志位使用bool

2. Derive API Patterns (CRITICAL)

2. Derive API模式(关键)

  • derive-parser-entry
    - Derive Parser for CLI entry point
  • derive-command-metadata
    - Use Command attribute for metadata
  • derive-subcommand-enum
    - Use Subcommand derive for command hierarchies
  • derive-args-reusable
    - Derive Args for reusable argument groups
  • derive-doc-comments
    - Use doc comments for help text
  • derive-global-options
    - Use Global for cross-subcommand options
  • derive-propagate-version
    - Propagate version to subcommands
  • derive-parser-entry
    - 为CLI入口点派生Parser
  • derive-command-metadata
    - 使用Command属性定义元数据
  • derive-subcommand-enum
    - 为命令层级结构派生Subcommand
  • derive-args-reusable
    - 为可复用参数组派生Args
  • derive-doc-comments
    - 使用文档注释生成帮助文本
  • derive-global-options
    - 使用Global定义跨子命令的全局选项
  • derive-propagate-version
    - 将版本信息传递给子命令

3. Argument Configuration (HIGH)

3. 参数配置(高)

  • arg-default-value
    - Use default_value for sensible defaults
  • arg-env-fallback
    - Use env for environment variable fallback
  • arg-short-long
    - Provide both short and long option names
  • arg-conflicts-with
    - Use conflicts_with for mutually exclusive options
  • arg-requires
    - Use requires for dependent arguments
  • arg-value-name
    - Use value_name for descriptive placeholders
  • arg-default-value
    - 使用default_value设置合理的默认值
  • arg-env-fallback
    - 使用env设置环境变量作为备选
  • arg-short-long
    - 同时提供短选项和长选项名称
  • arg-conflicts-with
    - 使用conflicts-with定义互斥选项
  • arg-requires
    - 使用requires定义依赖参数
  • arg-value-name
    - 使用value-name设置描述性占位符

4. Validation & Parsing (HIGH)

4. 验证与解析(高)

  • valid-value-parser
    - Use value_parser for custom validation
  • valid-possible-values
    - Use PossibleValuesParser for string constraints
  • valid-fromstr-types
    - Implement FromStr for domain types
  • valid-try-parse
    - Use try_parse for graceful error handling
  • valid-num-args
    - Use num_args for value count constraints
  • valid-value-parser
    - 使用value_parser进行自定义验证
  • valid-possible-values
    - 使用PossibleValuesParser设置字符串约束
  • valid-fromstr-types
    - 为领域类型实现FromStr
  • valid-try-parse
    - 使用try-parse实现优雅的错误处理
  • valid-num-args
    - 使用num-args设置参数数量约束

5. Subcommand Architecture (MEDIUM-HIGH)

5. 子命令架构(中高)

  • subcmd-nested-hierarchy
    - Use nested subcommands for complex CLIs
  • subcmd-args-struct
    - Use struct for subcommand arguments
  • subcmd-required-help
    - Require subcommand or show help
  • subcmd-arg-groups
    - Use ArgGroup for one-of-many requirements
  • subcmd-external
    - Use external subcommands for plugin systems
  • subcmd-nested-hierarchy
    - 对复杂CLI使用嵌套子命令
  • subcmd-args-struct
    - 使用结构体定义子命令参数
  • subcmd-required-help
    - 要求必须指定子命令或显示帮助信息
  • subcmd-arg-groups
    - 使用ArgGroup定义多选一的参数组
  • subcmd-external
    - 使用外部子命令实现插件系统

6. Help & Documentation (MEDIUM)

6. 帮助与文档(中等)

  • help-shell-completions
    - Generate shell completions with clap_complete
  • help-next-heading
    - Use next_help_heading for organized help
  • help-after-help
    - Use after_help for examples and context
  • help-hide-options
    - Hide advanced options from default help
  • help-shell-completions
    - 使用clap_complete生成Shell补全
  • help-next-heading
    - 使用next_help_heading组织帮助文本结构
  • help-after-help
    - 使用after_help添加示例和上下文信息
  • help-hide-options
    - 在默认帮助中隐藏高级选项

7. Error Handling (MEDIUM)

7. 错误处理(中等)

  • error-exit-codes
    - Use appropriate exit codes
  • error-context
    - Add context to error messages
  • error-suggestions
    - Enable suggestions for typos
  • error-color-styles
    - Use colored output for error visibility
  • error-exit-codes
    - 使用合适的退出码
  • error-context
    - 为错误消息添加上下文信息
  • error-suggestions
    - 启用拼写错误的建议功能
  • error-color-styles
    - 使用彩色输出提高错误可见性

8. Testing Patterns (LOW-MEDIUM)

8. 测试模式(中低)

  • test-assert-cmd
    - Use assert_cmd for integration testing
  • test-predicates
    - Use predicates for flexible assertions
  • test-temp-files
    - Use assert_fs for temporary test files
  • test-parse-from
    - Use parse_from for unit testing parsers
  • test-trycmd-snapshots
    - Use trycmd for snapshot testing
  • test-assert-cmd
    - 使用assert_cmd进行集成测试
  • test-predicates
    - 使用predicates实现灵活的断言
  • test-temp-files
    - 使用assert_fs管理测试临时文件
  • test-parse-from
    - 使用parse-from进行解析器单元测试
  • test-trycmd-snapshots
    - 使用trycmd进行快照测试

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
阅读单个参考文件获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响程度说明
  • 规则模板 - 添加新规则的模板

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md类别定义和排序规则
assets/templates/_template.md新规则模板
metadata.json版本和参考信息