mcpField
C
cli

cli

github.com/posit-dev开发551705 次安装今天更新
代码仓库

关于 cli

cli 是一项介绍 R cli 包的技能指南,帮助 R 包作者构建易读的命令行输出,涵盖格式化条件、行内标记、进度指示和语义化元素。

主要功能

  1. 01格式化错误、警告和消息
  2. 02代码与值的行内标记
  3. 03支持单复数的文本格式
  4. 04进度条与状态步骤
  5. 05语义化标题、提醒和列表

适用场景

  1. 01为 R 包错误补充上下文
  2. 02报告批量任务的进度
  3. 03格式化命令行消息与列表

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/posit-dev/skills --skill cli

安装后在 Claude Code 中输入/cli确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
ansi-operations.md
conditions.md
inline-markup.md
progress.md
themes.md

详细介绍

R 包的 CLI

何时使用什么

任务:显示包含上下文和格式的错误 使用:cli_abort(),搭配行内标记和项目符号列表

任务:显示带格式的警告 使用:cli_warn(),搭配行内标记

任务:显示提示信息 使用:cli_inform(),搭配行内标记

任务:为计数操作显示进度 使用:cli_progress_bar(),并指定总数

任务:显示简单的进度步骤 使用:cli_progress_step(),并附上状态消息

任务:格式化代码或函数名 使用:{.code ...} 或 {.fn package::function}

任务:格式化文件路径 使用:{.file path/to/file}

任务:格式化包名 使用:{.pkg packagename}

任务:格式化变量名 使用:{.var variable_name}

任务:格式化值 使用:{.val value}

任务:处理单复数文本 使用:{?s} 或 {?y/ies} 实现复数形式

任务:创建标题 使用:cli_h1()、cli_h2()、cli_h3()

任务:创建提醒 使用:cli_alert_success()、cli_alert_danger()、cli_alert_warning()、cli_alert_info()

任务:创建列表 使用:cli_ul()、cli_ol()、cli_dl(),并搭配 cli_li()

行内标记要点

使用 {.class content} 语法通过行内标记设置文本格式:

# Basic formatting
cli_text("Function {.fn mean} calculates averages")
cli_text("Install package {.pkg dplyr}")
cli_text("See file {.file ~/.Rprofile}")
cli_text("{.var x} must be numeric, not {.obj_type_of {x}}")
cli_text("Got value {.val {x}}")

# Code formatting
cli_text("Use {.code sum(x, na.rm = TRUE)}")

# Paths and arguments
cli_text("Reading from {.path /data/file.csv}")
cli_text("Set {.arg na.rm} to TRUE")

# Types and classes
cli_text("Object is {.cls data.frame}")

# Emphasis
cli_text("This is {.emph important}")
cli_text("This is {.strong critical}")

# Fields
cli_text("The {.field name} field is required")
向量合并

向量会自动用逗号和“以及”合并:

pkgs <- c("dplyr", "tidyr", "ggplot2")
cli_text("Installing packages: {.pkg {pkgs}}")
#> Installing packages: dplyr, tidyr, and ggplot2

files <- c("data.csv", "script.R")
cli_text("Found {length(files)} file{?s}: {.file {files}}")
#> Found 2 files: data.csv and script.R
转义大括号

使用双大括号 {{ 和 }} 转义字面大括号:

cli_text("Use {{variable}} syntax in glue")
#> Use {variable} syntax in glue

完整标记参考:参阅 references/inline-markup.md,了解全部 50 多种行内类、边缘情况、嵌套规则和高级模式。

单复数基础

使用 {?} 通过三种模式处理复数形式:

单个备选形式
nfile <- 1
cli_text("Found {nfile} file{?s}")
#> Found 1 file

nfile <- 3
cli_text("Found {nfile} file{?s}")
#> Found 3 files
两种备选形式
ndir <- 1
cli_text("Found {ndir} director{?y/ies}")
#> Found 1 directory

ndir <- 5
cli_text("Found {ndir} director{?y/ies}")
#> Found 5 directories
三种备选形式(零/一/多个)
nfile <- 0
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 0 files: no files

nfile <- 1
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 1 file: the file

nfile <- 3
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 3 files: the files
辅助函数:qty() 和 no()

使用 no() 显示“no”而非零:

nfile <- 0
cli_text("Found {no(nfile)} file{?s}")
#> Found no files

使用 qty() 显式设置数量:

nupd <- 3
ntotal <- 10
cli_text("{nupd}/{ntotal} {qty(nupd)} file{?s} {?needs/need} updates")
#> 3/10 files need updates

高级单复数处理:参阅 references/inline-markup.md,了解边缘情况和复杂模式。

CLI 条件:核心模式

使用 CLI 条件代替基础 R,以获得更好的格式:

cli_abort() - 格式化错误
# Before (base R)
stop("File not found: ", path)

# After (cli)
cli_abort("File {.file {path}} not found")

# With bullets for context
check_file <- function(path) {
  if (!file.exists(path)) {
    cli_abort(c(
      "File not found",
      "x" = "Cannot read {.file {path}}",
      "i" = "Check that the file exists"
    ))
  }
}
cli_warn() - 格式化警告
# Before (base R)
warning("Column ", col, " has missing values")

# After (cli)
cli_warn("Column {.field {col}} has missing values")

# With context
cli_warn(c(
  "Data quality issues detected",
  "!" = "Column {.field {col}} has {n_missing} missing value{?s}",
  "i" = "Consider using {.fn tidyr::drop_na}"
))
cli_inform() - 格式化消息
# Before (base R)
message("Processing ", n, " files")

