cli について
cliは、R cliパッケージで読みやすいコマンドライン出力を作るためのスキルガイドです。Rパッケージ開発者向けに、条件の整形、インラインマークアップ、進捗表示、意味的な要素を扱います。
主な機能
- 01エラー、警告、メッセージの整形
- 02コードや値のインライン表示
- 03単複に応じたテキスト整形
- 04プログレスバーと状態ステップ
- 05見出し、アラート、リストの作成
活用シーン
- 01Rパッケージのエラーへの状況説明追加
- 02一括処理中の進捗報告
- 03コマンドラインのメッセージやリストの整形
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ posit-dev/ skills --skill cliインストール後、Claude Code で/cliを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/ansi-operations.mdconditions.mdinline-markup.mdprogress.mdthemes.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_li()と組み合わせた cli_ul()、cli_ol()、cli_dl()
インラインマークアップの基本
{.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")
ベクトルの結合
ベクトルはカンマと「and」で自動的に結合されます。
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
マークアップの完全なリファレンス:50種類以上のインラインクラス、エッジケース、入れ子の規則、高度なパターンについては、references/inline-markup.mdを参照してください。
複数形化の基本
3つのパターンで複数形化するには、{?}を使います。
選択肢が1つの場合
nfile <- 1
cli_text("Found {nfile} file{?s}")
#> Found 1 file
nfile <- 3
cli_text("Found {nfile} file{?s}")
#> Found 3 files
選択肢が2つの場合
ndir <- 1
cli_text("Found {ndir} director{?y/ies}")
#> Found 1 directory
ndir <- 5
cli_text("Found {ndir} director{?y/ies}")
#> Found 5 directories
選択肢が3つの場合(ゼロ/1つ/複数)
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 条件:基本パターン
書式をより適切に整えるため、base RではなくCLI条件を使います。
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"- 成功(緑のチェックマーク)"*"- 箇条書き">"- 矢印/ポインター
高度なエラー設計:エラー設計の原則、rlangとの連携、テスト戦略、実環境でのパターンについては、references/conditions.mdを参照してください。
基本的な進捗インジケーター
シンプルな進捗ステップ
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
}
高度な進捗表示:ネストされた進捗、カスタム形式、並列処理、すべての進捗変数、Shinyとの連携については、references/progress.mdを参照してください。
セマンティックな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()
よくあるワークフロー
base 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 文字列操作(align、columns、nchar など)、ハイパーリンク、色の検出、CLI 出力のテスト、トラブルシューティング
外部リソース
関連パッケージ
- rlang - 条件処理とエラーオブジェクトが cli と統合されます
- glue - 文字列補間が cli の
{}構文を支えています - testthat - cli 出力のスナップショットテスト