# After (cli)
cli_inform("Processing {n} file{?s}")

# With structure
cli_inform(c(
  "v" = "Successfully loaded {.pkg dplyr}",
  "i" = "Version {packageVersion('dplyr')}"
))
项目符号类型
  • "x" - 错误/问题(红色 X)
  • "!" - 警告(黄色 !)
  • "i" - 信息(蓝色 i)
  • "v" - 成功(绿色勾号)
  • "*" - 项目符号
  • ">" - 箭头/指示符

高级错误设计:参阅 references/conditions.md,了解错误设计原则、rlang 集成、测试策略和实际应用模式。

基础进度指示器

简单进度步骤
process_data <- function() {
  cli_progress_step("Loading data")
  data <- load_data()

  cli_progress_step("Cleaning data")
  clean <- clean_data(data)

  cli_progress_step("Analyzing data")
  analyze(clean)
}
基础进度条
process_files <- function(files) {
  cli_progress_bar("Processing files", total = length(files))

  for (file in files) {
    process_file(file)
    cli_progress_update()
  }
}
自动清理

函数退出时,进度条会自动关闭:

process <- function() {
  cli_progress_bar("Working", total = 100)
  for (i in 1:100) {
    Sys.sleep(0.01)
    cli_progress_update()
  }
  # No need to call cli_progress_done() - auto-closes
}

高级进度功能:参阅 references/progress.md,了解嵌套进度、自定义格式、并行处理、所有进度变量和 Shiny 集成。

语义化 CLI 元素

标题
cli_h1("Main Section")
cli_h2("Subsection")
cli_h3("Detail")
提醒
cli_alert_success("Operation completed successfully")
cli_alert_danger("Critical error occurred")
cli_alert_warning("Potential issue detected")
cli_alert_info("Additional information available")
文本和代码
# Regular text with markup
cli_text("This is formatted text with {.emph emphasis}")

# Code blocks
cli_code(c(
  "library(dplyr)",
  "mtcars %>% filter(mpg > 20)"
))

# Verbatim text (no formatting)
cli_verbatim("This is displayed exactly as-is: {not interpolated}")
列表
# Unordered list
cli_ul()
cli_li("First item")
cli_li("Second item")
cli_end()

# Ordered list
cli_ol()
cli_li("First step")
cli_li("Second step")
cli_end()

# Definition list
cli_dl()
cli_li(c(name = "The name field"))
cli_li(c(email = "The email address"))
cli_end()

常见工作流

从基础 R 迁移到 CLI
# Before: Base R error handling
validate_input <- function(x, y) {
  if (!is.numeric(x)) {
    stop("x must be numeric")
  }
  if (length(y) == 0) {
    stop("y cannot be empty")
  }
  if (length(x) != length(y)) {
    stop("x and y must have the same length")
  }
}

# After: CLI error handling
validate_input <- function(x, y) {
  if (!is.numeric(x)) {
    cli_abort(c(
      "{.arg x} must be numeric",
      "x" = "You supplied a {.cls {class(x)}} vector",
      "i" = "Use {.fn as.numeric} to convert"
    ))
  }

  if (length(y) == 0) {
    cli_abort(c(
      "{.arg y} cannot be empty",
      "i" = "Provide at least one element"
    ))
  }

  if (length(x) != length(y)) {
    cli_abort(c(
      "{.arg x} and {.arg y} must have the same length",
      "x" = "{.arg x} has length {length(x)}",
      "x" = "{.arg y} has length {length(y)}"
    ))
  }
}
包含丰富上下文的错误消息
check_required_columns <- function(data, required_cols) {
  actual_cols <- names(data)
  missing_cols <- setdiff(required_cols, actual_cols)

  if (length(missing_cols) > 0) {
    cli_abort(c(
      "Required column{?s} missing from data",
      "x" = "Missing {length(missing_cols)} column{?s}: {.field {missing_cols}}",
      "i" = "Data has {length(actual_cols)} column{?s}: {.field {actual_cols}}",
      "i" = "Add the missing column{?s} or check for typos"
    ))
  }

  invisible(data)
}
带进度条的函数
process_files <- function(files, verbose = TRUE) {
  n <- length(files)

  if (verbose) {
    cli_progress_bar(
      format = "Processing {cli::pb_bar} {cli::pb_current}/{cli::pb_total} [{cli::pb_eta}]",
      total = n
    )
  }

  results <- vector("list", n)

  for (i in seq_along(files)) {
    results[[i]] <- process_file(files[[i]])

    if (verbose) {
      cli_progress_update()
    }
  }

  results
}

资源与高级主题

参考文件
  • references/inline-markup.md - 按类别整理的内联类完整目录、高级模式、嵌套规则和实际示例

  • references/conditions.md - 高级错误设计模式、rlang 集成、使用 testthat 快照进行测试、迁移指南和反模式

  • references/progress.md - 嵌套进度条、自定义格式、所有进度变量、并行处理、Shiny 集成和调试

  • references/themes.md - 完整的主题系统,包含类似 CSS 的选择器、容器函数、调色板、自定义主题和无障碍功能

  • references/ansi-operations.md - ANSI 字符串操作(对齐、列、nchar 等)、超链接、颜色检测、CLI 输出测试和故障排除

外部资源
相关包
  • rlang - 条件处理和错误对象与 cli 集成
  • glue - 字符串插值为 cli 的 {} 语法提供支持
  • testthat - 对 cli 输出进行快照测试

评论

支持 Markdown