From a5a013ce3790f65a73806e6310e475d8c2699681 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Sat, 24 Oct 2026 01:28:10 -0400 Subject: [PATCH 01/35] v2 init --- .Rbuildignore | 5 ++ .gitignore | 3 ++ .vscode/settings.json | 15 +++++- DESCRIPTION | 4 +- R/extendr-wrappers.R | 12 +++++ cleanup | 1 + cleanup.win | 1 + configure | 3 ++ configure.win | 2 + src/.gitignore | 8 +++ src/Makevars.in | 52 +++++++++++++++++++ src/Makevars.win.in | 51 +++++++++++++++++++ src/entrypoint.c | 10 ++++ src/rpkgkit-win.def | 2 + src/rust/Cargo.toml | 21 ++++++++ src/rust/document.rs | 20 ++++++++ src/rust/src/lib.rs | 16 ++++++ tools/config.R | 112 ++++++++++++++++++++++++++++++++++++++++ tools/msrv.R | 116 ++++++++++++++++++++++++++++++++++++++++++ 19 files changed, 452 insertions(+), 2 deletions(-) create mode 100644 R/extendr-wrappers.R create mode 100644 cleanup create mode 100644 cleanup.win create mode 100755 configure create mode 100644 configure.win create mode 100644 src/.gitignore create mode 100644 src/Makevars.in create mode 100644 src/Makevars.win.in create mode 100644 src/entrypoint.c create mode 100644 src/rpkgkit-win.def create mode 100644 src/rust/Cargo.toml create mode 100644 src/rust/document.rs create mode 100644 src/rust/src/lib.rs create mode 100644 tools/config.R create mode 100644 tools/msrv.R diff --git a/.Rbuildignore b/.Rbuildignore index 89e8537..095240f 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -77,3 +77,8 @@ ^\.uvr$ ^\.clangd$ ^\.build\.timestamp$ +^src/\.cargo$ +^src/rust/vendor$ +^src/rust/target$ +^src/Makevars$ +^src/Makevars\.win$ diff --git a/.gitignore b/.gitignore index f2ce683..687d86e 100644 --- a/.gitignore +++ b/.gitignore @@ -53,3 +53,6 @@ inst/doc .posit/assistant/skills/r-lib tests/testthat/_problems/ tests/testthat/testthat-problems.rds +src/rust/vendor +src/Makevars +src/Makevars.win diff --git a/.vscode/settings.json b/.vscode/settings.json index 127178c..391adb7 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,17 @@ { + "rust-analyzer.linkedProjects": [ + "${workspaceFolder}/src/rust/Cargo.toml" + ], + "files.associations": { + "Makevars": "makefile", + "Makevars.in": "makefile", + "Makevars.win": "makefile", + "Makevars.win.in": "makefile", + "configure": "shellscript", + "configure.win": "shellscript", + "cleanup": "shellscript", + "cleanup.win": "shellscript" + }, "[quarto]": { "editor.defaultFormatter": "quarto.quarto", "editor.formatOnSave": true @@ -18,4 +31,4 @@ "positron.r.useNativePipe": true, "r.rpath.linux": "/opt/R/4.5.1/lib/R/bin/R", "r.rterm.linux": "/opt/R/4.5.1/lib/R/bin/R" -} +} \ No newline at end of file diff --git a/DESCRIPTION b/DESCRIPTION index 0d5c959..1425d4f 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -22,7 +22,7 @@ URL: https://github.com/WangLabCSU/rpkgkit, https://wanglabcsu.github.io/rpkgkit/ BugReports: https://github.com/WangLabCSU/rpkgkit/issues Depends: - R (>= 4.1.0) + R (>= 4.2) Imports: cli, lifecycle, @@ -54,3 +54,5 @@ Copyright: Jacob Scott, Christopher T. Kenny, and Sebastian Lammers (for Encoding: UTF-8 Roxygen: list(markdown = TRUE) Config/roxygen2/version: 8.1.0 +Config/rextendr/version: 0.5.0 +SystemRequirements: Cargo (Rust's package manager), rustc >= 1.65.0, xz diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R new file mode 100644 index 0000000..5899981 --- /dev/null +++ b/R/extendr-wrappers.R @@ -0,0 +1,12 @@ +# Generated by extendr: Do not edit by hand +# nolint start + +#' @usage NULL +#' @useDynLib rpkgkit, .registration = TRUE +NULL + +#' Return string `"Hello world!"` to R. +#' @export +hello_world <- function() .Call(wrap__hello_world) + +# nolint end diff --git a/cleanup b/cleanup new file mode 100644 index 0000000..e346d71 --- /dev/null +++ b/cleanup @@ -0,0 +1 @@ +rm -f src/Makevars diff --git a/cleanup.win b/cleanup.win new file mode 100644 index 0000000..a182174 --- /dev/null +++ b/cleanup.win @@ -0,0 +1 @@ +rm -f src/Makevars.win diff --git a/configure b/configure new file mode 100755 index 0000000..c608b11 --- /dev/null +++ b/configure @@ -0,0 +1,3 @@ +#!/usr/bin/env sh +: "${R_HOME=`R RHOME`}" +"${R_HOME}/bin/Rscript" tools/config.R diff --git a/configure.win b/configure.win new file mode 100644 index 0000000..57eb255 --- /dev/null +++ b/configure.win @@ -0,0 +1,2 @@ +#!/usr/bin/env sh +"${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" tools/config.R diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..24e51fc --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,8 @@ +*.o +*.so +*.dll +target +.cargo +rust/vendor +Makevars +Makevars.win diff --git a/src/Makevars.in b/src/Makevars.in new file mode 100644 index 0000000..71c6c91 --- /dev/null +++ b/src/Makevars.in @@ -0,0 +1,52 @@ +TARGET_DIR = ./rust/target +LIBDIR = $(TARGET_DIR)/@LIBDIR@ +STATLIB = $(LIBDIR)/librpkgkit.a +PKG_LIBS = -L$(LIBDIR) -lrpkgkit + +all: $(SHLIB) rust_clean + +.PHONY: $(STATLIB) + +$(SHLIB): $(STATLIB) + +CARGOTMP = $(CURDIR)/.cargo +VENDOR_DIR = $(CURDIR)/vendor + + +# RUSTFLAGS appends --print=native-static-libs to ensure that +# the correct linkers are used. Use this for debugging if need. +# +# CRAN note: Cargo and Rustc versions are reported during +# configure via tools/msrv.R. +# +# If a vendor directory exists, it is used for offline compilation. Otherwise if +# vendor.tar.xz exists, it is unzipped and used for offline compilation. +$(STATLIB): + + if [ -d ./vendor ]; then \ + echo "=== Using offline vendor directory ==="; \ + mkdir -p $(CARGOTMP) && \ + cp rust/vendor-config.toml $(CARGOTMP)/config.toml; \ + elif [ -f ./rust/vendor.tar.xz ]; then \ + echo "=== Using offline vendor tarball ==="; \ + tar xf rust/vendor.tar.xz && \ + mkdir -p $(CARGOTMP) && \ + cp rust/vendor-config.toml $(CARGOTMP)/config.toml; \ + fi + + export CARGO_HOME=$(CARGOTMP) && \ + export PATH="$(PATH):$(HOME)/.cargo/bin" && \ + @PANIC_EXPORTS@RUSTFLAGS="$(RUSTFLAGS) --print=native-static-libs" cargo build @CRAN_FLAGS@ --lib @PROFILE@ --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR) @TARGET@ + + export CARGO_HOME=$(CARGOTMP) && \ + export PATH="$(PATH):$(HOME)/.cargo/bin" && \ + cargo run @CRAN_FLAGS@ --bin document --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR) @TARGET@ + + # Always clean up CARGOTMP + rm -Rf $(CARGOTMP); + +rust_clean: $(SHLIB) + rm -Rf $(CARGOTMP) $(VENDOR_DIR) @CLEAN_TARGET@ + +clean: + rm -Rf $(SHLIB) $(STATLIB) $(OBJECTS) $(TARGET_DIR) $(VENDOR_DIR) diff --git a/src/Makevars.win.in b/src/Makevars.win.in new file mode 100644 index 0000000..079d8fb --- /dev/null +++ b/src/Makevars.win.in @@ -0,0 +1,51 @@ +TARGET = $(subst 64,x86_64,$(subst 32,i686,$(WIN)))-pc-windows-gnu + +TARGET_DIR = ./rust/target +LIBDIR = $(TARGET_DIR)/$(TARGET)/@LIBDIR@ +STATLIB = $(LIBDIR)/librpkgkit.a +PKG_LIBS = -L$(LIBDIR) -lrpkgkit -lws2_32 -ladvapi32 -luserenv -lbcrypt -lntdll + +all: $(SHLIB) rust_clean + +.PHONY: $(STATLIB) + +$(SHLIB): $(STATLIB) + +CARGOTMP = $(CURDIR)/.cargo +VENDOR_DIR = vendor + +$(STATLIB): + mkdir -p $(TARGET_DIR)/libgcc_mock + touch $(TARGET_DIR)/libgcc_mock/libgcc_eh.a + + # If a vendor directory exists, it is used for offline compilation. Otherwise if + # vendor.tar.xz exists, it is unzipped and used for offline compilation. + if [ -d ./vendor ]; then \ + echo "=== Using offline vendor directory ==="; \ + mkdir -p $(CARGOTMP) && \ + cp rust/vendor-config.toml $(CARGOTMP)/config.toml; \ + elif [ -f ./rust/vendor.tar.xz ]; then \ + echo "=== Using offline vendor tarball ==="; \ + tar xf rust/vendor.tar.xz && \ + mkdir -p $(CARGOTMP) && \ + cp rust/vendor-config.toml $(CARGOTMP)/config.toml; \ + fi + + # Build the project using Cargo with additional flags + export CARGO_HOME=$(CARGOTMP) && \ + export LIBRARY_PATH="$(LIBRARY_PATH);$(CURDIR)/$(TARGET_DIR)/libgcc_mock" && \ + RUSTFLAGS="$(RUSTFLAGS) --print=native-static-libs" cargo build @CRAN_FLAGS@ --target=$(TARGET) --lib @PROFILE@ --manifest-path=rust/Cargo.toml --target-dir=$(TARGET_DIR) + + # Generate wrappers + export CARGO_HOME=$(CARGOTMP) && \ + export PATH="$(PATH):$(HOME)/.cargo/bin" && \ + cargo run @CRAN_FLAGS@ --bin document --target $(TARGET) --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR) + + # Always clean up CARGOTMP + rm -Rf $(CARGOTMP); + +rust_clean: $(SHLIB) + rm -Rf $(CARGOTMP) $(VENDOR_DIR) @CLEAN_TARGET@ + +clean: + rm -Rf $(SHLIB) $(STATLIB) $(OBJECTS) $(TARGET_DIR) $(VENDOR_DIR) diff --git a/src/entrypoint.c b/src/entrypoint.c new file mode 100644 index 0000000..113622b --- /dev/null +++ b/src/entrypoint.c @@ -0,0 +1,10 @@ +// We need to forward routine registration from C to Rust +// to avoid the linker removing the static library. + +void R_init_rpkgkit_extendr(void *dll); +void register_extendr_panic_hook(void); + +void R_init_rpkgkit(void *dll) { + register_extendr_panic_hook(); + R_init_rpkgkit_extendr(dll); +} diff --git a/src/rpkgkit-win.def b/src/rpkgkit-win.def new file mode 100644 index 0000000..8c22465 --- /dev/null +++ b/src/rpkgkit-win.def @@ -0,0 +1,2 @@ +EXPORTS +R_init_rpkgkit diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml new file mode 100644 index 0000000..365811e --- /dev/null +++ b/src/rust/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = 'rpkgkit' +publish = false +version = '0.1.0' +edition = '2021' +rust-version = '1.65' + +[lib] +crate-type = [ 'rlib', 'staticlib' ] +name = 'rpkgkit' + +[[bin]] +name = 'document' +path = 'document.rs' + +[dependencies] +extendr-api = '0.9.0' + +[profile.release] +lto = true +codegen-units = 1 diff --git a/src/rust/document.rs b/src/rust/document.rs new file mode 100644 index 0000000..e118d77 --- /dev/null +++ b/src/rust/document.rs @@ -0,0 +1,20 @@ +// Generated by extendr: Do not edit by hand +fn main() -> Result<(), Box> { + let wrapper_path = "../R/extendr-wrappers.R"; + let header = "\ + # Generated by extendr: Do not edit by hand\n\ + # nolint start\n\ + \n\ + #' @usage NULL\n\ + #' @useDynLib rpkgkit, .registration = TRUE\n\ + NULL\n\ + \n\ + "; + let footer = "# nolint end\n"; + let wrappers = rpkgkit::get_rpkgkit_metadata() + .make_r_wrappers(true, "rpkgkit") + .map_err(|e| format!("failed to generate wrappers: {e}"))?; + std::fs::write(wrapper_path, format!("{header}{wrappers}{footer}")) + .map_err(|e| format!("failed to write {wrapper_path}: {e}"))?; + Ok(()) +} diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs new file mode 100644 index 0000000..dd57862 --- /dev/null +++ b/src/rust/src/lib.rs @@ -0,0 +1,16 @@ +use extendr_api::prelude::*; + +/// Return string `"Hello world!"` to R. +/// @export +#[extendr] +fn hello_world() -> &'static str { + "Hello world!" +} + +// Macro to generate exports. +// This ensures exported functions are registered with R. +// See corresponding C code in `entrypoint.c`. +extendr_module! { + mod rpkgkit; + fn hello_world; +} diff --git a/tools/config.R b/tools/config.R new file mode 100644 index 0000000..06d57cd --- /dev/null +++ b/tools/config.R @@ -0,0 +1,112 @@ +# Note: Any variables prefixed with `.` are used for text +# replacement in the Makevars.in and Makevars.win.in + +# check the packages MSRV first +source("tools/msrv.R") + +# check DEBUG and NOT_CRAN environment variables +env_debug <- Sys.getenv("DEBUG") +env_not_cran <- Sys.getenv("NOT_CRAN") + +# check if the vendored zip file exists +vendor_exists <- file.exists("src/rust/vendor.tar.xz") + +is_not_cran <- env_not_cran != "" +is_debug <- env_debug != "" + +if (is_debug) { + # if we have DEBUG then we set not cran to true + # CRAN is always release build + is_not_cran <- TRUE + message("Creating DEBUG build.") +} + +if (!is_not_cran) { + message("Building for CRAN.") +} + +# we set cran flags only if NOT_CRAN is empty and if +# the vendored crates are present. +.cran_flags <- ifelse( + !is_not_cran && vendor_exists, + "-j 2 --offline", + "" +) + +# when DEBUG env var is present we use `--debug` build +.profile <- ifelse(is_debug, "", "--release") +.clean_targets <- ifelse(is_debug, "", "$(TARGET_DIR)") + +# We specify this target when building for webR +webr_target <- "wasm32-unknown-emscripten" + +# here we check if the platform we are building for is webr +is_wasm <- identical(R.version$platform, webr_target) + +# print to terminal to inform we are building for webr +if (is_wasm) { + message("Building for WebR") +} + +# we check if we are making a debug build or not +# if so, the LIBDIR environment variable becomes: +# LIBDIR = $(TARGET_DIR)/{wasm32-unknown-emscripten}/debug +# this will be used to fill out the LIBDIR env var for Makevars.in +target_libpath <- if (is_wasm) "wasm32-unknown-emscripten" else NULL +cfg <- if (is_debug) "debug" else "release" + +# used to replace @LIBDIR@ +.libdir <- paste(c(target_libpath, cfg), collapse = "/") + +# use this to replace @TARGET@ +# we specify the target _only_ on webR +# there may be use cases later where this can be adapted or expanded +.target <- ifelse(is_wasm, paste0("--target=", webr_target), "") + +# add panic exports only for WASM builds +.panic_exports <- ifelse( + is_wasm, + "CARGO_PROFILE_DEV_PANIC=\"abort\" CARGO_PROFILE_RELEASE_PANIC=\"abort\" ", + "" +) + +# read in the Makevars.in file checking +is_windows <- .Platform[["OS.type"]] == "windows" + +# if windows we replace in the Makevars.win.in +mv_fp <- ifelse( + is_windows, + "src/Makevars.win.in", + "src/Makevars.in" +) + +# set the output file +mv_ofp <- ifelse( + is_windows, + "src/Makevars.win", + "src/Makevars" +) + +# delete the existing Makevars{.win/.wasm} +if (file.exists(mv_ofp)) { + message("Cleaning previous `", mv_ofp, "`.") + invisible(file.remove(mv_ofp)) +} + +# read as a single string +mv_txt <- readLines(mv_fp) + +# replace placeholder values +new_txt <- gsub("@CRAN_FLAGS@", .cran_flags, mv_txt) |> + gsub("@PROFILE@", .profile, x = _) |> + gsub("@CLEAN_TARGET@", .clean_targets, x = _) |> + gsub("@LIBDIR@", .libdir, x = _) |> + gsub("@TARGET@", .target, x = _) |> + gsub("@PANIC_EXPORTS@", .panic_exports, x = _) + +message("Writing `", mv_ofp, "`.") +con <- file(mv_ofp, open = "wb") +writeLines(new_txt, con, sep = "\n") +close(con) + +message("`tools/config.R` has finished.") diff --git a/tools/msrv.R b/tools/msrv.R new file mode 100644 index 0000000..59a61ab --- /dev/null +++ b/tools/msrv.R @@ -0,0 +1,116 @@ +# read the DESCRIPTION file +desc <- read.dcf("DESCRIPTION") + +if (!"SystemRequirements" %in% colnames(desc)) { + fmt <- c( + "`SystemRequirements` not found in `DESCRIPTION`.", + "Please specify `SystemRequirements: Cargo (Rust's package manager), rustc`" + ) + stop(paste(fmt, collapse = "\n")) +} + +# extract system requirements +sysreqs <- desc[, "SystemRequirements"] + +# check that cargo and rustc is found +if (!grepl("cargo", sysreqs, ignore.case = TRUE)) { + stop("You must specify `Cargo (Rust's package manager)` in your `SystemRequirements`") +} + +if (!grepl("rustc", sysreqs, ignore.case = TRUE)) { + stop("You must specify `Cargo (Rust's package manager), rustc` in your `SystemRequirements`") +} + +# split into parts +parts <- strsplit(sysreqs, ", ")[[1]] + +# identify which is the rustc +rustc_ver <- parts[grepl("rustc", parts)] + +# perform checks for the presence of rustc and cargo on the OS +no_cargo_msg <- c( + "----------------------- [CARGO NOT FOUND]--------------------------", + "The 'cargo' command was not found on the PATH. Please install Cargo", + "from: https://www.rust-lang.org/tools/install", + "", + "Alternatively, you may install Cargo from your OS package manager:", + " - Debian/Ubuntu: apt-get install cargo", + " - Fedora/CentOS: dnf install cargo", + " - macOS: brew install rust", + "-------------------------------------------------------------------" +) + +no_rustc_msg <- c( + "----------------------- [RUST NOT FOUND]---------------------------", + "The 'rustc' compiler was not found on the PATH. Please install", + paste(rustc_ver, "or higher from:"), + "https://www.rust-lang.org/tools/install", + "", + "Alternatively, you may install Rust from your OS package manager:", + " - Debian/Ubuntu: apt-get install rustc", + " - Fedora/CentOS: dnf install rustc", + " - macOS: brew install rust", + "-------------------------------------------------------------------" +) + +# Add {user}/.cargo/bin to path before checking +new_path <- paste0( + Sys.getenv("PATH"), + ":", + paste0(Sys.getenv("HOME"), "/.cargo/bin") +) + +# set the path with the new path +Sys.setenv("PATH" = new_path) + +# check for rustc installation +rustc_version <- tryCatch( + system("rustc --version", intern = TRUE), + error = function(e) { + stop(paste(no_rustc_msg, collapse = "\n")) + } +) + +# check for cargo installation +cargo_version <- tryCatch( + system("cargo --version", intern = TRUE), + error = function(e) { + stop(paste(no_cargo_msg, collapse = "\n")) + } +) + +# helper function to extract versions +extract_semver <- function(ver) { + if (grepl("\\d+\\.\\d+(\\.\\d+)?", ver)) { + sub(".*?(\\d+\\.\\d+(\\.\\d+)?).*", "\\1", ver) + } else { + NA + } +} + +# get the MSRV +msrv <- extract_semver(rustc_ver) + +# extract current version +current_rust_version <- extract_semver(rustc_version) + +# perform check +if (!is.na(msrv)) { + # -1 when current version is later + # 0 when they are the same + # 1 when MSRV is newer than current + is_msrv <- utils::compareVersion(msrv, current_rust_version) + if (is_msrv == 1) { + fmt <- paste0( + "\n------------------ [UNSUPPORTED RUST VERSION]------------------\n", + "- Minimum supported Rust version is %s.\n", + "- Installed Rust version is %s.\n", + "---------------------------------------------------------------" + ) + stop(sprintf(fmt, msrv, current_rust_version)) + } +} + +# print the versions +versions_fmt <- "Using %s\nUsing %s" +message(sprintf(versions_fmt, cargo_version, rustc_version)) From 230cde63e963f832cd5f54e8c3f5ef830282bab9 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Sat, 24 Oct 2026 01:38:42 -0400 Subject: [PATCH 02/35] update _pkgodwn.yml --- _pkgdown.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/_pkgdown.yml b/_pkgdown.yml index ff36d41..064b0d1 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -61,6 +61,7 @@ reference: - add_global_gitgnore - add_global_rbuildignore - air_format + - check_air_installed - badge_translated_by_ai - browse_standalone - check_pkgdown_reference From 77e69fcc876a35aef1a039feb16b64564822d653 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Sun, 25 Oct 2026 21:31:31 -0400 Subject: [PATCH 03/35] add citation --- CITATION.cff | 29 +++++++++++++++++++++++++++++ README.Rmd | 15 +++++++++++++++ README.md | 15 +++++++++++++++ inst/CITATION | 16 ++++++++++++++++ man/optimize_rmd_yaml.Rd | 2 +- man/package_optimize_rmd_yaml.Rd | 2 +- 6 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 CITATION.cff create mode 100644 inst/CITATION diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000..689e01c --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,29 @@ +# This CITATION.cff file was generated with cffinit. +# Visit https://bit.ly/cffinit to generate yours today! + +cff-version: 1.2.0 +title: rpkgkit +message: >- + If you use this software, please cite it using the + metadata from this file. +type: software +authors: + - given-names: Yuxi + family-names: Yang + email: 15364051195@163.com + affiliation: >- + Department of Biomedical Informatics, School of Life + Sciences, Central South University, Changsha, China + orcid: 'https://orcid.org/0009-0006-1329-1224' +repository-code: 'https://github.com/WangLabCSU/rpkgkit' +url: 'https://wanglabcsu.github.io/rpkgkit/' +abstract: >- + rpkgkit provides utilities for creating and maintaining R + packages. The functions support common development tasks + such as managing standalone scripts, maintaining NEWS.md, + modernizing R source, configuring package infrastructure, + and maintaining README files. +keywords: + - r package development + - r programming + - r package automation diff --git a/README.Rmd b/README.Rmd index 0f0e674..6a84d66 100644 --- a/README.Rmd +++ b/README.Rmd @@ -90,6 +90,21 @@ It's recommended to use following packages together with `rpkgkit`: - [`usethis`](https://usethis.r-lib.org/): manage package metadata. - [`devtools`](https://devtools.r-lib.org/): build and check package. +## AI skills + +`rpkgkit` ships an agent skill that tells coding agents when to reach for +`rpkgkit` and how to call it. It follows the +[Agent Skills](https://skills.sh) layout, so it works with Claude Code, Codex, +Cursor, Positron, and other compatible agents: + +```bash +npx skills add WangLabCSU/rpkgkit --skill rpkgkit +``` + +Add `-g` to install it for every project, and `-a ` to skip the agent +prompt. The skill source lives in +[`skills/rpkgkit/`](https://github.com/WangLabCSU/rpkgkit/tree/main/skills/rpkgkit). + ## Acknowledgements We would like to thank the following people and projects: diff --git a/README.md b/README.md index 2f5bcac..6909dd3 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,21 @@ It’s recommended to use following packages together with `rpkgkit`: - [`usethis`](https://usethis.r-lib.org/): manage package metadata. - [`devtools`](https://devtools.r-lib.org/): build and check package. +## AI skills + +`rpkgkit` ships an agent skill that tells coding agents when to reach +for `rpkgkit` and how to call it. It follows the [Agent +Skills](https://skills.sh) layout, so it works with Claude Code, Codex, +Cursor, Positron, and other compatible agents: + +``` bash +npx skills add WangLabCSU/rpkgkit --skill rpkgkit +``` + +Add `-g` to install it for every project, and `-a ` to skip the +agent prompt. The skill source lives in +[`skills/rpkgkit/`](https://github.com/WangLabCSU/rpkgkit/tree/main/skills/rpkgkit). + ## Acknowledgements We would like to thank the following people and projects: diff --git a/inst/CITATION b/inst/CITATION new file mode 100644 index 0000000..7e9aec1 --- /dev/null +++ b/inst/CITATION @@ -0,0 +1,16 @@ +citHeader("To cite rpkgkit in publications use:") + +bibentry( + bibtype = "Manual", + title = "rpkgkit: Create and Maintain R Packages", + author = c( + person("Yuxi", "Yang", email = "15364051195@163.com") + ), + year = "2026", + note = paste0("R package version ", meta$Version), + url = "https://wanglabcsu.github.io/rpkgkit/" +) + +citFooter( + "Corresponding repository: https://github.com/WangLabCSU/rpkgkit" +) diff --git a/man/optimize_rmd_yaml.Rd b/man/optimize_rmd_yaml.Rd index ce40c25..e4b5101 100644 --- a/man/optimize_rmd_yaml.Rd +++ b/man/optimize_rmd_yaml.Rd @@ -24,7 +24,7 @@ RStudio editor is used.} \item{readme_format}{Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html".} -\item{date}{"auto" -> 2026-10-24; "desc" -> DESCRIPTION Date field; +\item{date}{"auto" -> 2026-10-25; "desc" -> DESCRIPTION Date field; "none" -> do not add a date.} \item{extra}{Named list of extra YAML fields added to the file. It is merged diff --git a/man/package_optimize_rmd_yaml.Rd b/man/package_optimize_rmd_yaml.Rd index 556ad3a..9cbe94a 100644 --- a/man/package_optimize_rmd_yaml.Rd +++ b/man/package_optimize_rmd_yaml.Rd @@ -25,7 +25,7 @@ package_optimize_rmd_yaml( \item{readme_format}{Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html".} -\item{date}{"auto" -> 2026-10-24; "desc" -> DESCRIPTION Date field; +\item{date}{"auto" -> 2026-10-25; "desc" -> DESCRIPTION Date field; "none" -> do not add a date.} \item{extra}{Named list of extra YAML fields added to the file. It is merged From d2b296ed34e0548a3a0378557f4b69abfa343729 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Wed, 28 Oct 2026 22:20:33 -0400 Subject: [PATCH 04/35] * Added `use_workflow_rust_compatible_check()` --- NAMESPACE | 1 + NEWS.md | 22 +++ R/20_convert_int_literals.R | 2 +- R/21_convert_pipe.R | 2 +- R/42C_use_workflow_rust_compatible_check.R | 91 ++++++++++++ R/46_use_r_v4.1.0.R | 2 +- R/49_use_url.R | 2 +- R/50_use_bugreports.R | 2 +- R/73_badge_to_readme.R | 10 +- _pkgdown.yml | 1 + .../rust_compatible_check/R-CMD-Check.yaml | 53 +++++++ man/badge_to_readme.Rd | 10 +- man/convert_int_literals.Rd | 2 +- man/convert_pipe.Rd | 2 +- man/optimize_rmd_yaml.Rd | 2 +- man/package_optimize_rmd_yaml.Rd | 2 +- man/use_bugreports.Rd | 2 +- man/use_r_v4.1.0.Rd | 2 +- man/use_url.Rd | 2 +- man/use_workflow_rust_compatible_check.Rd | 56 +++++++ skills/rpkgkit/SKILL.md | 14 +- .../rpkgkit/references/function-reference.md | 1 + .../test-use_workflow_rust_compatible_check.R | 140 ++++++++++++++++++ vignettes/pkg_maintain.Rmd | 59 ++++++++ 24 files changed, 457 insertions(+), 25 deletions(-) create mode 100644 R/42C_use_workflow_rust_compatible_check.R create mode 100644 inst/actions/rust_compatible_check/R-CMD-Check.yaml create mode 100644 man/use_workflow_rust_compatible_check.Rd create mode 100644 tests/testthat/test-use_workflow_rust_compatible_check.R diff --git a/NAMESPACE b/NAMESPACE index 51b7be1..6383e23 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -53,6 +53,7 @@ export(use_multilanguage_readme) export(use_r_v4.1.0) export(use_url) export(use_vendor) +export(use_workflow_rust_compatible_check) export(use_workflow_test_branch) export(use_workflow_version_update) export(use_zzz) diff --git a/NEWS.md b/NEWS.md index e865530..8046a82 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,25 @@ +# rpkgkit 0.1.22 (2026-10-28) + +## NEW FEATURES + +* Added `use_workflow_rust_compatible_check()` to install a + `.github/workflows/R-CMD-check.yaml` that can build packages shipping Rust + code. It copies the bundled `R-CMD-Check.yaml` template to the target + package, creating `.github/workflows/` when needed. Unlike the workflow from + `usethis::use_github_action("check-standard")`, which only sets up R and + leaves the runner's default toolchain in place, the template installs Rust + through `dtolnay/rust-toolchain` and, on Windows, additionally the + `x86_64-pc-windows-gnu` target: the Windows runner defaults to an MSVC + toolchain while R and Rtools are GNU based, so the static library produced by + `cargo` cannot be linked and the build noise makes `R CMD check` report a + WARNING. The job matrix covers Windows, macOS, Ubuntu release and Ubuntu + devel with `fail-fast: false`, and sets `R_REMOTES_NO_ERRORS_FROM_WARNINGS` so + that download noise from `remotes`/`pak` does not surface as a check failure. + The function aborts when the path is not a package root, when the template is + missing, or when the workflow file already exists and `overwrite = FALSE`, and + it returns the created path invisibly. The template follows the official + `extendr` CI. + # rpkgkit 0.1.21 (2026-10-19) ## NEW FEATURES diff --git a/R/20_convert_int_literals.R b/R/20_convert_int_literals.R index 276c4db..a198eee 100644 --- a/R/20_convert_int_literals.R +++ b/R/20_convert_int_literals.R @@ -50,7 +50,7 @@ #' - adjacent to an identifier character (`a-zA-Z0-9._`). #' #' @examples -#' \donttest{ +#' \dontrun{ #' # --- Single file --- #' temp <- tempfile(fileext = ".R") #' writeLines("tmp <- seq_len(10)", temp) diff --git a/R/21_convert_pipe.R b/R/21_convert_pipe.R index 110872d..b1cbef8 100644 --- a/R/21_convert_pipe.R +++ b/R/21_convert_pipe.R @@ -49,7 +49,7 @@ #' unchanged. #' #' @examples -#' \donttest{ +#' \dontrun{ #' # --- Single file --- #' temp <- tempfile(fileext = ".R") #' writeLines("mtcars |> dplyr::filter(cyl > 4)", temp) diff --git a/R/42C_use_workflow_rust_compatible_check.R b/R/42C_use_workflow_rust_compatible_check.R new file mode 100644 index 0000000..df91387 --- /dev/null +++ b/R/42C_use_workflow_rust_compatible_check.R @@ -0,0 +1,91 @@ +#' Create a Rust-compatible R-CMD-check Workflow +#' +#' @description +#' Copies the built-in `R-CMD-Check.yaml` workflow template to the target +#' package's `.github/workflows/` directory, so that `R CMD check` runs on +#' GitHub Actions with a toolchain that can download, compile and link Rust +#' crates (packages built on `extendr`/`rextendr`). +#' +#' @section Why not the `usethis` workflow: +#' `usethis::use_github_action("check-standard")` only sets up R and then calls +#' `R CMD check` on a matrix of operating systems. For packages with Rust code +#' this is not enough: +#' +#' * No Rust toolchain is installed, so the runner default is used. On Windows +#' that default is an **MSVC** toolchain, while R and Rtools are **GNU** +#' based, so the static library produced by `cargo` cannot be linked, and the +#' resulting build noise (`cargo` warnings, linker messages) makes +#' `R CMD check` report a WARNING. +#' +#' The template used here follows the official `extendr` CI: +#' +#' * `dtolnay/rust-toolchain` installs the requested toolchain, and on Windows +#' additionally the `x86_64-pc-windows-gnu` target that Rtools can link. +#' * The R matrix covers Windows, macOS, Ubuntu release and Ubuntu devel, with +#' `fail-fast: false` so one broken platform does not hide the others. +#' * `R_REMOTES_NO_ERRORS_FROM_WARNINGS` keeps `remotes`/`pak` download noise +#' from turning into check failures. +#' +#' @param path Character. Path to the package root directory. If \code{NULL} +#' (the default), uses the current working directory. +#' @param overwrite Logical. If `TRUE`, overwrite an existing workflow file. +#' Defaults to `FALSE`. +#' +#' @return Invisibly returns the path to the created workflow file. +#' @export +#' +#' @examples +#' \dontrun{ +#' temp <- tempdir() +#' usethis::create_package(temp) +#' use_workflow_rust_compatible_check(temp) +#' use_workflow_rust_compatible_check(temp, overwrite = TRUE) +#' } +use_workflow_rust_compatible_check <- function( + path = NULL, + overwrite = FALSE +) { + path <- path %||% "." + if (!is_pkg(path)) { + cli::cli_abort(c( + "x" = "{.path {path}} is not an R package root.", + ">" = "No {.file DESCRIPTION} found." + )) + } + + # Source workflow template from inst/ + workflow_src <- system.file( + "actions", + "rust_compatible_check", + "R-CMD-Check.yaml", + package = "rpkgkit" + ) + + if (!nzchar(workflow_src) || !file.exists(workflow_src)) { + cli::cli_abort(c( + "x" = "Workflow template {.file R-CMD-Check.yaml} was not found.", + ">" = "Reinstall {.pkg rpkgkit} to restore {.path inst/actions/rust_compatible_check/}." + )) + } + + # ── Copy workflow file to .github/workflows/ ── + workflow_target <- file.path(path, ".github", "workflows") + dir.create(workflow_target, recursive = TRUE, showWarnings = FALSE) + + workflow_dst <- file.path(workflow_target, "R-CMD-check.yaml") + + if (file.exists(workflow_dst) && isFALSE(overwrite)) { + cli::cli_abort(c( + "x" = "{.file {workflow_dst}} already exists. Use `overwrite = TRUE` to overwrite." + )) + } + file.copy(from = workflow_src, to = workflow_dst, overwrite = TRUE) + + cli::cli_inform(c( + "v" = "Created workflow: {.path {workflow_dst}}", + ">" = "It triggers on push to {.val main} and on pull requests targeting {.val main}.", + ">" = "Rust crates are compiled with a pinned toolchain and the {.val x86_64-pc-windows-gnu} target on Windows, so they link against Rtools." + )) + + invisible(workflow_dst) +} diff --git a/R/46_use_r_v4.1.0.R b/R/46_use_r_v4.1.0.R index b92a1bc..dc1ed8e 100644 --- a/R/46_use_r_v4.1.0.R +++ b/R/46_use_r_v4.1.0.R @@ -17,7 +17,7 @@ #' @export #' #' @examples -#' \donttest{ +#' \dontrun{ #' tmpdir <- tempdir() #' usethis::create_package(path = tmpdir) #' use_r_v4.1.0(path = tmpdir) diff --git a/R/49_use_url.R b/R/49_use_url.R index d307e28..c838950 100644 --- a/R/49_use_url.R +++ b/R/49_use_url.R @@ -23,7 +23,7 @@ #' @export #' #' @examples -#' \donttest{ +#' \dontrun{ #' tmpdir <- tempdir() #' usethis::create_package(path = tmpdir) #' use_url( diff --git a/R/50_use_bugreports.R b/R/50_use_bugreports.R index df78d10..c2bcfbf 100644 --- a/R/50_use_bugreports.R +++ b/R/50_use_bugreports.R @@ -20,7 +20,7 @@ #' @export #' #' @examples -#' \donttest{ +#' \dontrun{ #' tmpdir <- tempdir() #' usethis::create_package(path = tmpdir) #' use_bugreports( diff --git a/R/73_badge_to_readme.R b/R/73_badge_to_readme.R index ffdcf72..f1c17a9 100644 --- a/R/73_badge_to_readme.R +++ b/R/73_badge_to_readme.R @@ -18,12 +18,10 @@ #' #' @examples #' \dontrun{ -#' try({ -#' tmpdir <- tempdir() -#' usethis::create_package(path = tmpdir, open = FALSE) -#' usethis::proj_set(path = tmpdir) -#' badger::badge_last_commit(alt = "last-commit") |> badge_to_readme(path = tmpdir) -#' }) +#' tmpdir <- tempdir() +#' usethis::create_package(path = tmpdir, open = FALSE) +#' usethis::proj_set(path = tmpdir) +#' badger::badge_last_commit(alt = "last-commit") |> badge_to_readme(path = tmpdir) #' } badge_to_readme <- function(badge, path = NULL, ...) { rlang::check_dots_empty() diff --git a/_pkgdown.yml b/_pkgdown.yml index 064b0d1..8412d1b 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -87,6 +87,7 @@ reference: - use_r_v4.1.0 - use_url - use_vendor + - use_workflow_rust_compatible_check - use_workflow_test_branch - use_workflow_version_update - use_zzz diff --git a/inst/actions/rust_compatible_check/R-CMD-Check.yaml b/inst/actions/rust_compatible_check/R-CMD-Check.yaml new file mode 100644 index 0000000..8b8277c --- /dev/null +++ b/inst/actions/rust_compatible_check/R-CMD-Check.yaml @@ -0,0 +1,53 @@ +on: + push: + branches: + - main + pull_request: + branches: + - main + +name: R-CMD-check + +jobs: + R-CMD-check: + runs-on: ${{ matrix.config.os }} + + name: ${{ matrix.config.os }} (R-${{ matrix.config.r }} rust-${{ matrix.config.rust-version }}) + + strategy: + fail-fast: false + matrix: + config: + - { + os: windows-latest, + r: "release", + rust-version: "stable-msvc", + rust-target: "x86_64-pc-windows-gnu", + } + - { os: macOS-latest, r: "release", rust-version: "stable" } + - { os: ubuntu-latest, r: "release", rust-version: "stable" } + - { os: ubuntu-latest, r: "devel", rust-version: "stable" } + + env: + R_REMOTES_NO_ERRORS_FROM_WARNINGS: true + + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.config.rust-version }} + targets: ${{ matrix.config.rust-target }} + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: ${{ matrix.config.r }} + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck + + - uses: r-lib/actions/check-r-package@v2 diff --git a/man/badge_to_readme.Rd b/man/badge_to_readme.Rd index 543a0d7..78143c8 100644 --- a/man/badge_to_readme.Rd +++ b/man/badge_to_readme.Rd @@ -27,11 +27,9 @@ If both files exist, only \code{README.Rmd} is updated. } \examples{ \dontrun{ -try({ - tmpdir <- tempdir() - usethis::create_package(path = tmpdir, open = FALSE) - usethis::proj_set(path = tmpdir) - badger::badge_last_commit(alt = "last-commit") |> badge_to_readme(path = tmpdir) -}) +tmpdir <- tempdir() +usethis::create_package(path = tmpdir, open = FALSE) +usethis::proj_set(path = tmpdir) +badger::badge_last_commit(alt = "last-commit") |> badge_to_readme(path = tmpdir) } } diff --git a/man/convert_int_literals.Rd b/man/convert_int_literals.Rd index e1d76b3..76b537e 100644 --- a/man/convert_int_literals.Rd +++ b/man/convert_int_literals.Rd @@ -76,7 +76,7 @@ and it is \strong{not}: } } \examples{ -\donttest{ +\dontrun{ # --- Single file --- temp <- tempfile(fileext = ".R") writeLines("tmp <- seq_len(10)", temp) diff --git a/man/convert_pipe.Rd b/man/convert_pipe.Rd index 2819afe..41d2cdf 100644 --- a/man/convert_pipe.Rd +++ b/man/convert_pipe.Rd @@ -79,7 +79,7 @@ unchanged. } } \examples{ -\donttest{ +\dontrun{ # --- Single file --- temp <- tempfile(fileext = ".R") writeLines("mtcars |> dplyr::filter(cyl > 4)", temp) diff --git a/man/optimize_rmd_yaml.Rd b/man/optimize_rmd_yaml.Rd index e4b5101..ad4d55d 100644 --- a/man/optimize_rmd_yaml.Rd +++ b/man/optimize_rmd_yaml.Rd @@ -24,7 +24,7 @@ RStudio editor is used.} \item{readme_format}{Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html".} -\item{date}{"auto" -> 2026-10-25; "desc" -> DESCRIPTION Date field; +\item{date}{"auto" -> 2026-10-28; "desc" -> DESCRIPTION Date field; "none" -> do not add a date.} \item{extra}{Named list of extra YAML fields added to the file. It is merged diff --git a/man/package_optimize_rmd_yaml.Rd b/man/package_optimize_rmd_yaml.Rd index 9cbe94a..817e07f 100644 --- a/man/package_optimize_rmd_yaml.Rd +++ b/man/package_optimize_rmd_yaml.Rd @@ -25,7 +25,7 @@ package_optimize_rmd_yaml( \item{readme_format}{Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html".} -\item{date}{"auto" -> 2026-10-25; "desc" -> DESCRIPTION Date field; +\item{date}{"auto" -> 2026-10-28; "desc" -> DESCRIPTION Date field; "none" -> do not add a date.} \item{extra}{Named list of extra YAML fields added to the file. It is merged diff --git a/man/use_bugreports.Rd b/man/use_bugreports.Rd index 4cba697..c6e1133 100644 --- a/man/use_bugreports.Rd +++ b/man/use_bugreports.Rd @@ -30,7 +30,7 @@ the GitHub issues page URL is derived from the configured \code{git} remote } } \examples{ -\donttest{ +\dontrun{ tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_bugreports( diff --git a/man/use_r_v4.1.0.Rd b/man/use_r_v4.1.0.Rd index 2ceded6..a369ea6 100644 --- a/man/use_r_v4.1.0.Rd +++ b/man/use_r_v4.1.0.Rd @@ -26,7 +26,7 @@ This sets a minimum R version requirement for your package. Then you can use } } \examples{ -\donttest{ +\dontrun{ tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_r_v4.1.0(path = tmpdir) diff --git a/man/use_url.Rd b/man/use_url.Rd index a770611..1a52ba4 100644 --- a/man/use_url.Rd +++ b/man/use_url.Rd @@ -34,7 +34,7 @@ URL (a trailing \code{.git} suffix is removed). } } \examples{ -\donttest{ +\dontrun{ tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_url( diff --git a/man/use_workflow_rust_compatible_check.Rd b/man/use_workflow_rust_compatible_check.Rd new file mode 100644 index 0000000..5955e9a --- /dev/null +++ b/man/use_workflow_rust_compatible_check.Rd @@ -0,0 +1,56 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/42C_use_workflow_rust_compatible_check.R +\name{use_workflow_rust_compatible_check} +\alias{use_workflow_rust_compatible_check} +\title{Create a Rust-compatible R-CMD-check Workflow} +\usage{ +use_workflow_rust_compatible_check(path = NULL, overwrite = FALSE) +} +\arguments{ +\item{path}{Character. Path to the package root directory. If \code{NULL} +(the default), uses the current working directory.} + +\item{overwrite}{Logical. If \code{TRUE}, overwrite an existing workflow file. +Defaults to \code{FALSE}.} +} +\value{ +Invisibly returns the path to the created workflow file. +} +\description{ +Copies the built-in \code{R-CMD-Check.yaml} workflow template to the target +package's \verb{.github/workflows/} directory, so that \verb{R CMD check} runs on +GitHub Actions with a toolchain that can download, compile and link Rust +crates (packages built on \code{extendr}/\code{rextendr}). +} +\section{Why not the \code{usethis} workflow}{ + +\code{usethis::use_github_action("check-standard")} only sets up R and then calls +\verb{R CMD check} on a matrix of operating systems. For packages with Rust code +this is not enough: +\itemize{ +\item No Rust toolchain is installed, so the runner default is used. On Windows +that default is an \strong{MSVC} toolchain, while R and Rtools are \strong{GNU} +based, so the static library produced by \code{cargo} cannot be linked, and the +resulting build noise (\code{cargo} warnings, linker messages) makes +\verb{R CMD check} report a WARNING. +} + +The template used here follows the official \code{extendr} CI: +\itemize{ +\item \code{dtolnay/rust-toolchain} installs the requested toolchain, and on Windows +additionally the \code{x86_64-pc-windows-gnu} target that Rtools can link. +\item The R matrix covers Windows, macOS, Ubuntu release and Ubuntu devel, with +\code{fail-fast: false} so one broken platform does not hide the others. +\item \code{R_REMOTES_NO_ERRORS_FROM_WARNINGS} keeps \code{remotes}/\code{pak} download noise +from turning into check failures. +} +} + +\examples{ +\dontrun{ +temp <- tempdir() +usethis::create_package(temp) +use_workflow_rust_compatible_check(temp) +use_workflow_rust_compatible_check(temp, overwrite = TRUE) +} +} diff --git a/skills/rpkgkit/SKILL.md b/skills/rpkgkit/SKILL.md index 3c14f3a..2d6b758 100644 --- a/skills/rpkgkit/SKILL.md +++ b/skills/rpkgkit/SKILL.md @@ -1,6 +1,6 @@ --- name: rpkgkit -description: Use rpkgkit functions to create and maintain R packages when the task involves qualifying package calls with pkg::, detecting CRAN-unsafe print()/cat(), lost glue braces or unmatched # nocov start / # nocov end markers, modernizing R syntax (base/magrittr pipes, integer L suffix, non-ASCII literals, \\( lambdas, knitr chunk headers), editing or displaying NEWS.md, creating r-lib standalone files, configuring DESCRIPTION fields, .Rbuildignore/.clangd/zzz.R, vendoring upstream code, or generating multilingual README translations and badges. +description: Use rpkgkit functions to create and maintain R packages when the task involves qualifying package calls with pkg::, detecting CRAN-unsafe print()/cat(), lost glue braces or unmatched # nocov start / # nocov end markers, modernizing R syntax (base/magrittr pipes, integer L suffix, non-ASCII literals, \\( lambdas, knitr chunk headers), editing or displaying NEWS.md, creating r-lib standalone files, configuring DESCRIPTION fields, .Rbuildignore/.clangd/zzz.R, vendoring upstream code, generating GitHub Actions workflows (R-CMD-check including Rust/extendr builds, version bump, branch sync), or generating multilingual README translations and badges. --- # rpkgkit @@ -109,9 +109,21 @@ rpkgkit::use_clangd() # .clangd for Rcpp projects rpkgkit::add_global_rbuildignore() # curated .Rbuildignore patterns rpkgkit::add_global_gitgnore() rpkgkit::use_vendor("pkg") # vendor upstream source into inst/vendor/ +rpkgkit::use_workflow_version_update() # version bump workflow + local action +rpkgkit::use_workflow_rust_compatible_check() # R-CMD-check that builds Rust code +rpkgkit::use_workflow_test_branch() # sync main -> test after check passes rpkgkit::check_pkgdown_reference() # every export present in _pkgdown.yml ``` +The three `use_workflow_*()` functions copy bundled templates from `inst/actions/` +into `.github/`, create the directories they need, abort instead of overwriting +unless `overwrite = TRUE`, and return the written path invisibly. Use +`use_workflow_rust_compatible_check()` rather than +`usethis::use_github_action("check-standard")` for `extendr`/`rextendr` +packages: it installs a Rust toolchain and the `x86_64-pc-windows-gnu` target, +without which the MSVC default cannot link against Rtools and the check ends in a +WARNING. + ## Workflow: README, badges, Rmd ```r diff --git a/skills/rpkgkit/references/function-reference.md b/skills/rpkgkit/references/function-reference.md index 76cdd51..dc5f90c 100644 --- a/skills/rpkgkit/references/function-reference.md +++ b/skills/rpkgkit/references/function-reference.md @@ -78,6 +78,7 @@ These share an Rd page with their single-file counterpart (`@rdname`/`@describeI | `use_vendor(pkg, ..., branch = "main", path = NULL)` | `43_use_vendor.R` | Vendors upstream source into `inst/vendor/`, writes provenance and license, records vendor version and imports. | | `use_workflow_version_update(path = NULL, overwrite = FALSE, color = "blue", ...)` | `42_use_workflow_version_update.R` | Generates the version bump GitHub Actions workflow. | | `use_workflow_test_branch(path = NULL, overwrite = FALSE)` | `42B_use_workflow_test_branch.R` | Generates the `main` → `test` sync workflow. | +| `use_workflow_rust_compatible_check(path = NULL, overwrite = FALSE)` | `42C_use_workflow_rust_compatible_check.R` | Copies `inst/actions/rust_compatible_check/R-CMD-Check.yaml` to `.github/workflows/R-CMD-check.yaml`; installs Rust via `dtolnay/rust-toolchain` plus the `x86_64-pc-windows-gnu` target on Windows, because the MSVC default cannot link with Rtools and makes the check report a WARNING. Use instead of `usethis::use_github_action("check-standard")` for `extendr` packages. | | `check_pkgdown_reference(pkg = ".")` | `40_check_pkgdown_reference.R` | Verifies every export appears in `_pkgdown.yml`. Argument is `pkg`. | | `check_sysdeps(deps = NULL, manager = NULL, verbose = TRUE)` | `92_check_sysdeps.R` | Reports system dependencies and install commands (apt/dnf/brew). | | `get_positron_version(long = FALSE)` | `91_get_positron_version.R` | Returns the Positron version, `NA_character_` outside Positron. | diff --git a/tests/testthat/test-use_workflow_rust_compatible_check.R b/tests/testthat/test-use_workflow_rust_compatible_check.R new file mode 100644 index 0000000..9a90da3 --- /dev/null +++ b/tests/testthat/test-use_workflow_rust_compatible_check.R @@ -0,0 +1,140 @@ +test_that("aborts when path is not a package root", { + tmp <- withr::local_tempdir(pattern = "not_pkg") + + expect_error( + use_workflow_rust_compatible_check(path = tmp), + "not an R package root" + ) +}) + +test_that("aborts when workflow file already exists and overwrite = FALSE", { + tmp <- withr::local_tempdir(pattern = "pkg") + file.create(file.path(tmp, "DESCRIPTION")) + + workflow_file <- file.path( + tmp, + ".github", + "workflows", + "R-CMD-check.yaml" + ) + dir.create(dirname(workflow_file), recursive = TRUE) + file.create(workflow_file) + + expect_error( + use_workflow_rust_compatible_check(path = tmp, overwrite = FALSE), + "already exists" + ) +}) + +test_that("creates workflow directory and copies the Rust template", { + tmp <- withr::local_tempdir(pattern = "pkg") + file.create(file.path(tmp, "DESCRIPTION")) + + expect_message( + result <- use_workflow_rust_compatible_check(path = tmp), + "Created workflow" + ) + + expected_path <- file.path( + tmp, + ".github", + "workflows", + "R-CMD-check.yaml" + ) + expect_equal(result, expected_path) + expect_true(file.exists(expected_path)) + + lines <- readLines(expected_path, warn = FALSE) + expect_match(lines[1L], "on:", fixed = TRUE) + expect_true(any(grepl("name: R-CMD-check", lines, fixed = TRUE))) + expect_true(any(grepl( + "uses: dtolnay/rust-toolchain@master", + lines, + fixed = TRUE + ))) + expect_true(any(grepl( + "x86_64-pc-windows-gnu", + lines, + fixed = TRUE + ))) + expect_true(any(grepl( + "r-lib/actions/check-r-package@v2", + lines, + fixed = TRUE + ))) +}) + +test_that("overwrite = TRUE replaces existing workflow file", { + tmp <- withr::local_tempdir(pattern = "pkg") + file.create(file.path(tmp, "DESCRIPTION")) + + workflow_file <- file.path( + tmp, + ".github", + "workflows", + "R-CMD-check.yaml" + ) + dir.create(dirname(workflow_file), recursive = TRUE) + writeLines(c("# old content"), workflow_file) + + suppressMessages( + result <- use_workflow_rust_compatible_check(path = tmp, overwrite = TRUE) + ) + + lines <- readLines(workflow_file, warn = FALSE) + expect_false(identical(lines, "# old content")) + expect_true(any(grepl( + "uses: dtolnay/rust-toolchain@master", + lines, + fixed = TRUE + ))) + expect_equal(result, workflow_file) +}) + +test_that("returns invisible file path", { + tmp <- withr::local_tempdir(pattern = "pkg") + file.create(file.path(tmp, "DESCRIPTION")) + + result <- withVisible( + suppressMessages(use_workflow_rust_compatible_check(path = tmp)) + ) + + expect_equal( + result$value, + file.path(tmp, ".github", "workflows", "R-CMD-check.yaml") + ) + expect_false(result$visible) +}) + +test_that("copied file is identical to the bundled template", { + tmp <- withr::local_tempdir(pattern = "pkg") + file.create(file.path(tmp, "DESCRIPTION")) + + suppressMessages(use_workflow_rust_compatible_check(path = tmp)) + + template <- system.file( + "actions", + "rust_compatible_check", + "R-CMD-Check.yaml", + package = "rpkgkit" + ) + expect_equal( + readLines(file.path(tmp, ".github", "workflows", "R-CMD-check.yaml")), + readLines(template) + ) +}) + +test_that("path = NULL falls back to the current working directory", { + tmp <- withr::local_tempdir(pattern = "pkg") + file.create(file.path(tmp, "DESCRIPTION")) + withr::local_dir(tmp) + + suppressMessages(use_workflow_rust_compatible_check()) + + expect_true(file.exists(file.path( + tmp, + ".github", + "workflows", + "R-CMD-check.yaml" + ))) +}) diff --git a/vignettes/pkg_maintain.Rmd b/vignettes/pkg_maintain.Rmd index f733122..ffdf635 100644 --- a/vignettes/pkg_maintain.Rmd +++ b/vignettes/pkg_maintain.Rmd @@ -193,6 +193,65 @@ add_global_rbuildignore(path = dir) add_global_gitgnore(pkg = dir) ``` +# GitHub Actions workflows + +Each `use_workflow_*()` function copies a workflow template bundled in +`inst/actions/` into the `.github/` directory of the target package. All of them +create the directories they need, abort instead of overwriting unless +`overwrite = TRUE`, and return the written path invisibly. + +## Bump the version from commit messages + +`use_workflow_version_update()` installs `version_update.yml` together with the +`version-bumper` composite action. The version is bumped from the commit message +(`major`/`breaking`, `feat`/`minor`, `patch`/`fix`), or explicitly through +`workflow_dispatch`. A bump is skipped when the new version would exceed the +highest version documented in `NEWS.md`, and the `version` field of +`src/rust/Cargo.toml` is kept in sync when the package ships Rust code. + +```{r} +#| label = "use_workflow_version_update" +use_workflow_version_update(path = dir) +``` + +## Run `R CMD check` on packages with Rust code + +`use_workflow_rust_compatible_check()` installs a `R-CMD-check.yaml` that can +download, compile and link Rust crates, which is what packages built on +`extendr`/`rextendr` need. It replaces +`usethis::use_github_action("check-standard")` for such packages. + +```{r} +#| label = "use_workflow_rust_compatible_check" +use_workflow_rust_compatible_check(path = dir) +``` + +The difference lies in the toolchain. The `usethis` workflow only sets up R and +leaves the runner default in place; on Windows that default is an MSVC +toolchain, while R and Rtools are GNU based, so the static library produced by +`cargo` cannot be linked and the resulting build noise makes `R CMD check` +report a WARNING. The template used here follows the official `extendr` CI: + +* `dtolnay/rust-toolchain` installs the requested toolchain and, on Windows, + additionally the `x86_64-pc-windows-gnu` target that Rtools can link. +* The matrix covers Windows, macOS, Ubuntu release and Ubuntu devel with + `fail-fast: false`, so one broken platform does not hide the others. +* `R_REMOTES_NO_ERRORS_FROM_WARNINGS` keeps download noise from `remotes` and + `pak` from surfacing as a check failure. + +## Sync `main` to a `test` branch + +`use_workflow_test_branch()` adds a workflow that runs after `R-CMD-check.yaml` +succeeds on `main`/`master` and force-pushes the checked commit to `test`. The +sync is skipped when `test` holds commits that are not reachable from `main`, so +unmerged work is never overwritten. Push experimental changes to `test` and each +push to `main` resets it again. + +```{r} +#| label = "use_workflow_test_branch" +use_workflow_test_branch(path = dir) +``` + # Check system dependencies Some packages need system development libraries (graphics and font libraries, From 34be48e34e7a8a7496436b5a3503929129c4285d Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Sat, 31 Oct 2026 00:11:46 -0400 Subject: [PATCH 05/35] patch update: * Added `use_workflow_rust_compatible_check()` to install a `.github/workflows/R-CMD-check.yaml` that can build packages shipping Rust code. It copies the bundled `R-CMD-Check.yaml` template to the target package, creating `.github/workflows/` when needed. Unlike the workflow from `usethis::use_github_action("check-standard")`, which only sets up R and leaves the runner's default toolchain in place, the template installs Rust through `dtolnay/rust-toolchain` and, on Windows, additionally the `x86_64-pc-windows-gnu` target: the Windows runner defaults to an MSVC toolchain while R and Rtools are GNU based, so the static library produced by `cargo` cannot be linked and the build noise makes `R CMD check` report a WARNING. The job matrix covers Windows, macOS, Ubuntu release and Ubuntu devel with `fail-fast: false`, and sets `R_REMOTES_NO_ERRORS_FROM_WARNINGS` so that download noise from `remotes`/`pak` does not surface as a check failure. The function aborts when the path is not a package root, when the template is missing, or when the workflow file already exists and `overwrite = FALSE`, and it returns the created path invisibly. The template follows the official `extendr` CI. * `make_func_arg_explicit()` now accounts for the argument a pipe passes into its right-hand side call. The piped-in value already fills the function's first formal, so the arguments written in the call are matched one formal later: `x %>% stringr::str_remove("Merc")` becomes `x %>% stringr::str_remove(pattern = "Merc")`, where it previously claimed `string` and pushed `Merc` onto `pattern`. Placeholders are honoured too: a `.` anywhere in a magrittr right-hand side (`%>%`, `%<>%`, `%T>%`) cancels the leading injection, because the piped value is substituted at `.` instead of being inserted first, and a `_` in a native pipe (`|>`) makes the value fill the formal it is attached to, so `x |> lm(y ~ z, data = _)` becomes `x |> lm(formula = y ~ z, data = _)`. Symbols that merely start with a dot, such as the `.data` pronoun and `..1`, are not mistaken for the placeholder. A comment between a pipe and its right-hand side no longer hides the call from the transformation. --- DESCRIPTION | 3 +- NEWS.md | 17 ++ R/10_optimize_rmd_yaml.R | 2 +- R/19_make_func_arg_explicit.R | 143 ++++++++++- man/dot-mfae_has_placeholder.Rd | 14 ++ man/dot-mfae_parse_data.Rd | 3 +- man/dot-mfae_pipe_placeholder.Rd | 12 + man/dot-mfae_pipe_rhs.Rd | 17 ++ man/dot-mfae_pipe_shift.Rd | 16 ++ man/dot-mfae_pipes.Rd | 12 + man/dot-mfae_row_of.Rd | 13 + man/make_func_arg_explicit.Rd | 20 ++ man/optimize_rmd_yaml.Rd | 2 +- man/package_optimize_rmd_yaml.Rd | 2 +- tests/testthat/test-make_func_arg_explicit.R | 248 ++++++++++++++++++- vignettes/news.Rmd | 3 +- vignettes/pkg_maintain.Rmd | 19 +- 17 files changed, 521 insertions(+), 25 deletions(-) create mode 100644 man/dot-mfae_has_placeholder.Rd create mode 100644 man/dot-mfae_pipe_placeholder.Rd create mode 100644 man/dot-mfae_pipe_rhs.Rd create mode 100644 man/dot-mfae_pipe_shift.Rd create mode 100644 man/dot-mfae_pipes.Rd create mode 100644 man/dot-mfae_row_of.Rd diff --git a/DESCRIPTION b/DESCRIPTION index 1425d4f..91965f4 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -18,8 +18,7 @@ Description: Utilities for R package development including NEWS.md 'RStudio'. Includes helper functions for renaming functions and detecting common coding errors. License: MIT + file LICENSE -URL: https://github.com/WangLabCSU/rpkgkit, - https://wanglabcsu.github.io/rpkgkit/ +URL: /tmp/RtmpoUp5qA BugReports: https://github.com/WangLabCSU/rpkgkit/issues Depends: R (>= 4.2) diff --git a/NEWS.md b/NEWS.md index 8046a82..2e84cbf 100644 --- a/NEWS.md +++ b/NEWS.md @@ -20,6 +20,23 @@ it returns the created path invisibly. The template follows the official `extendr` CI. +## BUG FIXES + +* `make_func_arg_explicit()` now accounts for the argument a pipe passes into + its right-hand side call. The piped-in value already fills the function's + first formal, so the arguments written in the call are matched one formal + later: `x %>% stringr::str_remove("Merc")` becomes + `x %>% stringr::str_remove(pattern = "Merc")`, where it previously claimed + `string` and pushed `Merc` onto `pattern`. Placeholders are honoured too: a + `.` anywhere in a magrittr right-hand side (`%>%`, `%<>%`, `%T>%`) cancels + the leading injection, because the piped value is substituted at `.` instead + of being inserted first, and a `_` in a native pipe (`|>`) makes the value + fill the formal it is attached to, so `x |> lm(y ~ z, data = _)` becomes + `x |> lm(formula = y ~ z, data = _)`. Symbols that merely start with a dot, + such as the `.data` pronoun and `..1`, are not mistaken for the placeholder. + A comment between a pipe and its right-hand side no longer hides the call + from the transformation. + # rpkgkit 0.1.21 (2026-10-19) ## NEW FEATURES diff --git a/R/10_optimize_rmd_yaml.R b/R/10_optimize_rmd_yaml.R index aaf9f9a..6e4dcb8 100644 --- a/R/10_optimize_rmd_yaml.R +++ b/R/10_optimize_rmd_yaml.R @@ -23,7 +23,7 @@ #' "readme" or "vignette". #' @param readme_format Format used when a README has the default output: #' "gfm" (md_document + variant: gfm), "github_document" or "html". -#' @param date "auto" -> `r Sys.Date()`; "desc" -> DESCRIPTION Date field; +#' @param date "auto" -> `Sys.Date()`; "desc" -> DESCRIPTION Date field; #' "none" -> do not add a date. #' @param extra Named list of extra YAML fields added to the file. It is merged #' onto the built-in defaults with [utils::modifyList()] (nested lists are diff --git a/R/19_make_func_arg_explicit.R b/R/19_make_func_arg_explicit.R index 3c6d5f9..22da8db 100644 --- a/R/19_make_func_arg_explicit.R +++ b/R/19_make_func_arg_explicit.R @@ -19,6 +19,24 @@ #' \code{<<-}), and special syntax (\code{if}, \code{for}, \code{while}, #' \code{repeat}, \code{\{}, \code{(}, \code{function}) are not transformed. #' +#' @section Pipes and placeholders: +#' The right-hand side of a pipe receives an extra argument from its +#' left-hand side, so that argument is counted during positional matching: +#' \code{x \%>\% str_remove("a")} becomes +#' \code{x \%>\% str_remove(pattern = "a")}, because the piped-in data already +#' fills the first formal (\code{string}). +#' +#' Placeholders are honoured. When a native pipe (\code{|>}) uses the +#' \code{_} placeholder, the piped value fills the formal named next to +#' \code{_}, so no leading argument is pre-claimed and the remaining +#' positional arguments are still matched: +#' \code{x |> lm(y ~ z, data = _)} becomes +#' \code{x |> lm(formula = y ~ z, data = _)}. When a magrittr pipe +#' (\code{\%>\%}, \code{\%<>\%}, \code{\%T>\%}) contains \code{.} anywhere in +#' its right-hand side, the piped value is substituted at \code{.} instead of +#' being inserted as the first argument, and again no formal is pre-claimed: +#' \code{x \%>\% f(., y)} becomes \code{x \%>\% f(a = ., b = y)}. +#' #' @section Single-file operation: #' Operates on one R file. When \code{path} is \code{NULL} and RStudio is #' available, the currently active document is used automatically. @@ -138,8 +156,19 @@ make_func_arg_explicit <- function(path = NULL, skip_functions = NULL, ...) { next } + # A call on the right-hand side of a pipe silently receives the piped-in + # value as an extra leading argument. Unless a placeholder is present, it + # claims the function's first formal, so positional matching has to start + # one formal later than the written arguments suggest. + shift <- .mfae_pipe_shift(pd, id) arg_names <- vapply(slots, function(s) s$name, character(1L)) - wanted <- .mfae_assign_arg_names(arg_names, names(fmls)) + wanted <- .mfae_assign_arg_names( + arg_nms = c(rep("", shift), arg_names), + fml_nms = names(fmls) + ) + if (shift > 0L) { + wanted <- wanted[-seq_len(shift)] + } for (i in seq_along(slots)) { if (nzchar(arg_names[[i]]) || !nzchar(wanted[[i]])) { @@ -169,7 +198,8 @@ make_func_arg_explicit <- function(path = NULL, skip_functions = NULL, ...) { #' planning a single large file quadratic. #' #' Rows are reordered into source order first, because that order is what maps -#' a call's child tokens onto its arguments. +#' a call's child tokens onto its arguments. The reverse lookup (id to row) sits +#' in \code{pd$row_of}, an integer vector indexed by node id. #' @keywords internal .mfae_parse_data <- function(parse_data) { parse_data <- parse_data[ @@ -195,6 +225,13 @@ make_func_arg_explicit <- function(path = NULL, skip_functions = NULL, ...) { hash = TRUE, parent = emptyenv() ) + # Node ids are assigned sequentially, so an integer lookup vector maps an id + # to its row without hashing a name. + pd$row_of <- integer(max(pd$id)) + pd$row_of[pd$id] <- seq_along(pd$id) + pipe <- .mfae_pipe_rhs(pd) + pd$pipe_rhs <- pipe$rhs + pd$pipe_op <- pipe$op pd } @@ -210,6 +247,20 @@ make_func_arg_explicit <- function(path = NULL, skip_functions = NULL, ...) { } +#' Row of a node id +#' +#' Reverse of \code{pd$id}; \code{NA} when the id is not in \code{pd} (the root +#' node has parent \code{0}, which is never present). +#' @keywords internal +.mfae_row_of <- function(pd, id) { + if (length(id) != 1L || is.na(id) || id < 1L || id > length(pd$row_of)) { + return(NA_integer_) + } + row <- pd$row_of[[id]] + if (row == 0L) NA_integer_ else row +} + + #' Resolve the callee of a call from its head parse-data row #' #' Returns \code{NULL} when the head is not a plain function name (for example @@ -326,6 +377,94 @@ make_func_arg_explicit <- function(path = NULL, skip_functions = NULL, ...) { } +#' Pipe operators that pass their left-hand side into the right-hand side call +#' @keywords internal +.mfae_pipes <- c("%>%", "%<>%", "%T>%", "|>") + +#' Placeholder each pipe flavour understands +#' +#' The native pipe uses \code{_}, magrittr uses \code{.}. +#' @keywords internal +.mfae_pipe_placeholder <- function(op) { + if (identical(op, "|>")) "_" else "." +} + + +#' How many formals a pipe claims before the written arguments +#' +#' Returns \code{1L} when the call is the right-hand side of a pipe that +#' injects its left-hand side as the first argument, and \code{0L} otherwise. +#' A placeholder anywhere in the call cancels the leading injection: the piped +#' value is substituted at the placeholder instead, so the written arguments +#' keep their natural positions. +#' @keywords internal +.mfae_pipe_shift <- function(pd, id) { + row <- .mfae_row_of(pd, id) + if (is.na(row) || !pd$pipe_rhs[[row]]) { + return(0L) + } + op <- pd$pipe_op[[row]] + if (.mfae_has_placeholder(pd, id, .mfae_pipe_placeholder(op))) { + return(0L) + } + 1L +} + + +#' Locate the right-hand side of every pipe expression +#' +#' Returns a logical vector \code{rhs} that is \code{TRUE} at the row of every +#' expression a pipe feeds, plus \code{op}, the pipe operator used there. The +#' parse tree of \code{a \%>\% b()} nests that expression as the last child of +#' the pipe expression, so it is the last \code{expr} child after the pipe +#' token. Comments are children of the pipe expression too, but they are not +#' \code{expr} nodes and are skipped by the same filter. +#' @keywords internal +.mfae_pipe_rhs <- function(pd) { + rhs <- logical(length(pd$token)) + op <- character(length(pd$token)) + op_rows <- which( + pd$token %in% c("SPECIAL", "PIPE") & pd$text %in% .mfae_pipes + ) + for (op_row in op_rows) { + kids <- .mfae_children(pd, pd$parent[[op_row]]) + fed <- kids[pd$token[kids] == "expr" & kids > op_row] + if (length(fed) == 0L) { + next + } + rhs[[fed[[length(fed)]]]] <- TRUE + op[[fed[[length(fed)]]]] <- pd$text[[op_row]] + } + list(rhs = rhs, op = op) +} + + +#' Does a placeholder occur anywhere inside this expression? +#' +#' Magrittr substitutes its left-hand side at every \code{.} in the whole +#' right-hand side call, including nested ones, so the search is recursive. +#' \code{.data} and \code{..1} are different symbols and do not match. +#' @keywords internal +.mfae_has_placeholder <- function(pd, id, placeholder) { + kids <- .mfae_children(pd, id) + if (length(kids) == 0L) { + return(FALSE) + } + tokens <- pd$token[kids] + if ( + any(tokens %in% c("SYMBOL", "PLACEHOLDER") & pd$text[kids] == placeholder) + ) { + return(TRUE) + } + for (kid in pd$id[kids[tokens == "expr"]]) { + if (.mfae_has_placeholder(pd, kid, placeholder)) { + return(TRUE) + } + } + FALSE +} + + #' Apply planned insertions to the source lines #' #' Insertions on the same line are applied right to left so that earlier diff --git a/man/dot-mfae_has_placeholder.Rd b/man/dot-mfae_has_placeholder.Rd new file mode 100644 index 0000000..8fa0b0e --- /dev/null +++ b/man/dot-mfae_has_placeholder.Rd @@ -0,0 +1,14 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/19_make_func_arg_explicit.R +\name{.mfae_has_placeholder} +\alias{.mfae_has_placeholder} +\title{Does a placeholder occur anywhere inside this expression?} +\usage{ +.mfae_has_placeholder(pd, id, placeholder) +} +\description{ +Magrittr substitutes its left-hand side at every \code{.} in the whole +right-hand side call, including nested ones, so the search is recursive. +\code{.data} and \code{..1} are different symbols and do not match. +} +\keyword{internal} diff --git a/man/dot-mfae_parse_data.Rd b/man/dot-mfae_parse_data.Rd index 8977228..0647f12 100644 --- a/man/dot-mfae_parse_data.Rd +++ b/man/dot-mfae_parse_data.Rd @@ -16,6 +16,7 @@ planning a single large file quadratic. } \details{ Rows are reordered into source order first, because that order is what maps -a call's child tokens onto its arguments. +a call's child tokens onto its arguments. The reverse lookup (id to row) sits +in \code{pd$row_of}, an integer vector indexed by node id. } \keyword{internal} diff --git a/man/dot-mfae_pipe_placeholder.Rd b/man/dot-mfae_pipe_placeholder.Rd new file mode 100644 index 0000000..180833c --- /dev/null +++ b/man/dot-mfae_pipe_placeholder.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/19_make_func_arg_explicit.R +\name{.mfae_pipe_placeholder} +\alias{.mfae_pipe_placeholder} +\title{Placeholder each pipe flavour understands} +\usage{ +.mfae_pipe_placeholder(op) +} +\description{ +The native pipe uses \code{_}, magrittr uses \code{.}. +} +\keyword{internal} diff --git a/man/dot-mfae_pipe_rhs.Rd b/man/dot-mfae_pipe_rhs.Rd new file mode 100644 index 0000000..319465f --- /dev/null +++ b/man/dot-mfae_pipe_rhs.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/19_make_func_arg_explicit.R +\name{.mfae_pipe_rhs} +\alias{.mfae_pipe_rhs} +\title{Locate the right-hand side of every pipe expression} +\usage{ +.mfae_pipe_rhs(pd) +} +\description{ +Returns a logical vector \code{rhs} that is \code{TRUE} at the row of every +expression a pipe feeds, plus \code{op}, the pipe operator used there. The +parse tree of \code{a \%>\% b()} nests that expression as the last child of +the pipe expression, so it is the last \code{expr} child after the pipe +token. Comments are children of the pipe expression too, but they are not +\code{expr} nodes and are skipped by the same filter. +} +\keyword{internal} diff --git a/man/dot-mfae_pipe_shift.Rd b/man/dot-mfae_pipe_shift.Rd new file mode 100644 index 0000000..88295c8 --- /dev/null +++ b/man/dot-mfae_pipe_shift.Rd @@ -0,0 +1,16 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/19_make_func_arg_explicit.R +\name{.mfae_pipe_shift} +\alias{.mfae_pipe_shift} +\title{How many formals a pipe claims before the written arguments} +\usage{ +.mfae_pipe_shift(pd, id) +} +\description{ +Returns \code{1L} when the call is the right-hand side of a pipe that +injects its left-hand side as the first argument, and \code{0L} otherwise. +A placeholder anywhere in the call cancels the leading injection: the piped +value is substituted at the placeholder instead, so the written arguments +keep their natural positions. +} +\keyword{internal} diff --git a/man/dot-mfae_pipes.Rd b/man/dot-mfae_pipes.Rd new file mode 100644 index 0000000..ba493d1 --- /dev/null +++ b/man/dot-mfae_pipes.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/19_make_func_arg_explicit.R +\name{.mfae_pipes} +\alias{.mfae_pipes} +\title{Pipe operators that pass their left-hand side into the right-hand side call} +\usage{ +.mfae_pipes +} +\description{ +Pipe operators that pass their left-hand side into the right-hand side call +} +\keyword{internal} diff --git a/man/dot-mfae_row_of.Rd b/man/dot-mfae_row_of.Rd new file mode 100644 index 0000000..d91f7c2 --- /dev/null +++ b/man/dot-mfae_row_of.Rd @@ -0,0 +1,13 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/19_make_func_arg_explicit.R +\name{.mfae_row_of} +\alias{.mfae_row_of} +\title{Row of a node id} +\usage{ +.mfae_row_of(pd, id) +} +\description{ +Reverse of \code{pd$id}; \code{NA} when the id is not in \code{pd} (the root +node has parent \code{0}, which is never present). +} +\keyword{internal} diff --git a/man/make_func_arg_explicit.Rd b/man/make_func_arg_explicit.Rd index 4e479dd..43c5444 100644 --- a/man/make_func_arg_explicit.Rd +++ b/man/make_func_arg_explicit.Rd @@ -52,6 +52,26 @@ Operators (\code{+}, \code{-}, \code{*}, \code{/}, etc.), subset operators package's \code{R/} directory, making function arguments explicit. }} +\section{Pipes and placeholders}{ + +The right-hand side of a pipe receives an extra argument from its +left-hand side, so that argument is counted during positional matching: +\code{x \%>\% str_remove("a")} becomes +\code{x \%>\% str_remove(pattern = "a")}, because the piped-in data already +fills the first formal (\code{string}). + +Placeholders are honoured. When a native pipe (\code{|>}) uses the +\code{_} placeholder, the piped value fills the formal named next to +\code{_}, so no leading argument is pre-claimed and the remaining +positional arguments are still matched: +\code{x |> lm(y ~ z, data = _)} becomes +\code{x |> lm(formula = y ~ z, data = _)}. When a magrittr pipe +(\code{\%>\%}, \code{\%<>\%}, \code{\%T>\%}) contains \code{.} anywhere in +its right-hand side, the piped value is substituted at \code{.} instead of +being inserted as the first argument, and again no formal is pre-claimed: +\code{x \%>\% f(., y)} becomes \code{x \%>\% f(a = ., b = y)}. +} + \section{Single-file operation}{ Operates on one R file. When \code{path} is \code{NULL} and RStudio is diff --git a/man/optimize_rmd_yaml.Rd b/man/optimize_rmd_yaml.Rd index ad4d55d..e4315aa 100644 --- a/man/optimize_rmd_yaml.Rd +++ b/man/optimize_rmd_yaml.Rd @@ -24,7 +24,7 @@ RStudio editor is used.} \item{readme_format}{Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html".} -\item{date}{"auto" -> 2026-10-28; "desc" -> DESCRIPTION Date field; +\item{date}{"auto" -> 2026-10-30; "desc" -> DESCRIPTION Date field; "none" -> do not add a date.} \item{extra}{Named list of extra YAML fields added to the file. It is merged diff --git a/man/package_optimize_rmd_yaml.Rd b/man/package_optimize_rmd_yaml.Rd index 817e07f..863ca95 100644 --- a/man/package_optimize_rmd_yaml.Rd +++ b/man/package_optimize_rmd_yaml.Rd @@ -25,7 +25,7 @@ package_optimize_rmd_yaml( \item{readme_format}{Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html".} -\item{date}{"auto" -> 2026-10-28; "desc" -> DESCRIPTION Date field; +\item{date}{"auto" -> 2026-10-30; "desc" -> DESCRIPTION Date field; "none" -> do not add a date.} \item{extra}{Named list of extra YAML fields added to the file. It is merged diff --git a/tests/testthat/test-make_func_arg_explicit.R b/tests/testthat/test-make_func_arg_explicit.R index f1a44ab..03da523 100644 --- a/tests/testthat/test-make_func_arg_explicit.R +++ b/tests/testthat/test-make_func_arg_explicit.R @@ -78,6 +78,87 @@ test_that("mfae_operators contains core operators (not control flow)", { expect_false("(" %in% .mfae_operators) }) +# --------------------------------------------------------------------------- +# .mfae_pipe_shift / .mfae_has_placeholder -- unit tests +# --------------------------------------------------------------------------- + +# Build the internal parse-data structure and locate the call node of a +# function by name, so the pipe helpers can be exercised directly. +mfae_pd <- function(code) { + exprs <- parse(text = code, keep.source = TRUE) + .mfae_parse_data(utils::getParseData(exprs)) +} + +mfae_call_id <- function(pd, fn) { + row <- which(pd$token == "SYMBOL_FUNCTION_CALL" & pd$text == fn)[[1L]] + head_row <- which(pd$id == pd$parent[[row]])[[1L]] + pd$parent[[head_row]] +} + +test_that("pipe_placeholder reports the placeholder of each pipe flavour", { + expect_equal(.mfae_pipe_placeholder("%>%"), ".") + expect_equal(.mfae_pipe_placeholder("%<>%"), ".") + expect_equal(.mfae_pipe_placeholder("%T>%"), ".") + expect_equal(.mfae_pipe_placeholder("|>"), "_") +}) + +test_that("pipe_shift is 1 for the right-hand side of a pipe", { + pd <- mfae_pd("x %>% round(2)") + expect_equal(.mfae_pipe_shift(pd, mfae_call_id(pd, "round")), 1L) +}) + +test_that("pipe_shift is 1 for the native pipe too", { + pd <- mfae_pd("x |> round(2)") + expect_equal(.mfae_pipe_shift(pd, mfae_call_id(pd, "round")), 1L) +}) + +test_that("pipe_shift is 0 when magrittr sees a dot placeholder", { + pd <- mfae_pd("x %>% rep(., 2)") + expect_equal(.mfae_pipe_shift(pd, mfae_call_id(pd, "rep")), 0L) +}) + +test_that("pipe_shift is 0 when the dot placeholder is nested", { + pd <- mfae_pd("x %>% rep(length(.), 2)") + expect_equal(.mfae_pipe_shift(pd, mfae_call_id(pd, "rep")), 0L) +}) + +test_that("pipe_shift ignores dot-prefixed symbols such as .data", { + pd <- mfae_pd("x %>% rep(.data$y, 2)") + expect_equal(.mfae_pipe_shift(pd, mfae_call_id(pd, "rep")), 1L) +}) + +test_that("pipe_shift is 0 when the native pipe uses _", { + skip_if(getRversion() < "4.3.0", "the _ placeholder needs R >= 4.3") + pd <- mfae_pd("x |> lm(y ~ z, data = _)") + expect_equal(.mfae_pipe_shift(pd, mfae_call_id(pd, "lm")), 0L) +}) + +test_that("pipe_shift is 0 outside a pipe", { + pd <- mfae_pd("round(2)") + expect_equal(.mfae_pipe_shift(pd, mfae_call_id(pd, "round")), 0L) +}) + +test_that("pipe_shift is 0 for the left-hand side of a pipe", { + pd <- mfae_pd("round(2) %>% sqrt()") + expect_equal(.mfae_pipe_shift(pd, mfae_call_id(pd, "round")), 0L) +}) + +test_that("pipe_shift is 0 for the pipe expression itself", { + pd <- mfae_pd("x %>% round(2)") + pipe_expr <- pd$parent[[which(pd$token == "SPECIAL")[[1L]]]] + expect_equal(.mfae_pipe_shift(pd, pipe_expr), 0L) +}) + +test_that("has_placeholder matches the exact symbol only", { + # `.data` and `..1` start with a dot but are different symbols. + pd <- mfae_pd("x %>% rep(.data$y, 2, ..1)") + expect_false(.mfae_has_placeholder(pd, mfae_call_id(pd, "rep"), ".")) + expect_false(.mfae_has_placeholder(pd, mfae_call_id(pd, "rep"), "_")) + + pd <- mfae_pd("x %>% rep(., .data$y)") + expect_true(.mfae_has_placeholder(pd, mfae_call_id(pd, "rep"), ".")) +}) + # --------------------------------------------------------------------------- # .mfae_resolve_function -- unit tests # --------------------------------------------------------------------------- @@ -428,10 +509,10 @@ test_that("infix operators like %>% are not transformed", { writeLines(input, tf) make_func_arg_explicit(tf) result <- readLines(tf, warn = FALSE) - # %>% is not transformed, but filter(y > 1) IS transformed because - # stats::filter is available (x -> filter(x = y > 1)) + # %>% itself is not transformed. The piped-in `x` already fills the first + # formal of stats::filter(x, filter, ...), so `y > 1` lands on `filter`. expect_true(grepl("x %>%", result, fixed = TRUE)) - expect_true(grepl("filter\\(x = y > 1\\)", result)) + expect_true(grepl("filter\\(filter = y > 1\\)", result)) }) test_that("if/for/while constructs are not transformed", { @@ -620,6 +701,167 @@ test_that("returns invisibly", { expect_invisible(make_func_arg_explicit(tf)) }) +# --------------------------------------------------------------------------- +# Pipes and placeholders +# --------------------------------------------------------------------------- + +test_that("a piped-in value claims the first formal", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines("x %>% substr(2, 3)", tf) + make_func_arg_explicit(tf) + expect_equal(readLines(tf, warn = FALSE), "x %>% substr(start = 2, stop = 3)") +}) + +test_that("the native pipe also claims the first formal", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines("x |> substr(2, 3)", tf) + make_func_arg_explicit(tf) + expect_equal(readLines(tf, warn = FALSE), "x |> substr(start = 2, stop = 3)") +}) + +test_that("a pipe chain is transformed link by link", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines( + c( + "a1 %>% substr(1, 1) %>% trimws(\"left\")", + "b2 |> substr(1, 1) |> trimws(\"left\")" + ), + tf + ) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + c( + "a1 %>% substr(start = 1, stop = 1) %>% trimws(which = \"left\")", + "b2 |> substr(start = 1, stop = 1) |> trimws(which = \"left\")" + ) + ) +}) + +test_that("only the direct right-hand side call consumes the piped value", { + tf <- withr::local_tempfile(fileext = ".R") + # `trimws()` is nested, so it keeps its own first formal `x`; only the outer + # `substr()` starts one formal later. + writeLines("x %>% substr(trimws(\"left\"), 2)", tf) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + "x %>% substr(start = trimws(x = \"left\"), stop = 2)" + ) +}) + +test_that("the magrittr dot placeholder cancels the leading injection", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines("x %>% substr(., 2)", tf) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + "x %>% substr(x = ., start = 2)" + ) +}) + +test_that("a nested dot placeholder cancels the leading injection too", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines("x %>% substr(nchar(.), 2)", tf) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + "x %>% substr(x = nchar(x = .), start = 2)" + ) +}) + +test_that("a dot-prefixed symbol is not a placeholder", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines("x %>% substr(.data$y, 2)", tf) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + "x %>% substr(start = .data$y, stop = 2)" + ) +}) + +test_that("the native pipe placeholder claims the formal it is attached to", { + skip_if(getRversion() < "4.3.0", "the _ placeholder needs R >= 4.3") + tf <- withr::local_tempfile(fileext = ".R") + writeLines("d |> lm(mpg ~ wt, data = _)", tf) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + "d |> lm(formula = mpg ~ wt, data = _)" + ) +}) + +test_that("a named argument after _ is matched normally", { + skip_if(getRversion() < "4.3.0", "the _ placeholder needs R >= 4.3") + tf <- withr::local_tempfile(fileext = ".R") + writeLines("d |> sub(\"a\", \"b\", x = _)", tf) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + "d |> sub(pattern = \"a\", replacement = \"b\", x = _)" + ) +}) + +test_that("piping into a dots-only function inserts nothing", { + tf <- withr::local_tempfile(fileext = ".R") + input_lines <- c("x %>% list(1, 2)", "x |> print()") + writeLines(input_lines, tf) + make_func_arg_explicit(tf) + expect_equal(readLines(tf, warn = FALSE), input_lines) +}) + +test_that("other magrittr pipes are treated like %>%", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines("x %T>% substr(2, 3)", tf) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + "x %T>% substr(start = 2, stop = 3)" + ) +}) + +test_that("a comment between a pipe and its right-hand side is preserved", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines( + c( + "res <- \"a1\" |>", + " # trim it", + " substr(2, 3)" + ), + tf + ) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + c( + "res <- \"a1\" |>", + " # trim it", + " substr(start = 2, stop = 3)" + ) + ) +}) + +test_that("the reported pipeline bug stays fixed", { + tf <- withr::local_tempfile(fileext = ".R") + writeLines( + c( + "res <- rownames(mtcars) %>%", + " substr(1, 2) |>", + " trimws(\"left\")" + ), + tf + ) + make_func_arg_explicit(tf) + expect_equal( + readLines(tf, warn = FALSE), + c( + "res <- rownames(x = mtcars) %>%", + " substr(start = 1, stop = 2) |>", + " trimws(which = \"left\")" + ) + ) +}) + # --------------------------------------------------------------------------- # package_func_arg_explicit -- integration tests # --------------------------------------------------------------------------- diff --git a/vignettes/news.Rmd b/vignettes/news.Rmd index 6d4a1de..efd61c7 100644 --- a/vignettes/news.Rmd +++ b/vignettes/news.Rmd @@ -36,8 +36,7 @@ knitr::opts_chunk$set( Here we create a template for editing NEWS.md ```{r} -#| label = "setup", -#| echo = FALSE +#| label = "setup" library(rpkgkit) tmpdir <- tempdir() usethis::create_package(tmpdir, open = FALSE) diff --git a/vignettes/pkg_maintain.Rmd b/vignettes/pkg_maintain.Rmd index ffdf635..b85534f 100644 --- a/vignettes/pkg_maintain.Rmd +++ b/vignettes/pkg_maintain.Rmd @@ -31,11 +31,10 @@ knitr::opts_chunk$set( ```{r} #| label = "setup", -#| echo = FALSE, -#| message = FALSE library(rpkgkit) dir <- tempdir() usethis::create_package(path = dir, open = FALSE) +usethis::use_pkgdown() ``` # Create package infrastructure @@ -79,8 +78,7 @@ the `R/` directory (which holds no C++ code) and adds `.clangd` to `.Rbuildignore`. ```{r} -#| label = "use_clangd_include", -#| eval = FALSE +#| label = "use_clangd_include" use_clangd(path = dir, include = c("Rcpp", "BH"), overwrite = TRUE) ``` @@ -104,7 +102,7 @@ directory. When `path` is a package root, `jarl.toml` is also added to ```{r} #| label = "use_jarl_content" -readLines(file.path(dir, "jarl.toml")) +readLines(file.path(dir, "jarl.toml")) |> cli::cli_code() ``` Read the @@ -261,8 +259,7 @@ reports every hit and miss together with a ready-to-paste install command for the missing ones. ```{r} -#| label = "check_sysdeps", -#| eval = FALSE +#| label = "check_sysdeps" check_sysdeps() ``` @@ -273,17 +270,15 @@ expects. Pass your own names in `deps`, and optionally set `manager` to check against a manager other than the detected one: ```{r} -#| label = "check_sysdeps_deps", -#| eval = FALSE -check_sysdeps(c("freetype-devel", "libwebp-devel"), manager = "rpm") +#| label = "check_sysdeps_deps" +try(check_sysdeps(c("freetype-devel", "libwebp-devel"), manager = "rpm")) ``` The result is returned invisibly as a named logical vector, so it can be reused in scripts. Set `verbose = FALSE` to keep the run silent: ```{r} -#| label = "check_sysdeps_result", -#| eval = FALSE +#| label = "check_sysdeps_result" ok <- check_sysdeps(verbose = FALSE) ok[!ok] ``` From 1942f2c873b786dde92820c0e974c6c3a4a9395b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 31 Oct 2026 04:12:41 +0000 Subject: [PATCH 06/35] chore: bump version to 0.1.22 [skip ci] --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 91965f4..04d9dfe 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: rpkgkit Title: Create and Maintain R Packages -Version: 0.1.21 +Version: 0.1.22 Authors@R: c( person("Yuxi", "Yang", , "15364051195@163.com", role = c("aut", "cre")), person("Jacob", "Scott", role = c("ctb", "cph"), From d41245ecfe6c9119750fc9ec1848e390f6d73836 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Sat, 31 Oct 2026 00:49:43 -0400 Subject: [PATCH 07/35] update vignettes --- man/optimize_rmd_yaml.Rd | 2 +- man/package_optimize_rmd_yaml.Rd | 2 +- man/rpkgkit-package.Rd | 3 +-- vignettes/pkg_maintain.Rmd | 9 ++++--- vignettes/standalone_tools.Rmd | 41 ++++++++++++++------------------ 5 files changed, 27 insertions(+), 30 deletions(-) diff --git a/man/optimize_rmd_yaml.Rd b/man/optimize_rmd_yaml.Rd index e4315aa..a8c001a 100644 --- a/man/optimize_rmd_yaml.Rd +++ b/man/optimize_rmd_yaml.Rd @@ -24,7 +24,7 @@ RStudio editor is used.} \item{readme_format}{Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html".} -\item{date}{"auto" -> 2026-10-30; "desc" -> DESCRIPTION Date field; +\item{date}{"auto" -> \code{Sys.Date()}; "desc" -> DESCRIPTION Date field; "none" -> do not add a date.} \item{extra}{Named list of extra YAML fields added to the file. It is merged diff --git a/man/package_optimize_rmd_yaml.Rd b/man/package_optimize_rmd_yaml.Rd index 863ca95..c608cb3 100644 --- a/man/package_optimize_rmd_yaml.Rd +++ b/man/package_optimize_rmd_yaml.Rd @@ -25,7 +25,7 @@ package_optimize_rmd_yaml( \item{readme_format}{Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html".} -\item{date}{"auto" -> 2026-10-30; "desc" -> DESCRIPTION Date field; +\item{date}{"auto" -> \code{Sys.Date()}; "desc" -> DESCRIPTION Date field; "none" -> do not add a date.} \item{extra}{Named list of extra YAML fields added to the file. It is merged diff --git a/man/rpkgkit-package.Rd b/man/rpkgkit-package.Rd index cda46d2..49724b7 100644 --- a/man/rpkgkit-package.Rd +++ b/man/rpkgkit-package.Rd @@ -20,8 +20,7 @@ MIT + file LICENSE \seealso{ Useful links: \itemize{ - \item \url{https://github.com/WangLabCSU/rpkgkit} - \item \url{https://wanglabcsu.github.io/rpkgkit/} + \item /tmp/RtmpoUp5qA \item Report bugs at \url{https://github.com/WangLabCSU/rpkgkit/issues} } diff --git a/vignettes/pkg_maintain.Rmd b/vignettes/pkg_maintain.Rmd index b85534f..fbc8fbe 100644 --- a/vignettes/pkg_maintain.Rmd +++ b/vignettes/pkg_maintain.Rmd @@ -259,7 +259,8 @@ reports every hit and miss together with a ready-to-paste install command for the missing ones. ```{r} -#| label = "check_sysdeps" +#| label = "check_sysdeps", +#| eval = FALSE check_sysdeps() ``` @@ -270,7 +271,8 @@ expects. Pass your own names in `deps`, and optionally set `manager` to check against a manager other than the detected one: ```{r} -#| label = "check_sysdeps_deps" +#| label = "check_sysdeps_deps", +#| eval = FALSE try(check_sysdeps(c("freetype-devel", "libwebp-devel"), manager = "rpm")) ``` @@ -278,7 +280,8 @@ The result is returned invisibly as a named logical vector, so it can be reused in scripts. Set `verbose = FALSE` to keep the run silent: ```{r} -#| label = "check_sysdeps_result" +#| label = "check_sysdeps_result", +#| eval = FALSE ok <- check_sysdeps(verbose = FALSE) ok[!ok] ``` diff --git a/vignettes/standalone_tools.Rmd b/vignettes/standalone_tools.Rmd index a755cbd..5d4474c 100644 --- a/vignettes/standalone_tools.Rmd +++ b/vignettes/standalone_tools.Rmd @@ -30,8 +30,7 @@ knitr::opts_chunk$set( ``` ```{r} -#| label = "setup", -#| eval = FALSE +#| label = "setup" library(rpkgkit) dir <- file.path(tempdir(), "example") usethis::create_package(dir, open = FALSE) @@ -39,14 +38,6 @@ usethis::local_project(dir) usethis::use_readme_md(open = FALSE) ``` -```{r} -#| label = "setup_bg", -#| include = FALSE, -#| echo = FALSE, -#| message = FALSE -library(rpkgkit) -``` - # Import standalone helpers `rpkgkit` includes utilities that can also be imported directly into another @@ -120,7 +111,9 @@ color_cli2$cli_alert_success( The `ts_cli.R` standalone script creates timestamped `cli` functions. -```r +```{r} +#| label = "ts_cli", +#| eval = FALSE ts_cli <- create_ts_cli_env() ts_cli$cli_alert_info("Hello, world!") ``` @@ -172,8 +165,10 @@ add("sum", 3) Errors raised inside the block reach the caller unchanged, and an assignment to an existing argument is written back through the returned list: -```r -list2env(validate_add(), envir = environment()) +```{r} +#| label = "validate_add", +#| eval = FALSE +try(list2env(validate_add(), envir = environment())) ``` Only names that already existed in the caller's frame are returned, so a @@ -199,9 +194,8 @@ try(browse_standalone()) |> head() Create a local standalone file with a standard metadata header: ```{r} -#| label = "create", -#| eval = FALSE -create_standalone("foo", open = FALSE) +#| label = "create" +create_standalone("foo", path = file.path(dir, "R"), open = FALSE) ``` ## Validate the standalone file layout @@ -213,9 +207,8 @@ required `repo`, `file`, `last-updated` and `license` slots, the optional carries `@noRd`, and that a `# nocov start` marker precedes all functions. ```{r} -#| label = "check_standalone", -#| eval = FALSE -check_standalone("R/standalone-foo.R") +#| label = "check_standalone" +check_standalone(path = file.path(dir, "R/standalone-foo.R")) ``` Findings are printed in the style of `devtools::check()`, and the counts are @@ -225,9 +218,8 @@ point skips the remaining ones, while warnings and notes never stop the run. After editing standalone files, refresh their `last-updated` field: ```{r} -#| label = "update timestamp", -#| eval = FALSE -update_time_in_standalone(path = "./R/standalone-foo.R") +#| label = "update timestamp" +update_time_in_standalone(path = file.path(dir, "R/standalone-foo.R")) ``` Add a dated changelog entry to one or more standalone files: @@ -235,5 +227,8 @@ Add a dated changelog entry to one or more standalone files: ```{r} #| label = "add changelog", #| eval = FALSE -add_changelog_in_standalone("R/standalone-foo.R", "Added foo function") +add_changelog_in_standalone( + path = file.path(dir, "R/standalone-foo.R"), + "Added foo function" +) ``` From 92f341a62cacf844e6ff7c5c276c5058be22d1d6 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Sat, 31 Oct 2026 05:43:03 -0400 Subject: [PATCH 08/35] update vignettes --- R/61_create_standalone.R | 2 +- vignettes/standalone_tools.Rmd | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/R/61_create_standalone.R b/R/61_create_standalone.R index 885430f..6679480 100644 --- a/R/61_create_standalone.R +++ b/R/61_create_standalone.R @@ -133,7 +133,7 @@ create_standalone <- function( "\n# TODO\n", paste0("# nocov", " end") ) - + file.create(target_path) writeLines(head_lines, con = target_path) cli::cli_alert_success("Created standalone file: {.path {target_path}}") diff --git a/vignettes/standalone_tools.Rmd b/vignettes/standalone_tools.Rmd index 5d4474c..8a4db7f 100644 --- a/vignettes/standalone_tools.Rmd +++ b/vignettes/standalone_tools.Rmd @@ -30,10 +30,12 @@ knitr::opts_chunk$set( ``` ```{r} -#| label = "setup" +#| label = "setup", +#| eval = FALSE library(rpkgkit) -dir <- file.path(tempdir(), "example") -usethis::create_package(dir, open = FALSE) +dir <- tempdir() +dir.create(dir) +usethis::create_package(dir) usethis::local_project(dir) usethis::use_readme_md(open = FALSE) ``` @@ -195,7 +197,8 @@ Create a local standalone file with a standard metadata header: ```{r} #| label = "create" -create_standalone("foo", path = file.path(dir, "R"), open = FALSE) +dir <- file.path(tempdir(), "R") +create_standalone("foo", path = dir, open = FALSE) ``` ## Validate the standalone file layout @@ -208,7 +211,7 @@ carries `@noRd`, and that a `# nocov start` marker precedes all functions. ```{r} #| label = "check_standalone" -check_standalone(path = file.path(dir, "R/standalone-foo.R")) +check_standalone(path = file.path(dir, "standalone-foo.R")) ``` Findings are printed in the style of `devtools::check()`, and the counts are @@ -219,7 +222,7 @@ After editing standalone files, refresh their `last-updated` field: ```{r} #| label = "update timestamp" -update_time_in_standalone(path = file.path(dir, "R/standalone-foo.R")) +update_time_in_standalone(path = file.path(dir, "standalone-foo.R")) ``` Add a dated changelog entry to one or more standalone files: @@ -228,7 +231,7 @@ Add a dated changelog entry to one or more standalone files: #| label = "add changelog", #| eval = FALSE add_changelog_in_standalone( - path = file.path(dir, "R/standalone-foo.R"), + path = file.path(dir, "standalone-foo.R"), "Added foo function" ) ``` From 4026bd6f50b6543e009e51c7b26319cdd4420dd7 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Sat, 31 Oct 2026 19:45:00 -0400 Subject: [PATCH 09/35] update vignettes --- vignettes/standalone_tools.Rmd | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vignettes/standalone_tools.Rmd b/vignettes/standalone_tools.Rmd index 8a4db7f..27653d8 100644 --- a/vignettes/standalone_tools.Rmd +++ b/vignettes/standalone_tools.Rmd @@ -197,7 +197,9 @@ Create a local standalone file with a standard metadata header: ```{r} #| label = "create" +library(rpkgkit) dir <- file.path(tempdir(), "R") +dir.create(dir, recursive = TRUE) create_standalone("foo", path = dir, open = FALSE) ``` @@ -228,8 +230,7 @@ update_time_in_standalone(path = file.path(dir, "standalone-foo.R")) Add a dated changelog entry to one or more standalone files: ```{r} -#| label = "add changelog", -#| eval = FALSE +#| label = "add changelog" add_changelog_in_standalone( path = file.path(dir, "standalone-foo.R"), "Added foo function" From 0146aef75f42647fbab86bfbc2ee417ed26c007b Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Sun, 1 Nov 2026 23:48:20 -0500 Subject: [PATCH 10/35] ## NEW FEATURES * Added `detect_fn_arg_path()` and `package_fn_arg_path()` to report exported functions whose path-like argument defaults to a concrete location, which CRAN does not allow. The check is syntactic: the file is parsed, the top-level `name <- function(...)` definitions that count as exported are kept, and every formal whose name matches `arg_pattern` (default `"path|file|filename"`) is reported when its default is not listed in `allow` (default `"NULL"`); an argument without a default is always fine. Each hit is printed as `file:line:col` with the function and argument name, the source lines and a caret marker under `arg = default`. `detect_fn_arg_path()` checks one file and falls back to the active document; pass `exports` or `export_patterns` when the exports of that file are known, otherwise every top-level function is checked. `package_fn_arg_path()` reads the exports from `NAMESPACE` and scans the `.R` files under `dirs` (default `"R"`). Both return `TRUE` invisibly when nothing needs fixing. * Added `use_tidy_addin()` to register an exported function in `inst/rstudio/addins.dcf`, which makes it available from the RStudio Addins menu. The new entry is written above the existing ones, a `Binding` that is already registered is never added twice, and the file is written as UTF-8. Before writing, the function checks that the path is a package and that the function is exported in `NAMESPACE`, reads the function body (from the installed package, or from `R/` when the package has not been documented yet), and warns when the body calls no `rstudioapi` function or, with `Interactive = TRUE`, no `shiny`/`miniUI` function; a non-interactive session cannot confirm, so it only reports the warning and continues. It returns the path of the dcf file invisibly, or `NULL` when the operation is cancelled. * `rpkgkit` now registers its own addins in `inst/rstudio/addins.dcf`: `package_lost_glue_brace()` and `detect_lost_glue_brace()`, `package_print_and_cat()` and `detect_print_and_cat()`, `package_fn_arg_path()` and `detect_fn_arg_path()`, `package_unmatched_nocov_marker()` and `check_pkgdown_reference()`. The `detect_*()` addins run on the active editor, the package-wide ones on the current package directory. All of them only report, so none rewrites a file. ## MINOR IMPROVEMENTS * `detect_lost_glue_brace()` and `detect_print_and_cat()` now print the offending source line with cli syntax highlighting. The file is highlighted once and then indexed line by line, because a single source line is usually not parseable (a continuation such as `x = fn(a, b),` ends with a comma) and `cli::code_highlight()` silently returns unparseable input unchanged; when the highlighting fails, or when it returns a different number of lines, the plain source is printed instead. * `add_colors_to_cli()` (standalone `colorful_cli.R`) gained `.envir`, defaulting to `parent.frame()` and forwarded to the wrapped cli function, so glue-style interpolation such as `"Hello, {name}"` is resolved in the caller's environment instead of the wrapper's frame. * `use_zzz()` now resolves `file_name` inside the function body (`file_name = NULL` means `-package.R`) instead of in the default argument, following the `path = NULL` convention of the other `use_*()` helpers. ## DOCUMENTATION * The `code_convertion` vignette gained a "Detect default paths in exported arguments" section covering `detect_fn_arg_path()` and `package_fn_arg_path()`, and the `pkg_maintain` vignette an "RStudio addins" section covering `use_tidy_addin()` and the bundled addins. * The `standalone_tools` vignette documents the `.envir` argument of the `colorful_cli.R` wrapper. * The README gained an "Addin" section, and `README.md` was regenerated from `README.Rmd`. Both translations under `inst/translations/` were brought back in sync with the English README: they now share its badge block (the stale development-version badge is gone), and carry the "recommended packages" and "AI skills" sections and the "Addin" section they were missing. * The package skill (`skills/rpkgkit/`) covers the new functions and the addin workflow. * Vignette subtitles now report version 0.1.23. --- DESCRIPTION | 2 +- NAMESPACE | 3 + NEWS.md | 72 +++ R/11A_package_fn_arg_path.R | 86 ++++ R/11_detect_fn_arg_path.R | 262 +++++++++++ R/14_detect_lost_glue_brace.R | 18 +- R/18A_package_print_and_cat.R | 6 +- R/18_detect_print_and_cat.R | 18 +- R/45_use_zzz.R | 5 +- R/53_use_tidy_addin.R | 295 ++++++++++++ R/standalone-caller_cli.R | 10 +- R/standalone-colorful_cli.R | 18 +- R/standalone-ts_cli.R | 23 +- README.Rmd | 8 + README.md | 9 + _pkgdown.yml | 3 + inst/rstudio/addins.dcf | 49 ++ inst/translations/README.es.md | 34 +- inst/translations/README.zh-cn.md | 34 +- man/detect_fn_arg_path.Rd | 86 ++++ man/rpkgkit-package.Rd | 2 +- man/use_tidy_addin.Rd | 33 ++ man/use_zzz.Rd | 2 +- skills/rpkgkit/SKILL.md | 37 +- .../rpkgkit/references/function-reference.md | 5 +- tests/testthat/standalone-test.R | 0 tests/testthat/test-add_caller_to_cli.R | 4 +- tests/testthat/test-colorful_cli.R | 16 +- tests/testthat/test-detect_fn_arg_path.R | 285 ++++++++++++ tests/testthat/test-package_fn_arg_path.R | 217 +++++++++ tests/testthat/test-ts_cli.R | 22 +- tests/testthat/test-use_tidy_addin.R | 434 ++++++++++++++++++ vignettes/code_convertion.Rmd | 51 +- vignettes/news.Rmd | 2 +- vignettes/pkg_maintain.Rmd | 51 +- vignettes/readme_and_doc.Rmd | 2 +- vignettes/standalone_tools.Rmd | 16 +- 37 files changed, 2166 insertions(+), 54 deletions(-) create mode 100644 R/11A_package_fn_arg_path.R create mode 100644 R/11_detect_fn_arg_path.R create mode 100644 R/53_use_tidy_addin.R create mode 100644 inst/rstudio/addins.dcf create mode 100644 man/detect_fn_arg_path.Rd create mode 100644 man/use_tidy_addin.Rd create mode 100644 tests/testthat/standalone-test.R create mode 100644 tests/testthat/test-detect_fn_arg_path.R create mode 100644 tests/testthat/test-package_fn_arg_path.R create mode 100644 tests/testthat/test-use_tidy_addin.R diff --git a/DESCRIPTION b/DESCRIPTION index 04d9dfe..a2b3a12 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -18,7 +18,7 @@ Description: Utilities for R package development including NEWS.md 'RStudio'. Includes helper functions for renaming functions and detecting common coding errors. License: MIT + file LICENSE -URL: /tmp/RtmpoUp5qA +URL: https://github.com/Exceret/rpkgkit BugReports: https://github.com/WangLabCSU/rpkgkit/issues Depends: R (>= 4.2) diff --git a/NAMESPACE b/NAMESPACE index 6383e23..7bc7c0c 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -19,6 +19,7 @@ export(convert_nonascii_code) export(convert_pipe) export(create_standalone) export(current_packages) +export(detect_fn_arg_path) export(detect_lost_glue_brace) export(detect_print_and_cat) export(detect_unmatched_nocov_marker) @@ -36,6 +37,7 @@ export(open_cffinit) export(optimize_rmd_yaml) export(package_convert_int_literals) export(package_convert_pipe) +export(package_fn_arg_path) export(package_func_arg_explicit) export(package_func_call_explicit) export(package_lost_glue_brace) @@ -51,6 +53,7 @@ export(use_hexsticker) export(use_jarl) export(use_multilanguage_readme) export(use_r_v4.1.0) +export(use_tidy_addin) export(use_url) export(use_vendor) export(use_workflow_rust_compatible_check) diff --git a/NEWS.md b/NEWS.md index 2e84cbf..8abe18b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,75 @@ +# rpkgkit 0.1.23 (2026-11-01) + +## NEW FEATURES + +* Added `detect_fn_arg_path()` and `package_fn_arg_path()` to report exported + functions whose path-like argument defaults to a concrete location, which CRAN + does not allow. The check is syntactic: the file is parsed, the top-level + `name <- function(...)` definitions that count as exported are kept, and every + formal whose name matches `arg_pattern` (default `"path|file|filename"`) is + reported when its default is not listed in `allow` (default `"NULL"`); an + argument without a default is always fine. Each hit is printed as + `file:line:col` with the function and argument name, the source lines and a + caret marker under `arg = default`. `detect_fn_arg_path()` checks one file and + falls back to the active document; pass `exports` or `export_patterns` when the + exports of that file are known, otherwise every top-level function is checked. + `package_fn_arg_path()` reads the exports from `NAMESPACE` and scans the `.R` + files under `dirs` (default `"R"`). Both return `TRUE` invisibly when nothing + needs fixing. +* Added `use_tidy_addin()` to register an exported function in + `inst/rstudio/addins.dcf`, which makes it available from the RStudio Addins + menu. The new entry is written above the existing ones, a `Binding` that is + already registered is never added twice, and the file is written as UTF-8. + Before writing, the function checks that the path is a package and that the + function is exported in `NAMESPACE`, reads the function body (from the + installed package, or from `R/` when the package has not been documented yet), + and warns when the body calls no `rstudioapi` function or, with + `Interactive = TRUE`, no `shiny`/`miniUI` function; a non-interactive session + cannot confirm, so it only reports the warning and continues. It returns the + path of the dcf file invisibly, or `NULL` when the operation is cancelled. +* `rpkgkit` now registers its own addins in `inst/rstudio/addins.dcf`: + `package_lost_glue_brace()` and `detect_lost_glue_brace()`, + `package_print_and_cat()` and `detect_print_and_cat()`, + `package_fn_arg_path()` and `detect_fn_arg_path()`, + `package_unmatched_nocov_marker()` and `check_pkgdown_reference()`. The + `detect_*()` addins run on the active editor, the package-wide ones on the + current package directory. All of them only report, so none rewrites a file. + +## MINOR IMPROVEMENTS + +* `detect_lost_glue_brace()` and `detect_print_and_cat()` now print the offending + source line with cli syntax highlighting. The file is highlighted once and then + indexed line by line, because a single source line is usually not parseable (a + continuation such as `x = fn(a, b),` ends with a comma) and + `cli::code_highlight()` silently returns unparseable input unchanged; when the + highlighting fails, or when it returns a different number of lines, the plain + source is printed instead. +* `add_colors_to_cli()` (standalone `colorful_cli.R`) gained `.envir`, defaulting + to `parent.frame()` and forwarded to the wrapped cli function, so glue-style + interpolation such as `"Hello, {name}"` is resolved in the caller's environment + instead of the wrapper's frame. +* `use_zzz()` now resolves `file_name` inside the function body + (`file_name = NULL` means `-package.R`) instead of in the default + argument, following the `path = NULL` convention of the other `use_*()` + helpers. + +## DOCUMENTATION + +* The `code_convertion` vignette gained a "Detect default paths in exported + arguments" section covering `detect_fn_arg_path()` and + `package_fn_arg_path()`, and the `pkg_maintain` vignette an "RStudio addins" + section covering `use_tidy_addin()` and the bundled addins. +* The `standalone_tools` vignette documents the `.envir` argument of the + `colorful_cli.R` wrapper. +* The README gained an "Addin" section, and `README.md` was regenerated from + `README.Rmd`. Both translations under `inst/translations/` were brought back in + sync with the English README: they now share its badge block (the stale + development-version badge is gone), and carry the "recommended packages" and + "AI skills" sections and the "Addin" section they were missing. +* The package skill (`skills/rpkgkit/`) covers the new functions and the addin + workflow. +* Vignette subtitles now report version 0.1.23. + # rpkgkit 0.1.22 (2026-10-28) ## NEW FEATURES diff --git a/R/11A_package_fn_arg_path.R b/R/11A_package_fn_arg_path.R new file mode 100644 index 0000000..b9492ef --- /dev/null +++ b/R/11A_package_fn_arg_path.R @@ -0,0 +1,86 @@ +#' @rdname detect_fn_arg_path +#' @export +package_fn_arg_path <- function( + path = NULL, + arg_pattern = "path|file|filename", + allow = "NULL", + dirs = "R", + verbose = TRUE, + ... +) { + rlang::check_dots_empty() + path <- path %||% "." + if (!nzchar(path)) { + cli::cli_abort(c("x" = "{.arg path} is required")) + } + path <- normalizePath(path = path, mustWork = FALSE) + if (!is_pkg(path = path)) { + cli::cli_abort("{.path {path}} is not an R package (no DESCRIPTION found).") + } + + ns <- .uta_parse_namespace(file.path(path, "NAMESPACE")) + if (length(ns$exports) == 0L && length(ns$export_patterns) == 0L) { + cli::cli_alert_info("No exported functions found in {.file NAMESPACE}.") + return(invisible(TRUE)) + } + + files <- character() + for (dir in dirs) { + dir_path <- file.path(path, dir) + if (!dir.exists(dir_path)) { + next + } + files <- c( + files, + list.files( + path = dir_path, + pattern = "\\.[Rr]$", + full.names = TRUE, + recursive = TRUE + ) + ) + } + + n <- length(files) + if (n < 1L) { + cli::cli_alert_info("No {.code .R} files found to scan in {.path {path}}.") + return(invisible(TRUE)) + } + + n_hits <- 0L + n_bad_files <- 0L + for (f in files) { + scanned <- scan_fn_arg_path( + file = f, + arg_pattern = arg_pattern, + exports = ns$exports, + export_patterns = ns$export_patterns, + allow = allow + ) + k <- length(scanned$hits) + if (k > 0L) { + n_hits <- n_hits + k + n_bad_files <- n_bad_files + 1L + if (verbose) { + report_fn_arg_hits( + file = f, + lines = scanned$lines, + hits = scanned$hits, + root = path + ) + } + } + } + + if (n_hits == 0L) { + cli::cli_alert_success( + "No exported function has a default path argument ({n} file{?s} scanned)." + ) + } else { + cli::cli_alert_danger( + "Found {n_hits} argument{?s} with a default path in {n_bad_files} of {n} file{?s}." + ) + } + + invisible(n_hits == 0L) +} diff --git a/R/11_detect_fn_arg_path.R b/R/11_detect_fn_arg_path.R new file mode 100644 index 0000000..214181f --- /dev/null +++ b/R/11_detect_fn_arg_path.R @@ -0,0 +1,262 @@ +#' Detect Default Paths in Exported Function Arguments +#' +#' @description +#' CRAN does not allow exported functions to default a path-like argument to a +#' concrete location. This checker parses R source, finds exported functions, +#' and reports every argument whose name matches `arg_pattern` and whose +#' default value is not in `allow` (by default only `NULL`; an argument with +#' no default is always fine). Each hit is reported with file, line, column and +#' a caret (`^^^^`) marker under `arg = default`. +#' +#' @section Single file vs package scope: +#' \describe{ +#' \item{\code{detect_fn_arg_path()}}{Operates on one \R file. Use +#' \code{exports} / \code{export_patterns} to say which top-level functions +#' count as exported; when \code{exports} is \code{NULL} and no patterns are +#' given, every top-level function in the file is checked.} +#' \item{\code{package_fn_arg_path()}}{Checks that \code{path} is an \R +#' package, reads exports from \code{NAMESPACE}, then scans \code{.R} files +#' under \code{dirs} (default \code{"R"}).} +#' } +#' +#' @param path For \code{detect_fn_arg_path()}: path to an \R file. If +#' \code{NULL} and RStudio is available, the active document is used. +#' +#' For \code{package_fn_arg_path()}: root directory of an \R package. +#' Defaults to the current directory. +#' @param arg_pattern Regular expression matched (unanchored) against argument +#' names. Use e.g. `"^(path|file|filename)$"` to avoid matching `profile`. +#' @param exports Character vector of exported function names. +#' @param export_patterns Character vector of regular expressions, as in +#' `exportPattern()` in `NAMESPACE`. +#' @param allow Character vector of default-value expressions (as written in +#' the source, whitespace trimmed) that are acceptable. +#' Defaults to `"NULL"`. +#' @param dirs Package-relative directories scanned by +#' \code{package_fn_arg_path()}. +#' @param verbose Whether to emit results to the console. +#' @param ... Unused. +#' +#' @return Invisibly returns \code{TRUE} if no offending defaults are found, +#' \code{FALSE} otherwise. +#' +#' @examples +#' \donttest{ +#' file <- tempfile(fileext = ".R") +#' writeLines('read_it <- function(path = "~/data.csv", n = 1) NULL', file) +#' detect_fn_arg_path(file) +#' } +#' +#' @name detect_fn_arg_path +NULL + +#' @rdname detect_fn_arg_path +#' @export +detect_fn_arg_path <- function( + path = NULL, + arg_pattern = "path|file|filename", + exports = NULL, + export_patterns = character(), + allow = "NULL", + verbose = TRUE, + ... +) { + rlang::check_dots_empty() + path <- path %||% + if (rstudioapi::isAvailable()) rstudioapi::getActiveDocumentContext()$path + if (is.null(path) || !nzchar(path)) { + cli::cli_abort(c("x" = "{.arg path} is required")) + } + + scanned <- scan_fn_arg_path( + file = path, + arg_pattern = arg_pattern, + exports = exports, + export_patterns = export_patterns, + allow = allow + ) + + if (length(scanned$hits) == 0L) { + if (verbose) { + cli::cli_alert_success("No need to fix") + } + return(invisible(TRUE)) + } + + if (verbose) { + report_fn_arg_hits(path, scanned$lines, scanned$hits) + n_hits <- length(scanned$hits) + cli::cli_alert_danger( + "Found {n_hits} argument{?s} with a default path in {.path {path}}" + ) + } + invisible(FALSE) +} + +# --------------------------------------------------------------------------- +# Scan one file; return source lines and a list of hits +# +# A "hit" is a formal argument of a top-level `name <- function(...)` whose +# * function is exported (or all functions, when no export info is given), +# * name matches `arg_pattern`, +# * has a default value that is not listed in `allow`. +# --------------------------------------------------------------------------- +scan_fn_arg_path <- function( + file, + arg_pattern, + exports = NULL, + export_patterns = character(), + allow = "NULL" +) { + if (!file.exists(file)) { + cli::cli_abort("File {.path {file}} does not exist.") + } + lines <- readLines(file, warn = FALSE) + exprs <- parse_safely(paste(lines, collapse = "\n"), file) + pd <- utils::getParseData(exprs) + + if (is.null(pd) || nrow(pd) == 0L) { + return(list(lines = lines, hits = list())) + } + + check_all <- is.null(exports) && length(export_patterns) == 0L + is_exported <- function(nm) { + check_all || + nm %in% exports || + any(vapply(export_patterns, grepl, logical(1L), x = nm)) + } + + formals_tok <- pd[ + pd$token == "SYMBOL_FORMALS" & grepl(arg_pattern, pd$text), + , + drop = FALSE + ] + + hits <- list() + for (k in seq_len(nrow(formals_tok))) { + tok <- formals_tok[k, ] + + # function expr -> its parent must be a top-level assignment expr + fn_row <- pd[pd$id == tok$parent, ] + assign_row <- pd[pd$id == fn_row$parent, ] + if (nrow(assign_row) != 1L || assign_row$parent != 0L) { + next + } + + sib <- pd[pd$parent == assign_row$id, ] + sib <- sib[order(sib$line1, sib$col1), ] + if ( + nrow(sib) < 3L || + !(sib$token[2L] %in% c("LEFT_ASSIGN", "EQ_ASSIGN")) || + sib$id[3L] != fn_row$id + ) { + next + } + + # function name (symbol or string on the left-hand side) + lhs <- pd[pd$parent == sib$id[1L], ] + lhs <- lhs[lhs$token %in% c("SYMBOL", "STR_CONST"), ] + if (nrow(lhs) == 0L) { + next + } + fn_name <- gsub("^[`\"']|[`\"']$", "", lhs$text[1L]) + if (!is_exported(fn_name)) { + next + } + + # default value = the node right after `=` following the formal name + fsib <- pd[pd$parent == fn_row$id, ] + fsib <- fsib[order(fsib$line1, fsib$col1), ] + pos <- which(fsib$id == tok$id) + if ( + length(pos) != 1L || + pos + 2L > nrow(fsib) || + fsib$token[pos + 1L] != "EQ_FORMALS" + ) { + next # no default value: fine + } + def_row <- fsib[pos + 2L, ] + def_text <- utils::getParseText(pd, def_row$id) + if (trimws(def_text) %in% allow) { + next + } + + hits[[length(hits) + 1L]] <- list( + fn = fn_name, + arg = tok$text, + default = gsub("\\s*\n\\s*", " ", def_text), + line1 = tok$line1, + col1 = tok$col1, + line2 = def_row$line2, + col2 = def_row$col2 + ) + } + + list(lines = lines, hits = hits) +} + +# --------------------------------------------------------------------------- +# Print hits, e.g. +# +# R/read.R:3:15 read_it(): `path` defaults to "~/data.csv" +# read_it <- function(path = "~/data.csv", n = 1) { +# ^^^^^^^^^^^^^^^^^^^ +# +# The code line(s) and the caret marker are printed with `cli_verbatim()`, so +# they keep their line breaks and are never re-wrapped by cli's text formatter. +# The source is highlighted as a whole file, because `cli::code_highlight()` +# needs complete, parseable code: a single line is usually not parseable (a +# continuation such as ` x = fn(a, b),` ends with a comma) and on a parse +# failure `code_highlight()` silently returns its input unchanged, i.e. without +# any highlighting. It must also be fed one element per line: with a single +# string containing `\n` only the first line would be highlighted. +# --------------------------------------------------------------------------- +report_fn_arg_hits <- function(file, lines, hits, root = NULL) { + shown <- if (is.null(root)) { + file + } else { + sub( + paste0("^", gsub("([.\\\\|()\\[{^$*+?])", "\\\\\\1", root), "/?"), + "", + file + ) + } + + hl_lines <- tryCatch( + cli::code_highlight(lines), + error = function(e) lines, + cli_parse_failure = function(cnd) lines + ) + if (length(hl_lines) != length(lines)) { + hl_lines <- lines + } + + for (h in hits) { + line_content <- lines[h$line1] + end_col <- if (h$line2 == h$line1) h$col2 else nchar(line_content) + caret <- paste0( + strrep(" ", h$col1 - 1L), + strrep("^", max(end_col - h$col1 + 1L, 1L)) + ) + cli::cli_text( + "{.path {shown}}", + ":", + h$line1, + ":", + h$col1, + " ", + "{.strong {h$fn}}", + "(): `", + "{.field {h$arg}}", + "` defaults to ", + cli::col_grey(h$default) + ) + shown_lines <- seq.int(h$line1, max(h$line2, h$line1)) + for (i in shown_lines) { + code_line <- if (i <= length(hl_lines)) hl_lines[i] else lines[i] + cli::cli_verbatim(code_line) + } + cli::cli_verbatim(cli::col_grey(caret)) + } + invisible(NULL) +} diff --git a/R/14_detect_lost_glue_brace.R b/R/14_detect_lost_glue_brace.R index 30d360d..7b13959 100644 --- a/R/14_detect_lost_glue_brace.R +++ b/R/14_detect_lost_glue_brace.R @@ -71,6 +71,18 @@ detect_lost_glue_brace <- function(path = NULL, verbose = TRUE, ...) { error_lines <- integer() + # highlight the whole file: a single source line is usually not parseable, and + # `cli::code_highlight()` silently returns unparseable input unchanged. It must + # also get one element per line, otherwise only the first line is highlighted. + hl_lines <- tryCatch( + cli::code_highlight(lines), + error = function(e) lines, + cli_parse_failure = function(cnd) lines + ) + if (length(hl_lines) != length(lines)) { + hl_lines <- lines + } + for (info in strings_info) { result <- check_brace_balance(info$content) @@ -80,7 +92,7 @@ detect_lost_glue_brace <- function(path = NULL, verbose = TRUE, ...) { if (verbose) { message( format_brace_error( - line_content = lines[info$line1], + line_content = hl_lines[info$line1], str_content = info$content, line_num = info$line1, col_offset = info$col1, @@ -278,8 +290,8 @@ find_nearest_open_before <- function(s, pos) { # "Hello, {name!" # ^^^^^^ # -# The top line is the original source line, the second line has `^` markers -# aligned under the problematic region. +# The top line is the original source line (already highlighted by the caller), +# the second line has `^` markers aligned under the problematic region. # --------------------------------------------------------------------------- format_brace_error <- function( line_content, diff --git a/R/18A_package_print_and_cat.R b/R/18A_package_print_and_cat.R index da26c6e..30bb904 100644 --- a/R/18A_package_print_and_cat.R +++ b/R/18A_package_print_and_cat.R @@ -150,13 +150,13 @@ package_detect_print_and_cat <- function( ) tag <- if (!is.null(info$kind)) paste0(" [", info$kind, "]") else "" cli::cli_text( - "{.file {relative_path}}: {.val {info$line1}}:" + "{.file {relative_path}}: {info$line1}:" ) message(paste0( - report_lines[[info$line1]], + cli::code_highlight(report_lines[[info$line1]]), cli::col_grey(tag), "\n", - caret + cli::col_grey(caret) )) } diff --git a/R/18_detect_print_and_cat.R b/R/18_detect_print_and_cat.R index 32b3fb7..97a40c8 100644 --- a/R/18_detect_print_and_cat.R +++ b/R/18_detect_print_and_cat.R @@ -161,6 +161,17 @@ detect_print_and_cat <- function( } report_lines <- if (fix) original_lines else lines + # highlight the whole file: a single source line is usually not parseable, and + # `cli::code_highlight()` silently returns unparseable input unchanged. It must + # also get one element per line, otherwise only the first line is highlighted. + hl_lines <- tryCatch( + cli::code_highlight(report_lines), + error = function(e) report_lines, + cli_parse_failure = function(cnd) report_lines + ) + if (length(hl_lines) != length(report_lines)) { + hl_lines <- report_lines + } for (info in calls_info) { caret_width <- nchar(x = info$text) + if (info$type == "call") 1L else 0L caret <- paste0( @@ -168,7 +179,12 @@ detect_print_and_cat <- function( strrep(x = "^", times = caret_width) ) tag <- if (!is.null(info$kind)) paste0(" [", info$kind, "]") else "" - message(paste0(report_lines[[info$line1]], tag, "\n", caret)) + message( + hl_lines[[info$line1]], + tag, + "\n", + caret + ) } reported_lines <- unique(vapply(calls_info, `[[`, integer(1L), "line1")) diff --git a/R/45_use_zzz.R b/R/45_use_zzz.R index 60af9d8..c606163 100644 --- a/R/45_use_zzz.R +++ b/R/45_use_zzz.R @@ -35,7 +35,7 @@ #' } use_zzz <- function( path = NULL, - file_name = paste0(get_package_name(path = path), "-package.R"), + file_name = NULL, overwrite = FALSE, open = rlang::is_interactive(), ... @@ -52,6 +52,9 @@ use_zzz <- function( usethis::proj_set(path = path) + file_name <- file_name %||% + paste0(get_package_name(path = path), "-package.R") + desc <- read.dcf(file = file.path(path, "DESCRIPTION")) pkg <- desc[, "Package"] title <- desc[, "Title"] diff --git a/R/53_use_tidy_addin.R b/R/53_use_tidy_addin.R new file mode 100644 index 0000000..5f27f0e --- /dev/null +++ b/R/53_use_tidy_addin.R @@ -0,0 +1,295 @@ +#' Create an RStudio Addin registration entry for a package function +#' +#' `use_tidy_addin()` writes an entry into `inst/rstudio/addins.dcf`, which +#' makes an exported function available from the RStudio Addins menu. +#' +#' @param fn_name Name of the function (it must already be exported in +#' `NAMESPACE`). +#' @param desc Description of the addin. +#' @param Interactive Whether this is an interactive addin (maps to the +#' `Interactive` field of the dcf file). +#' @param path Root directory of the R package. +#' +#' @return Invisibly, the path of the dcf file that was written (`NULL` if the +#' operation was cancelled). +#' @export +#' @examples +#' \dontrun{ +#' # Inside a package that exports `my_addin()` +#' use_tidy_addin("my_addin", "Open my Shiny gadget", Interactive = TRUE) +#' } +use_tidy_addin <- function( + fn_name, + desc, + Interactive = FALSE, + path = NULL +) { + # ---- 0. Argument checks ------------------------------------------------ + rlang::check_string(fn_name, "fn_name") + rlang::check_string(desc, "desc") + rlang::check_bool(Interactive, "Interactive") + rlang::check_installed("desc", "parse DESCRIPTION") + desc <- gsub("\\s*\n\\s*", " ", desc) # strip newlines + + # ---- 1. Check that path is an R package -------------------------------- + path <- path %||% "." + path <- normalizePath(path, mustWork = FALSE) + if (!is_pkg(path)) { + cli::cli_abort( + "{.path {path}} is not an R package directory (no DESCRIPTION found)." + ) + } + desc_file <- file.path(path, "DESCRIPTION") + pkg <- unname(desc::desc_get("Package", file = desc_file)) + + # ---- 2. Check that fn_name is exported in NAMESPACE -------------------- + ns_file <- file.path(path, "NAMESPACE") + if (!file.exists(ns_file)) { + cli::cli_abort(c( + "Cannot find {.file NAMESPACE}.", + "i" = "Please run {.code devtools::document()} first." + )) + } + ns <- .uta_parse_namespace(ns_file) + is_exported <- fn_name %in% + ns$exports || + any(vapply(ns$export_patterns, function(p) grepl(p, fn_name), logical(1))) + if (!is_exported) { + cli::cli_abort(c( + "{.fn {fn_name}} is not exported in NAMESPACE.", + "i" = "Please add {.code #' @export} and re-run {.code devtools::document()}." + )) + } + + # ---- 3. Obtain the function body --------------------------------------- + body_expr <- NULL + if (.uta_is_documented(path)) { + # Already documented: use pkg::fn_name |> rlang::fn_body directly + body_expr <- tryCatch( + { + if (!requireNamespace(pkg, quietly = TRUE)) { + stop("package not available") + } + getExportedValue(pkg, fn_name) |> rlang::fn_body() + }, + error = function(e) NULL + ) + } + if (is.null(body_expr)) { + # Not documented / package not installed or loaded: scan files under R/ + # for the definition + body_expr <- .uta_find_fn_body(fn_name, path) + } + if (is.null(body_expr)) { + cli::cli_abort( + "Cannot find a definition of {.fn {fn_name}} under {.path {file.path(path, 'R')}}." + ) + } + + # ---- 4. Check for rstudioapi / shiny / miniUI calls -------------------- + if (!.uta_uses_pkg(body_expr, "rstudioapi", ns)) { + ok <- .uta_confirm( + "The body of {.fn {fn_name}} does not call any {.pkg rstudioapi} function." + ) + if (!ok) { + cli::cli_alert_info("Cancelled, no addin was written.") + return(invisible(NULL)) + } + } + if (Interactive) { + uses_ui <- .uta_uses_pkg(body_expr, "shiny", ns) || + .uta_uses_pkg(body_expr, "miniUI", ns) + if (!uses_ui) { + ok <- .uta_confirm( + "{.arg Interactive} is {.code TRUE}, but the body of {.fn {fn_name}} does not call any {.pkg shiny} or {.pkg miniUI} function." + ) + if (!ok) { + cli::cli_alert_info("Cancelled, no addin was written.") + return(invisible(NULL)) + } + } + } + + # ---- 5. Write inst/rstudio/addins.dcf (new entry goes at the top) ------ + dcf_dir <- file.path(path, "inst", "rstudio") + dcf_file <- file.path(dcf_dir, "addins.dcf") + + # Already registered under the same Binding: do not add it twice + if (file.exists(dcf_file) && fn_name %in% .uta_read_bindings(dcf_file)) { + cli::cli_alert_info( + "{.fn {fn_name}} is already registered in {.path {dcf_file}}, nothing was added." + ) + return(invisible(dcf_file)) + } + + new_lines <- c( + paste0("Name: ", fn_name), + paste0("Description: ", desc), + paste0("Binding: ", fn_name), + paste0("Interactive: ", tolower(as.character(Interactive))) + ) + + old_lines <- character() + if (file.exists(dcf_file)) { + old_lines <- readLines(dcf_file, encoding = "UTF-8", warn = FALSE) + # Drop leading blank lines so no extra blank line precedes the new entry + while (length(old_lines) > 0L && !nzchar(trimws(old_lines[1L]))) { + old_lines <- old_lines[-1L] + } + } + + lines <- if (length(old_lines) > 0L) { + c(new_lines, "", old_lines) # separate entries with a blank line + } else { + new_lines + } + + dir.create(dcf_dir, recursive = TRUE, showWarnings = FALSE) + # Write UTF-8 bytes to avoid mojibake in non-UTF-8 locales + writeLines(enc2utf8(lines), dcf_file, useBytes = TRUE) + + cli::cli_alert_success("Wrote addin {.val {fn_name}}: {.path {dcf_file}}") + invisible(dcf_file) +} + + +# ============================ internal helpers ============================== + +# Parse NAMESPACE (it is itself parseable R code) +.uta_parse_namespace <- function(ns_file) { + exprs <- parse(ns_file, keep.source = FALSE, encoding = "UTF-8") + exports <- character() + export_patterns <- character() + imports_all <- character() + imports_from <- data.frame(pkg = character(), sym = character()) + + for (e in exprs) { + if (!is.call(e) || !is.name(e[[1L]])) { + next + } + fn <- as.character(e[[1L]]) + args <- vapply( + as.list(e)[-1L], + function(a) as.character(a)[1L], + character(1) + ) + switch( + fn, + export = exports <- c(exports, args), + exportPattern = export_patterns <- c(export_patterns, args), + import = imports_all <- c(imports_all, args), + importFrom = if (length(args) >= 2L) { + imports_from <- rbind( + imports_from, + data.frame(pkg = args[1L], sym = args[-1L]) + ) + } + ) + } + list( + exports = exports, + export_patterns = export_patterns, + imports_all = imports_all, + imports_from = imports_from + ) +} + +# Whether devtools::document() has been run: NAMESPACE carries a roxygen2 +# header and man/ contains at least one Rd file +.uta_is_documented <- function(path) { + header <- readLines(file.path(path, "NAMESPACE"), n = 1L, warn = FALSE) + has_header <- length(header) == 1L && + grepl("Generated by roxygen2", header, fixed = TRUE) + has_rd <- length(list.files(file.path(path, "man"), pattern = "\\.Rd$")) > 0L + has_header && has_rd +} + +# Walk every file under R/, find the assignment that defines fn_name and +# return its function body +.uta_find_fn_body <- function(fn_name, path) { + files <- list.files( + file.path(path, "R"), + pattern = "\\.[Rr]$", + full.names = TRUE + ) + for (f in files) { + exprs <- tryCatch( + parse(f, keep.source = FALSE, encoding = "UTF-8"), + error = function(e) NULL + ) + if (is.null(exprs)) { + next + } + for (e in exprs) { + if ( + is.call(e) && + length(e) == 3L && + is.name(e[[1L]]) && + as.character(e[[1L]]) %in% c("<-", "=", "<<-") + ) { + lhs <- e[[2L]] + if ( + (is.name(lhs) || is.character(lhs)) && + identical(as.character(lhs), fn_name) + ) { + rhs <- e[[3L]] + if (is.call(rhs) && identical(rhs[[1L]], as.name("function"))) { + return(rhs[[3L]]) # function(args) body + } + return(rhs) + } + } + } + } + NULL +} + +# Whether the body uses a package: pkg::, library()/requireNamespace(), or a +# symbol imported through NAMESPACE +.uta_uses_pkg <- function(body, pkg, ns) { + txt <- paste(deparse(body), collapse = "\n") + + if (grepl(sprintf("\\b%s:::?", pkg), txt)) { + return(TRUE) + } + if ( + grepl( + sprintf( + "\\b(library|require|requireNamespace|loadNamespace)\\(\\s*[\"']?%s\\b", + pkg + ), + txt + ) + ) { + return(TRUE) + } + + imported <- ns$imports_from$sym[ns$imports_from$pkg == pkg] + if (pkg %in% ns$imports_all && requireNamespace(pkg, quietly = TRUE)) { + imported <- union(imported, getNamespaceExports(pkg)) + } + any(all.names(body) %in% imported) +} + +# Warn and ask whether to continue; a non-interactive session cannot ask, so +# only warn and continue +.uta_confirm <- function(msg, .envir = parent.frame()) { + cli::cli_alert_warning(msg, .envir = .envir) + if (!rlang::is_interactive()) { + cli::cli_alert_info( + "Non-interactive session, cannot ask for confirmation; continuing." + ) + return(TRUE) + } + isTRUE(utils::askYesNo("Add this addin anyway?", default = FALSE)) +} + +# Read the Bindings already registered in addins.dcf +.uta_read_bindings <- function(dcf_file) { + con <- file(dcf_file, encoding = "UTF-8") + mat <- tryCatch(read.dcf(con, fields = "Binding"), error = function(e) NULL) + if (is.null(mat)) { + return(character()) + } + as.character(stats::na.omit(mat[, "Binding"])) +} diff --git a/R/standalone-caller_cli.R b/R/standalone-caller_cli.R index 5e1be1e..424cfc4 100644 --- a/R/standalone-caller_cli.R +++ b/R/standalone-caller_cli.R @@ -1,7 +1,7 @@ # --- # repo: WangLabCSU/rpkgkit # file: standalone-caller_cli.R -# last-updated: 2026-10-12 +# last-updated: 2026-11-01 # license: https://unlicense.org # imports: [cli, rlang] # --- @@ -9,7 +9,9 @@ # Retrieve caller name and add caller context to CLI functions. # # ## Changelog: -# +# * `add_caller_to_cli()`: the wrapper now takes `.envir = parent.frame()` and +# forwards it to the wrapped cli function, so `{}` interpolation resolves in +# the caller's environment instead of the wrapper's frame # # 2026-10-12: # * Added variable checking @@ -77,12 +79,12 @@ add_caller_to_cli <- function(cli_func, offset = 2L) { if (!is.function(cli_func)) { cli::cli_abort(message = c("x" = "`cli_func` must be a {.cls function}")) } - function(...) { + function(..., .envir = parent.frame()) { # offset = 1 because we are inside this anonymous wrapper function. # We look back 1 frame to find who called this wrapper. caller_name <- get_caller_name(offset = offset) - messages <- list(...) + messages <- list(..., .envir = .envir) if (length(messages) > 0L && is.character(messages[[1L]])) { # Construct the prefix: [caller]: diff --git a/R/standalone-colorful_cli.R b/R/standalone-colorful_cli.R index 61eeb4f..1c03cb7 100644 --- a/R/standalone-colorful_cli.R +++ b/R/standalone-colorful_cli.R @@ -1,7 +1,7 @@ # --- # repo: WangLabCSU/rpkgkit # file: standalone-colorful_cli.R -# last-updated: 2026-10-12 +# last-updated: 2026-11-01 # license: https://unlicense.org # imports: [cli] # --- @@ -9,6 +9,10 @@ # # ## Changelog: # +# 2026-11-01: +# * `add_colors_to_cli()`: the wrapper now takes `.envir = parent.frame()` and +# forwards it to the wrapped cli function, so `{}` interpolation resolves in +# the caller's environment instead of the wrapper's frame # # 2026-10-12: # * Added variable checking @@ -133,6 +137,14 @@ create_colorful_cli_env <- function( #' at creation time. The color theme is applied via \code{\link[cli]{cli_div}} with #' automatic cleanup via \code{\link[base]{on.exit}} to call \code{\link[cli]{cli_end}}. #' +#' The returned function takes a `.envir` argument (defaulting to +#' \code{\link[base]{parent.frame}}, i.e. the caller) and passes it on to the +#' wrapped CLI function, so glue-style interpolation such as +#' \code{"Hello, {name}"} is resolved in the environment that called the wrapper +#' and not in the wrapper's own frame. Pass `.envir` explicitly to interpolate in +#' another environment (for example the frame of the function that created the +#' wrapper). +#' #' @examples #' \donttest{ #' # Create a color-enabled version of cli_alert_info @@ -165,8 +177,8 @@ add_colors_to_cli <- function( if (!is.function(cli_func)) { cli::cli_abort(message = "`cli_func` must be a {.cls function}") } - function(...) { - messages <- list(...) + function(..., .envir = parent.frame()) { + messages <- list(..., .envir = .envir) cli::cli_div(theme = cli_theme) on.exit(cli::cli_end()) do.call(what = cli_func, args = messages) diff --git a/R/standalone-ts_cli.R b/R/standalone-ts_cli.R index 6191655..72dec50 100644 --- a/R/standalone-ts_cli.R +++ b/R/standalone-ts_cli.R @@ -1,7 +1,7 @@ # --- # repo: WangLabCSU/rpkgkit # file: standalone-ts_cli.R -# last-updated: 2026-10-12 +# last-updated: 2026-11-01 # license: https://unlicense.org # imports: [cli] # --- @@ -10,6 +10,13 @@ # # ## Changelog: # +# 2026-11-01: +# * `add_timestamp_to_cli()`: the timestamp is now evaluated by the wrapper +# (`time_stamp()` is called directly) instead of being injected as +# `"{time_stamp()}"` glue syntax. cli interpolates `{}` in the caller's +# frame, so composing this wrapper with another one that forwards `.envir` +# (e.g. `add_colors_to_cli()`) failed with "could not find function +# time_stamp" # # 2026-10-12: # * Added variable checking @@ -36,9 +43,12 @@ #' #' @details #' This function uses \code{\link{force}} to ensure the CLI function is evaluated -#' at creation time. The timestamp is generated using a \code{time_stamp()} function -#' which should be available in the execution environment and is inserted using -#' cli's glue-like syntax \code{"{ }"}. +#' at creation time. The timestamp is produced by calling \code{time_stamp()} +#' inside the wrapper and is prepended to the message before the wrapped CLI +#' function is called. It therefore does not depend on \code{time_stamp()} being +#' visible in the environment cli interpolates \code{"{ }"} expressions in, and +#' the wrapper can be safely composed with other wrappers that forward +#' \code{.envir} (such as \code{\link{add_colors_to_cli}}). #' #' @examples #' \donttest{ @@ -65,7 +75,10 @@ add_timestamp_to_cli <- function( function(...) { messages <- list(...) if (length(messages) > 0L && is.character(messages[[1L]])) { - messages[[1L]] <- paste0("{time_stamp()}", messages[[1L]]) + # Evaluated here and not through cli's `{}` interpolation: cli resolves + # `{}` in `.envir`, which is the caller's frame (possibly several + # wrappers further out), where `time_stamp()` need not exist. + messages[[1L]] <- paste0(time_stamp(), messages[[1L]]) } do.call(what = cli_func, args = messages) } diff --git a/README.Rmd b/README.Rmd index 6a84d66..3915f2f 100644 --- a/README.Rmd +++ b/README.Rmd @@ -90,6 +90,14 @@ It's recommended to use following packages together with `rpkgkit`: - [`usethis`](https://usethis.r-lib.org/): manage package metadata. - [`devtools`](https://devtools.r-lib.org/): build and check package. +## Addin + +After v0.1.23, `rpkgkit` ships an addin that can be used in RStudio. It's +available in the `Addins` menu, and can be accessed by pressing `Ctrl+Shift+P` +(Windows/Linux) or `Cmd+Shift+P` (macOS). + +If you want to use addins in Positron, you can use [Positron R Wizard](https://github.com/ntluong95/positron-r-wizard.git) extension. + ## AI skills `rpkgkit` ships an agent skill that tells coding agents when to reach for diff --git a/README.md b/README.md index 6909dd3..a1a1e39 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,15 @@ It’s recommended to use following packages together with `rpkgkit`: - [`usethis`](https://usethis.r-lib.org/): manage package metadata. - [`devtools`](https://devtools.r-lib.org/): build and check package. +## Addin + +After v0.1.23, `rpkgkit` ships an addin that can be used in RStudio. +It’s available in the `Addins` menu, and can be accessed by pressing +`Ctrl+Shift+P` (Windows/Linux) or `Cmd+Shift+P` (macOS). + +If you want to use addins in Positron, you can use [Positron R +Wizard](https://github.com/ntluong95/positron-r-wizard.git) extension. + ## AI skills `rpkgkit` ships an agent skill that tells coding agents when to reach diff --git a/_pkgdown.yml b/_pkgdown.yml index 8412d1b..1298cc0 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -71,6 +71,7 @@ reference: - package_lost_glue_brace - package_print_and_cat - package_unmatched_nocov_marker + - package_fn_arg_path - flir_fix - inquire_standalone - package_func_arg_explicit @@ -91,10 +92,12 @@ reference: - use_workflow_test_branch - use_workflow_version_update - use_zzz + - use_tidy_addin - current_packages - detect_lost_glue_brace - detect_print_and_cat - detect_unmatched_nocov_marker + - detect_fn_arg_path - imported_functions - make_func_arg_explicit - make_func_call_explicit diff --git a/inst/rstudio/addins.dcf b/inst/rstudio/addins.dcf new file mode 100644 index 0000000..64b3ff9 --- /dev/null +++ b/inst/rstudio/addins.dcf @@ -0,0 +1,49 @@ +Name: package_func_arg_explicit +Description: Make all function arguments explicit in R/ folder. +Binding: package_func_arg_explicit +Interactive: false + +Name: make_func_arg_explicit +Description: Make all function arguments explicit in the active file. +Binding: make_func_arg_explicit +Interactive: false + +Name: package_lost_glue_brace +Description: Detect all possible unmatched glue(cli) braces in R/ folder. +Binding: package_lost_glue_brace +Interactive: false + +Name: detect_lost_glue_brace +Description: Detect all possible unmatched glue(cli) braces in the active file. +Binding: detect_lost_glue_brace +Interactive: false + +Name: package_print_and_cat +Description: Detect CRAN-unsafe print() and cat() calls in R/ folder. +Binding: package_print_and_cat +Interactive: false + +Name: detect_print_and_cat +Description: Detect CRAN-unsafe print() and cat() calls in the active file. +Binding: detect_print_and_cat +Interactive: false + +Name: package_fn_arg_path +Description: Detect default paths in arguments of exported functions across the package. +Binding: package_fn_arg_path +Interactive: false + +Name: detect_fn_arg_path +Description: Detect default paths in arguments of exported functions in the active file. +Binding: detect_fn_arg_path +Interactive: false + +Name: package_unmatched_nocov_marker +Description: Detect unmatched # nocov start / # nocov end markers in R/ folder. +Binding: package_unmatched_nocov_marker +Interactive: false + +Name: check_pkgdown_reference +Description: Check that every exported function is listed in the _pkgdown.yml reference. +Binding: check_pkgdown_reference +Interactive: false diff --git a/inst/translations/README.es.md b/inst/translations/README.es.md index 96ff9b2..41e9228 100644 --- a/inst/translations/README.es.md +++ b/inst/translations/README.es.md @@ -1,11 +1,9 @@ # rpkgkit sitio web de rpkgkit -[![Lifecycle:stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html#stable) -[![Project Status: Active - The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) [![CRAN-status](https://www.r-pkg.org/badges/version/rpkgkit)](https://CRAN.R-project.org/package=rpkgkit) +[![R-universe-version](https://wanglabcsu.r-universe.dev/rpkgkit/badges/version)](https://wanglabcsu.r-universe.dev/rpkgkit) [![R-CMD-check](https://github.com/WangLabCSU/rpkgkit/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/WangLabCSU/rpkgkit/actions/workflows/R-CMD-check.yaml) -[![Devel-version](https://img.shields.io/badge/devel%20version-0.1.16-blue.svg)](https://github.com/WangLabCSU/rpkgkit) [![Codesize](https://img.shields.io/github/languages/code-size/WangLabCSU/rpkgkit.svg)](https://github.com/WangLabCSU/rpkgkit) [![Codecov-testcoverage](https://codecov.io/gh/WangLabCSU/rpkgkit/graph/badge.svg)](https://app.codecov.io/gh/WangLabCSU/rpkgkit) [![Ask-DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/WangLabCSU/rpkgkit) @@ -13,14 +11,13 @@ [![English](https://img.shields.io/badge/README-English-blue)](../../README.md) [![Español](https://img.shields.io/badge/README-Espa%C3%B1ol-blue)]() [![简体中文](https://img.shields.io/badge/README-%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-blue)](README.zh-cn.md) -[![Last-commit](https://img.shields.io/github/last-commit/WangLabCSU/rpkgkit.svg)](https://github.com/WangLabCSU/rpkgkit/commits/main) ## Resumen `rpkgkit` ofrece utilidades para crear y mantener paquetes de R. Sus funciones cubren tareas habituales, como gestionar scripts independientes, mantener `NEWS.md`, modernizar código R, configurar la infraestructura de un paquete y mantener archivos README. -Muchas funciones detectan el contexto del archivo activo en RStudio y Positron, por lo que a menudo se puede omitir la ruta del archivo. +Muchas funciones detectan el contexto del archivo activo en RStudio y Positron (2026.10.1 o posterior), por lo que a menudo se puede omitir la ruta del archivo. ## Instalación @@ -39,7 +36,7 @@ install.packages( ) ``` -O instálala desde GitHub: +O instálala desde GitHub (recomendado): ```r pak::pak("WangLabCSU/rpkgkit") @@ -55,6 +52,31 @@ El sitio web del paquete organiza ejemplos detallados y listos para usar por tar - [Configuración y mantenimiento de paquetes](https://wanglabcsu.github.io/rpkgkit/articles/pkg_maintain.html): configura la infraestructura del paquete, incorpora código con licencias permisivas y gestiona archivos de exclusión. - [Herramientas para README y documentación](https://wanglabcsu.github.io/rpkgkit/articles/readme_and_doc.html): crea traducciones de README e inserta o genera insignias. +Se recomienda usar los siguientes paquetes junto con `rpkgkit`: + +- [`pkgdown`](https://pkgdown.r-lib.org/) / [`pkgdown.offline`](https://nanx.me/pkgdown.offline/): genera el sitio web del paquete. +- [`pkgload`](https://pkgload.r-lib.org/): carga el código fuente del paquete. +- [`flir`](https://flir.etiennebacher.com/) / [`jarl`](https://jarl.etiennebacher.com/) / [`lintr`](https://lintr.r-lib.org/): analiza y corrige el código fuente. +- [`air`](https://posit-dev.github.io/air/): formatea el código fuente. +- [`usethis`](https://usethis.r-lib.org/): gestiona los metadatos del paquete. +- [`devtools`](https://devtools.r-lib.org/): construye y comprueba el paquete. + +## Addin + +A partir de la v0.1.23, `rpkgkit` incluye un addin que se puede usar en RStudio. Está disponible en el menú `Addins` y también se puede abrir con `Ctrl+Shift+P` (Windows/Linux) o `Cmd+Shift+P` (macOS). + +Si quieres usar addins en Positron, puedes usar la extensión [Positron R Wizard](https://github.com/ntluong95/positron-r-wizard.git). + +## Habilidades de IA + +`rpkgkit` incluye una skill para agentes que indica a los agentes de programación cuándo deben usar `rpkgkit` y cómo llamarlo. Sigue el formato [Agent Skills](https://skills.sh), por lo que funciona con Claude Code, Codex, Cursor, Positron y otros agentes compatibles: + +```bash +npx skills add WangLabCSU/rpkgkit --skill rpkgkit +``` + +Añade `-g` para instalarla en todos los proyectos y `-a ` para omitir la pregunta del agente. El código fuente de la skill está en [`skills/rpkgkit/`](https://github.com/WangLabCSU/rpkgkit/tree/main/skills/rpkgkit). + ## Agradecimientos Agradecemos a las siguientes personas y proyectos: diff --git a/inst/translations/README.zh-cn.md b/inst/translations/README.zh-cn.md index 11f9319..a052059 100644 --- a/inst/translations/README.zh-cn.md +++ b/inst/translations/README.zh-cn.md @@ -1,11 +1,9 @@ # rpkgkit rpkgkit 网站 -[![Lifecycle:stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html#stable) -[![Project Status: Active - The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) [![CRAN-status](https://www.r-pkg.org/badges/version/rpkgkit)](https://CRAN.R-project.org/package=rpkgkit) +[![R-universe-version](https://wanglabcsu.r-universe.dev/rpkgkit/badges/version)](https://wanglabcsu.r-universe.dev/rpkgkit) [![R-CMD-check](https://github.com/WangLabCSU/rpkgkit/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/WangLabCSU/rpkgkit/actions/workflows/R-CMD-check.yaml) -[![Devel-version](https://img.shields.io/badge/devel%20version-0.1.16-blue.svg)](https://github.com/WangLabCSU/rpkgkit) [![Codesize](https://img.shields.io/github/languages/code-size/WangLabCSU/rpkgkit.svg)](https://github.com/WangLabCSU/rpkgkit) [![Codecov-testcoverage](https://codecov.io/gh/WangLabCSU/rpkgkit/graph/badge.svg)](https://app.codecov.io/gh/WangLabCSU/rpkgkit) [![Ask-DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/WangLabCSU/rpkgkit) @@ -13,14 +11,13 @@ [![English](https://img.shields.io/badge/README-English-blue)](../../README.md) [![Español](https://img.shields.io/badge/README-Espa%C3%B1ol-blue)](README.es.md) [![简体中文](https://img.shields.io/badge/README-%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87-blue)]() -[![Last-commit](https://img.shields.io/github/last-commit/WangLabCSU/rpkgkit.svg)](https://github.com/WangLabCSU/rpkgkit/commits/main) ## 概览 `rpkgkit` 为创建和维护 R 包提供实用工具。其函数覆盖独立脚本管理、`NEWS.md` 维护、R 源代码现代化、包基础设施配置和 README 文件维护等常见开发任务。 -多数函数可以检测 RStudio 和 Positron 中的活动文件上下文,因此通常可以省略文件路径。 +多数函数可以检测 RStudio 和 Positron(2026.10.1 或更高版本)中的活动文件上下文,因此通常可以省略文件路径。 ## 安装 @@ -39,7 +36,7 @@ install.packages( ) ``` -或从 GitHub 安装: +或从 GitHub 安装(推荐): ```r pak::pak("WangLabCSU/rpkgkit") @@ -55,6 +52,31 @@ pak::pak("WangLabCSU/rpkgkit") - [包设置与维护](https://wanglabcsu.github.io/rpkgkit/articles/pkg_maintain.html):配置包基础设施、引入宽松许可证代码,以及管理忽略文件。 - [README 与文档工具](https://wanglabcsu.github.io/rpkgkit/articles/readme_and_doc.html):创建 README 翻译文件,以及插入或生成徽章。 +建议将以下包与 `rpkgkit` 配合使用: + +- [`pkgdown`](https://pkgdown.r-lib.org/) / [`pkgdown.offline`](https://nanx.me/pkgdown.offline/):生成包网站。 +- [`pkgload`](https://pkgload.r-lib.org/):加载包源代码。 +- [`flir`](https://flir.etiennebacher.com/) / [`jarl`](https://jarl.etiennebacher.com/) / [`lintr`](https://lintr.r-lib.org/):检查并修复源代码。 +- [`air`](https://posit-dev.github.io/air/):格式化源代码。 +- [`usethis`](https://usethis.r-lib.org/):管理包元数据。 +- [`devtools`](https://devtools.r-lib.org/):构建和检查包。 + +## Addin + +自 v0.1.23 起,`rpkgkit` 附带了一个可在 RStudio 中使用的 addin。它位于 `Addins` 菜单中,也可以通过 `Ctrl+Shift+P`(Windows/Linux)或 `Cmd+Shift+P`(macOS)访问。 + +如果想在 Positron 中使用 addin,可以试试 [Positron R Wizard](https://github.com/ntluong95/positron-r-wizard.git) 扩展。 + +## AI 技能 + +`rpkgkit` 附带一个 agent skill,告诉编码智能体何时应当使用 `rpkgkit` 以及如何调用它。它遵循 [Agent Skills](https://skills.sh) 规范,因此可用于 Claude Code、Codex、Cursor、Positron 以及其他兼容的智能体: + +```bash +npx skills add WangLabCSU/rpkgkit --skill rpkgkit +``` + +加上 `-g` 可将其安装到所有项目,加上 `-a ` 可跳过智能体选择提示。技能源代码位于 [`skills/rpkgkit/`](https://github.com/WangLabCSU/rpkgkit/tree/main/skills/rpkgkit)。 + ## 致谢 感谢以下人员和项目: diff --git a/man/detect_fn_arg_path.Rd b/man/detect_fn_arg_path.Rd new file mode 100644 index 0000000..4c8c5ba --- /dev/null +++ b/man/detect_fn_arg_path.Rd @@ -0,0 +1,86 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/11A_package_fn_arg_path.R, +% R/11_detect_fn_arg_path.R +\name{package_fn_arg_path} +\alias{package_fn_arg_path} +\alias{detect_fn_arg_path} +\title{Detect Default Paths in Exported Function Arguments} +\usage{ +package_fn_arg_path( + path = NULL, + arg_pattern = "path|file|filename", + allow = "NULL", + dirs = "R", + verbose = TRUE, + ... +) + +detect_fn_arg_path( + path = NULL, + arg_pattern = "path|file|filename", + exports = NULL, + export_patterns = character(), + allow = "NULL", + verbose = TRUE, + ... +) +} +\arguments{ +\item{path}{For \code{detect_fn_arg_path()}: path to an \R file. If +\code{NULL} and RStudio is available, the active document is used. + +For \code{package_fn_arg_path()}: root directory of an \R package. +Defaults to the current directory.} + +\item{arg_pattern}{Regular expression matched (unanchored) against argument +names. Use e.g. \code{"^(path|file|filename)$"} to avoid matching \code{profile}.} + +\item{allow}{Character vector of default-value expressions (as written in +the source, whitespace trimmed) that are acceptable. +Defaults to \code{"NULL"}.} + +\item{dirs}{Package-relative directories scanned by +\code{package_fn_arg_path()}.} + +\item{verbose}{Whether to emit results to the console.} + +\item{...}{Unused.} + +\item{exports}{Character vector of exported function names.} + +\item{export_patterns}{Character vector of regular expressions, as in +\code{exportPattern()} in \code{NAMESPACE}.} +} +\value{ +Invisibly returns \code{TRUE} if no offending defaults are found, +\code{FALSE} otherwise. +} +\description{ +CRAN does not allow exported functions to default a path-like argument to a +concrete location. This checker parses R source, finds exported functions, +and reports every argument whose name matches \code{arg_pattern} and whose +default value is not in \code{allow} (by default only \code{NULL}; an argument with +no default is always fine). Each hit is reported with file, line, column and +a caret (\verb{^^^^}) marker under \code{arg = default}. +} +\section{Single file vs package scope}{ + +\describe{ +\item{\code{detect_fn_arg_path()}}{Operates on one \R file. Use +\code{exports} / \code{export_patterns} to say which top-level functions +count as exported; when \code{exports} is \code{NULL} and no patterns are +given, every top-level function in the file is checked.} +\item{\code{package_fn_arg_path()}}{Checks that \code{path} is an \R +package, reads exports from \code{NAMESPACE}, then scans \code{.R} files +under \code{dirs} (default \code{"R"}).} +} +} + +\examples{ +\donttest{ +file <- tempfile(fileext = ".R") +writeLines('read_it <- function(path = "~/data.csv", n = 1) NULL', file) +detect_fn_arg_path(file) +} + +} diff --git a/man/rpkgkit-package.Rd b/man/rpkgkit-package.Rd index 49724b7..42351ec 100644 --- a/man/rpkgkit-package.Rd +++ b/man/rpkgkit-package.Rd @@ -20,7 +20,7 @@ MIT + file LICENSE \seealso{ Useful links: \itemize{ - \item /tmp/RtmpoUp5qA + \item \url{https://github.com/Exceret/rpkgkit} \item Report bugs at \url{https://github.com/WangLabCSU/rpkgkit/issues} } diff --git a/man/use_tidy_addin.Rd b/man/use_tidy_addin.Rd new file mode 100644 index 0000000..45d704c --- /dev/null +++ b/man/use_tidy_addin.Rd @@ -0,0 +1,33 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/53_use_tidy_addin.R +\name{use_tidy_addin} +\alias{use_tidy_addin} +\title{Create an RStudio Addin registration entry for a package function} +\usage{ +use_tidy_addin(fn_name, desc, Interactive = FALSE, path = NULL) +} +\arguments{ +\item{fn_name}{Name of the function (it must already be exported in +\code{NAMESPACE}).} + +\item{desc}{Description of the addin.} + +\item{Interactive}{Whether this is an interactive addin (maps to the +\code{Interactive} field of the dcf file).} + +\item{path}{Root directory of the R package.} +} +\value{ +Invisibly, the path of the dcf file that was written (\code{NULL} if the +operation was cancelled). +} +\description{ +\code{use_tidy_addin()} writes an entry into \code{inst/rstudio/addins.dcf}, which +makes an exported function available from the RStudio Addins menu. +} +\examples{ +\dontrun{ +# Inside a package that exports `my_addin()` +use_tidy_addin("my_addin", "Open my Shiny gadget", Interactive = TRUE) +} +} diff --git a/man/use_zzz.Rd b/man/use_zzz.Rd index ec3c289..a13ddeb 100644 --- a/man/use_zzz.Rd +++ b/man/use_zzz.Rd @@ -6,7 +6,7 @@ \usage{ use_zzz( path = NULL, - file_name = paste0(get_package_name(path = path), "-package.R"), + file_name = NULL, overwrite = FALSE, open = rlang::is_interactive(), ... diff --git a/skills/rpkgkit/SKILL.md b/skills/rpkgkit/SKILL.md index 2d6b758..f4bea16 100644 --- a/skills/rpkgkit/SKILL.md +++ b/skills/rpkgkit/SKILL.md @@ -1,6 +1,6 @@ --- name: rpkgkit -description: Use rpkgkit functions to create and maintain R packages when the task involves qualifying package calls with pkg::, detecting CRAN-unsafe print()/cat(), lost glue braces or unmatched # nocov start / # nocov end markers, modernizing R syntax (base/magrittr pipes, integer L suffix, non-ASCII literals, \\( lambdas, knitr chunk headers), editing or displaying NEWS.md, creating r-lib standalone files, configuring DESCRIPTION fields, .Rbuildignore/.clangd/zzz.R, vendoring upstream code, generating GitHub Actions workflows (R-CMD-check including Rust/extendr builds, version bump, branch sync), or generating multilingual README translations and badges. +description: Use rpkgkit functions to create and maintain R packages when the task involves qualifying package calls with pkg::, detecting CRAN-unsafe print()/cat(), lost glue braces, unmatched # nocov start / # nocov end markers or path-like arguments of exported functions that default to a concrete location, modernizing R syntax (base/magrittr pipes, integer L suffix, non-ASCII literals, \\( lambdas, knitr chunk headers), editing or displaying NEWS.md, creating r-lib standalone files, configuring DESCRIPTION fields, .Rbuildignore/.clangd/zzz.R, registering RStudio addins in inst/rstudio/addins.dcf, vendoring upstream code, generating GitHub Actions workflows (R-CMD-check including Rust/extendr builds, version bump, branch sync), or generating multilingual README translations and badges. --- # rpkgkit @@ -22,10 +22,13 @@ Use this skill when the request touches R package housekeeping: - Making function calls explicit (`pkg::fun()`) or arguments explicit (`arg = value`) - Detecting or fixing CRAN-unsafe `print()`/`cat()`, or lost `{}` in `glue`/`cli` - Checking the `# nocov start` / `# nocov end` markers of a file or package +- Finding path-like arguments of exported functions that default to a concrete + location, which CRAN rejects - Converting pipes, `function()` ↔ `\(`, integer literals, non-ASCII literals, Rmd chunk headers - Adding, showing, or formatting `NEWS.md` entries - Creating or validating r-lib style `standalone-*.R` files - Adding DESCRIPTION fields (`URL`, `BugReports`, `Depends: R (>= ...)`), `.clangd`, `(pkg)-package.R` +- Registering an exported function as an RStudio addin (`inst/rstudio/addins.dcf`) - Vendoring upstream code, or generating `.Rbuildignore` patterns - Multilingual README translations, AI-translation badges, README badges, Rmd YAML headers - Formatting with air/flir, or checking `_pkgdown.yml` coverage @@ -42,8 +45,9 @@ CRAN submission mechanics beyond the functions listed here. `convert_pipe`, `optimize_rmd_yaml` act on one file. The matching `package_*` function walks the package. `dirs` defaults to `c("R", "tests/testthat")` for `package_lost_glue_brace()` and `package_print_and_cat()`, and to `"R"` for - `package_unmatched_nocov_marker()` and the converters; pass `dirs` to widen it. - Choose the package-level function whenever more than one file is involved. + `package_unmatched_nocov_marker()`, `package_fn_arg_path()` and the + converters; pass `dirs` to widen it. Choose the package-level function + whenever more than one file is involved. 3. **Results are reported with `cli` and returned invisibly.** Wrap calls in `invisible()`-tolerant code; do not assert on a visible return value. Use `verbose = TRUE` (default on most functions) to keep the report. @@ -64,6 +68,7 @@ rpkgkit::package_func_arg_explicit() # add arg = for non-leading formals rpkgkit::package_lost_glue_brace() # report lost {} in glue/cli rpkgkit::package_print_and_cat(fix = TRUE) # print()/cat() -> message() rpkgkit::package_unmatched_nocov_marker() # report unmatched nocov markers +rpkgkit::package_fn_arg_path() # report `path = "."` on exported functions rpkgkit::package_convert_pipe(direction = "to_base") rpkgkit::package_convert_int_literals() rpkgkit::air_format() # format last @@ -113,6 +118,7 @@ rpkgkit::use_workflow_version_update() # version bump workflow + local ac rpkgkit::use_workflow_rust_compatible_check() # R-CMD-check that builds Rust code rpkgkit::use_workflow_test_branch() # sync main -> test after check passes rpkgkit::check_pkgdown_reference() # every export present in _pkgdown.yml +rpkgkit::use_tidy_addin("my_addin", "Do something") # inst/rstudio/addins.dcf entry ``` The three `use_workflow_*()` functions copy bundled templates from `inst/actions/` @@ -124,6 +130,31 @@ packages: it installs a Rust toolchain and the `x86_64-pc-windows-gnu` target, without which the MSVC default cannot link against Rtools and the check ends in a WARNING. +## Workflow: RStudio addins + +```r +rpkgkit::use_tidy_addin("my_addin", "Do something") # Interactive: FALSE +rpkgkit::use_tidy_addin("my_gadget", "Open a gadget", Interactive = TRUE) +``` + +`use_tidy_addin()` writes one record (`Name`, `Description`, `Binding`, +`Interactive`) on top of `inst/rstudio/addins.dcf`, creating `inst/rstudio/` when +needed, and returns the dcf path invisibly. It aborts when `path` is not a package +or when the function is not exported in `NAMESPACE`, and it skips a `Binding` +that is already registered instead of adding it twice. It also warns when the +function body calls no `rstudioapi` function, or, for `Interactive = TRUE`, no +`shiny`/`miniUI` function, since such an entry is unlikely to work as an addin; a +non-interactive session cannot confirm the warning and only continues. Requires +`desc`. + +`rpkgkit` ships its own addins, all read-only, in `inst/rstudio/addins.dcf`: +`detect_lost_glue_brace`, `package_lost_glue_brace`, `detect_print_and_cat`, +`package_print_and_cat`, `detect_fn_arg_path`, `package_fn_arg_path`, +`package_unmatched_nocov_marker` and `check_pkgdown_reference`. The `detect_*` +entries run on the active editor, the package-wide ones on the working directory. +Addins are an RStudio feature; Positron needs an extension such as Positron R +Wizard. + ## Workflow: README, badges, Rmd ```r diff --git a/skills/rpkgkit/references/function-reference.md b/skills/rpkgkit/references/function-reference.md index dc5f90c..fa65f2c 100644 --- a/skills/rpkgkit/references/function-reference.md +++ b/skills/rpkgkit/references/function-reference.md @@ -22,6 +22,7 @@ document, falling back to the working directory. Source files are under `R/`. | `make_func_arg_explicit(path = NULL, skip_functions = NULL, ...)` | `19_make_func_arg_explicit.R` | Inserts `arg =` using parse data; leaves all other text untouched. | | `detect_lost_glue_brace(path = NULL, verbose = TRUE, ...)` | `14_detect_lost_glue_brace.R` | Finds unbalanced `{}` inside `glue()`/`cli` expressions. | | `detect_print_and_cat(path = NULL, fix = FALSE, pattern_fn_names = DEFAULT_PATTERN_FN_NAMES, replace_default_pattern = FALSE, include_s3 = TRUE, include_refs = FALSE, verbose = TRUE, ...)` | `18_detect_print_and_cat.R` | Reports CRAN-unsafe `print()`/`cat()`; `fix = TRUE` rewrites them to `message()`. | +| `detect_fn_arg_path(path = NULL, arg_pattern = "path\|file\|filename", exports = NULL, export_patterns = character(), allow = "NULL", verbose = TRUE, ...)` | `11_detect_fn_arg_path.R` | Reports exported `name <- function()` formals whose name matches `arg_pattern` and whose default is not in `allow`; shared Rd page with `package_fn_arg_path()`. | | `detect_unmatched_nocov_marker(path = NULL, verbose = TRUE, ...)` | `24_detect_unmatched_nocov_marker.R` | Textual scan of the `# nocov start` / `# nocov end` comments (strings and roxygen lines included by design). Reports every marker after the first of its kind, a start or an end without a counterpart, and an end before the start, each with line and column plus a caret. An unclosed start matters because `covr::package_coverage()` aborts on it. Read-only. | | `rename_func(path = NULL, style = c("snake_case", "camelCase", "PascalCase", "google"), num_to_word = c(for = 4, to = 2), ...)` | `15_rename_func.R` | Renames function definitions in one file. | | `convert_func_syntax(path = NULL, direction = c("to_lambda", "to_explicit"), ...)` | `16_convert_func_syntax.R` | `function()` ⇄ `\(`. | @@ -41,6 +42,7 @@ These share an Rd page with their single-file counterpart (`@rdname`/`@describeI | `package_func_arg_explicit(path = NULL, skip_functions = NULL, ...)` | `19A_package_func_arg_explicit.R` | Walks every `R/*.R` file. | | `package_lost_glue_brace(path = NULL, dirs = c("R", "tests/testthat"), test_included = lifecycle::deprecated(), ...)` | `14A_package_lost_glue_brace.R` | Multi-directory scan; reports file and line. | | `package_print_and_cat(path = NULL, dirs = c("R", "tests/testthat"), test_included = lifecycle::deprecated(), fix = FALSE, ...)` | `18A_package_print_and_cat.R` | Multi-directory scan, optional fix. | +| `package_fn_arg_path(path = NULL, arg_pattern = "path\|file\|filename", allow = "NULL", dirs = "R", verbose = TRUE, ...)` | `11A_package_fn_arg_path.R` | Reads exports from `NAMESPACE` (including `exportPattern`), then scans `dirs`; `...` must be empty. | | `package_unmatched_nocov_marker(path = NULL, dirs = "R", verbose = TRUE)` | `24A_package_unmatched_nocov_marker.R` | Same rules as the single-file version, reported per file with `file: line` and the caret hint. Scans only `R/` unless `dirs` says otherwise; no `test_included` argument. Read-only. | | `package_convert_int_literals(path = NULL, dirs = "R", recursive = TRUE, exclude = c("RcppExports.R", "extendr-wrappers.R"), ...)` | `20A_package_convert_int_literals.R` | Batch conversion. | | `package_convert_pipe(path = NULL, direction = c("to_base", "to_magrittr"), dirs = "R", recursive = TRUE, ...)` | `21A_package_convert_pipe.R` | Batch conversion. | @@ -74,7 +76,8 @@ These share an Rd page with their single-file counterpart (`@rdname`/`@describeI | `use_url(url = NULL, pkgdown_url = NULL, path = NULL, ...)` | `49_use_url.R` | Writes `URL`; defaults to the git remote. | | `use_bugreports(url = NULL, path = NULL, ...)` | `50_use_bugreports.R` | Writes `BugReports`. | | `use_clangd(path = NULL, include = c("Rcpp", "RcppEigen", "RcppArmadillo"), overwrite = FALSE, open = rlang::is_interactive(), ...)` | `51_use_clangd.R` | Creates `.clangd`. | -| `use_zzz(path = NULL, file_name = paste0(get_package_name(path = path), "-package.R"), overwrite = FALSE, open = rlang::is_interactive(), ...)` | `45_use_zzz.R` | Creates `R/-package.R` from `inst/R_template/zzz_template.R`. | +| `use_zzz(path = NULL, file_name = NULL, overwrite = FALSE, open = rlang::is_interactive(), ...)` | `45_use_zzz.R` | Creates `R/-package.R` from `inst/R_template/zzz_template.R`; `file_name = NULL` resolves to `-package.R` inside the function. | +| `use_tidy_addin(fn_name, desc, Interactive = FALSE, path = NULL)` | `53_use_tidy_addin.R` | Prepend a record to `inst/rstudio/addins.dcf`; requires the function to be exported in `NAMESPACE`, skips an already registered `Binding`, warns when the body calls no `rstudioapi` (or, with `Interactive = TRUE`, no `shiny`/`miniUI`) function. Requires `desc`. | | `use_vendor(pkg, ..., branch = "main", path = NULL)` | `43_use_vendor.R` | Vendors upstream source into `inst/vendor/`, writes provenance and license, records vendor version and imports. | | `use_workflow_version_update(path = NULL, overwrite = FALSE, color = "blue", ...)` | `42_use_workflow_version_update.R` | Generates the version bump GitHub Actions workflow. | | `use_workflow_test_branch(path = NULL, overwrite = FALSE)` | `42B_use_workflow_test_branch.R` | Generates the `main` → `test` sync workflow. | diff --git a/tests/testthat/standalone-test.R b/tests/testthat/standalone-test.R new file mode 100644 index 0000000..e69de29 diff --git a/tests/testthat/test-add_caller_to_cli.R b/tests/testthat/test-add_caller_to_cli.R index f289b41..64c7dfb 100644 --- a/tests/testthat/test-add_caller_to_cli.R +++ b/tests/testthat/test-add_caller_to_cli.R @@ -17,7 +17,9 @@ test_that("add_caller_to_cli prepends caller name to character message", { test_that("add_caller_to_cli does not modify message when no arguments", { captured <- NULL - mock_cli <- function(...) { + # `add_caller_to_cli()` always forwards `.envir`, so the mock mirrors the + # signature of the cli functions it wraps and keeps `.envir` out of `...` + mock_cli <- function(..., .envir = parent.frame()) { captured <<- list(...) } diff --git a/tests/testthat/test-colorful_cli.R b/tests/testthat/test-colorful_cli.R index d272991..cb79d6d 100644 --- a/tests/testthat/test-colorful_cli.R +++ b/tests/testthat/test-colorful_cli.R @@ -16,9 +16,21 @@ test_that("combined cli env works", { cli::cli_alert_success )) - powered_cli_alert_success("{.red This is a red alert.}") + # The timestamp must still be resolvable when the color wrapper forwards + # `.envir` down to the timestamp wrapper + msg <- NULL + withCallingHandlers( + powered_cli_alert_success("{.red This is a red alert.}"), + message = function(m) { + msg <<- conditionMessage(m) + invokeRestart("muffleMessage") + } + ) + + expect_match(msg, "\\[\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}\\]") + expect_match(msg, "This is a red alert") cli_cyan_h1 <- add_colors_to_cli(add_timestamp_to_cli(cli::cli_h1)) - cli_cyan_h1("{.cyan This is a cyan header}") + expect_message(cli_cyan_h1("{.cyan This is a cyan header}"), "cyan header") }) diff --git a/tests/testthat/test-detect_fn_arg_path.R b/tests/testthat/test-detect_fn_arg_path.R new file mode 100644 index 0000000..1468982 --- /dev/null +++ b/tests/testthat/test-detect_fn_arg_path.R @@ -0,0 +1,285 @@ +# --------------------------------------------------------------------------- +# detect_fn_arg_path() / scan_fn_arg_path() / report_fn_arg_hits() +# --------------------------------------------------------------------------- + +test_that("detect_fn_arg_path returns TRUE when no default path is found", { + file <- withr::local_tempfile( + lines = c( + "read_it <- function(path = NULL, n = 1) NULL", + "write_it <- function(x, file) NULL" + ), + fileext = ".R" + ) + + expect_true(detect_fn_arg_path(file, verbose = FALSE)) +}) + +test_that("detect_fn_arg_path flags a default path and returns FALSE", { + file <- withr::local_tempfile( + lines = 'read_it <- function(path = "~/data.csv", n = 1) NULL', + fileext = ".R" + ) + + expect_false(detect_fn_arg_path(file, verbose = FALSE)) +}) + +test_that("scan_fn_arg_path records fn, arg, default and position", { + file <- withr::local_tempfile( + lines = 'read_it <- function(n = 1, path = "~/data.csv") NULL', + fileext = ".R" + ) + + hits <- scan_fn_arg_path(file, arg_pattern = "path|file|filename")$hits + + expect_length(hits, 1L) + expect_equal(hits[[1L]]$fn, "read_it") + expect_equal(hits[[1L]]$arg, "path") + expect_equal(hits[[1L]]$default, '"~/data.csv"') + expect_equal(hits[[1L]]$line1, 1L) + expect_equal(hits[[1L]]$col1, 28L) +}) + +test_that("scan_fn_arg_path keeps an argument without default clean", { + file <- withr::local_tempfile( + lines = "read_it <- function(path, n = 1) NULL", + fileext = ".R" + ) + + expect_length(scan_fn_arg_path(file, arg_pattern = "path")$hits, 0L) +}) + +test_that("scan_fn_arg_path honours the allow list", { + file <- withr::local_tempfile( + lines = c( + 'a <- function(path = NULL) NULL', + 'b <- function(path = ".") NULL' + ), + fileext = ".R" + ) + + hits <- scan_fn_arg_path( + file, + arg_pattern = "path", + allow = c("NULL", '"."') + )$hits + expect_length(hits, 0L) + + hits <- scan_fn_arg_path(file, arg_pattern = "path", allow = "NULL")$hits + expect_length(hits, 1L) + expect_equal(hits[[1L]]$fn, "b") +}) + +test_that("scan_fn_arg_path only checks the requested exports", { + file <- withr::local_tempfile( + lines = c( + 'exported <- function(path = "a") NULL', + 'internal <- function(path = "b") NULL' + ), + fileext = ".R" + ) + + hits <- scan_fn_arg_path( + file, + arg_pattern = "path", + exports = "external" + )$hits + expect_length(hits, 0L) + + hits <- scan_fn_arg_path( + file, + arg_pattern = "path", + exports = c("internal") + )$hits + expect_length(hits, 1L) + expect_equal(hits[[1L]]$fn, "internal") +}) + +test_that("scan_fn_arg_path supports export_patterns", { + file <- withr::local_tempfile( + lines = c( + 'read_data <- function(path = "a") NULL', + 'write_data <- function(path = "b") NULL' + ), + fileext = ".R" + ) + + hits <- scan_fn_arg_path( + file, + arg_pattern = "path", + export_patterns = "^read_" + )$hits + expect_length(hits, 1L) + expect_equal(hits[[1L]]$fn, "read_data") +}) + +test_that("scan_fn_arg_path skips functions that are not top-level", { + file <- withr::local_tempfile( + lines = c( + "wrapper <- function() {", + ' inner <- function(path = "~/x") NULL', + " inner()", + "}" + ), + fileext = ".R" + ) + + expect_length(scan_fn_arg_path(file, arg_pattern = "path")$hits, 0L) +}) + +test_that("scan_fn_arg_path reports the whole multi-line default", { + file <- withr::local_tempfile( + lines = c( + "read_it <- function(", + " path = c(", + ' "a",', + ' "b"', + " )", + ") NULL" + ), + fileext = ".R" + ) + + hits <- scan_fn_arg_path(file, arg_pattern = "path")$hits + expect_length(hits, 1L) + expect_match(hits[[1L]]$default, "^c\\(") + expect_equal(hits[[1L]]$line1, 2L) + expect_gt(hits[[1L]]$line2, hits[[1L]]$line1) +}) + +test_that("scan_fn_arg_path aborts for a missing file", { + missing_file <- file.path(withr::local_tempdir(), "nope.R") + + expect_error( + scan_fn_arg_path(missing_file, arg_pattern = "path"), + "does not exist" + ) +}) + +test_that("detect_fn_arg_path matches arg_pattern unanchored by default", { + # `profile` contains `file`, so it is matched by the default pattern + file <- withr::local_tempfile( + lines = 'load_it <- function(profile = "~/p") NULL', + fileext = ".R" + ) + + expect_false(detect_fn_arg_path(file, verbose = FALSE)) + expect_length( + scan_fn_arg_path(file, arg_pattern = "path|file|filename")$hits, + 1L + ) + expect_length( + scan_fn_arg_path(file, arg_pattern = "^(path|file|filename)$")$hits, + 0L + ) +}) + +test_that("detect_fn_arg_path aborts when path cannot be resolved", { + local_mocked_bindings( + isAvailable = function(...) FALSE, + .package = "rstudioapi" + ) + + expect_error(detect_fn_arg_path(), "required") +}) + +test_that("detect_fn_arg_path aborts when the active document has no path", { + local_mocked_bindings( + isAvailable = function(...) TRUE, + getActiveDocumentContext = function(...) list(path = ""), + .package = "rstudioapi" + ) + + expect_error(detect_fn_arg_path(), "required") +}) + +test_that("detect_fn_arg_path uses the active document when path is NULL", { + file <- withr::local_tempfile( + lines = 'read_it <- function(path = "~/data.csv") NULL', + fileext = ".R" + ) + local_mocked_bindings( + isAvailable = function(...) TRUE, + getActiveDocumentContext = function(...) list(path = file), + .package = "rstudioapi" + ) + + expect_false(detect_fn_arg_path(verbose = FALSE)) +}) + +test_that("detect_fn_arg_path errors on non-empty dots", { + file <- withr::local_tempfile( + lines = "read_it <- function(path) NULL", + fileext = ".R" + ) + + expect_error(detect_fn_arg_path(file, unused = 1), class = "rlang_error") +}) + +test_that("detect_fn_arg_path is quiet when verbose is FALSE", { + file <- withr::local_tempfile( + lines = c( + 'bad <- function(path = "~/x") NULL', + 'good <- function(path = NULL) NULL' + ), + fileext = ".R" + ) + + expect_silent(detect_fn_arg_path(file, verbose = FALSE)) +}) + +test_that("detect_fn_arg_path reports hits on the console", { + file <- withr::local_tempfile( + lines = 'read_it <- function(path = "~/x.csv") NULL', + fileext = ".R" + ) + + expect_message(detect_fn_arg_path(file), "Found 1 argument") +}) + +test_that("report_fn_arg_hits prints the source line and a caret marker", { + file <- withr::local_tempfile( + lines = 'read_it <- function(path = "~/x.csv") NULL', + fileext = ".R" + ) + scanned <- scan_fn_arg_path(file, arg_pattern = "path") + + out <- paste( + capture.output( + report_fn_arg_hits(file, scanned$lines, scanned$hits), + type = "message" + ), + collapse = "\n" + ) + + expect_match(out, "read_it\\(\\).*path", all = FALSE) + expect_match(out, "read_it <- function\\(path = ", all = FALSE) + expect_match(out, "\\^+") +}) + +test_that("report_fn_arg_hits strips the root from the shown path", { + dir <- withr::local_tempdir() + file <- file.path(dir, "read.R") + writeLines('read_it <- function(path = "~/x.csv") NULL', file) + scanned <- scan_fn_arg_path(file, arg_pattern = "path") + + out <- paste( + capture.output( + report_fn_arg_hits(file, scanned$lines, scanned$hits, root = dir), + type = "message" + ), + collapse = "\n" + ) + + expect_match(out, "'read\\.R':1:21", all = FALSE) + expect_false(grepl(dir, out, fixed = TRUE)) +}) + +test_that("report_fn_arg_hits returns NULL invisibly", { + file <- withr::local_tempfile( + lines = 'read_it <- function(path = "~/x.csv") NULL', + fileext = ".R" + ) + scanned <- scan_fn_arg_path(file, arg_pattern = "path") + + expect_invisible(report_fn_arg_hits(file, scanned$lines, scanned$hits)) +}) diff --git a/tests/testthat/test-package_fn_arg_path.R b/tests/testthat/test-package_fn_arg_path.R new file mode 100644 index 0000000..b69260b --- /dev/null +++ b/tests/testthat/test-package_fn_arg_path.R @@ -0,0 +1,217 @@ +# --------------------------------------------------------------------------- +# package_fn_arg_path() -- package-wide wrapper around scan_fn_arg_path() +# --------------------------------------------------------------------------- + +# Build a minimal package on disk. `files` maps package-relative paths to the +# lines written there, e.g. list("R/read.R" = 'read_it <- function(path="x")'). +local_path_pkg <- function( + files = list(), + namespace = character(), + env = parent.frame() +) { + pkg <- withr::local_tempdir(.local_envir = env) + writeLines( + c("Package: testpkg", "Version: 0.0.1"), + file.path(pkg, "DESCRIPTION") + ) + writeLines(namespace, file.path(pkg, "NAMESPACE")) + for (rel_path in names(files)) { + target <- file.path(pkg, rel_path) + dir.create(dirname(target), recursive = TRUE, showWarnings = FALSE) + writeLines(files[[rel_path]], target) + } + pkg +} + +test_that("package_fn_arg_path aborts when path is not a package", { + # A dedicated directory: `tempdir()` may already contain a DESCRIPTION + # written by another test + non_pkg <- withr::local_tempdir() + + expect_error(package_fn_arg_path(non_pkg), "is not an R package") +}) + +test_that("package_fn_arg_path aborts when path is an empty string", { + expect_error(package_fn_arg_path(""), "required") +}) + +test_that("package_fn_arg_path informs and returns TRUE with no exports", { + pkg <- local_path_pkg( + files = list("R/read.R" = 'read_it <- function(path = "~/x") NULL'), + namespace = character() + ) + + expect_message( + expect_true(package_fn_arg_path(pkg)), + "No exported functions found" + ) +}) + +test_that("package_fn_arg_path informs and returns TRUE when no files match", { + pkg <- local_path_pkg( + files = list("src/read.R" = 'read_it <- function(path = "~/x") NULL'), + namespace = "export(read_it)" + ) + + expect_message( + expect_true(package_fn_arg_path(pkg)), + "files found to scan" + ) +}) + +test_that("package_fn_arg_path returns TRUE for a clean package", { + pkg <- local_path_pkg( + files = list( + "R/read.R" = 'read_it <- function(path = NULL, n = 1) NULL', + "R/write.R" = 'write_it <- function(file, x) NULL' + ), + namespace = c("export(read_it)", "export(write_it)") + ) + + expect_message( + expect_true(package_fn_arg_path(pkg, verbose = FALSE)), + "No exported function has a default path" + ) +}) + +test_that("package_fn_arg_path detects a default path and returns FALSE", { + pkg <- local_path_pkg( + files = list("R/read.R" = 'read_it <- function(path = "~/x.csv") NULL'), + namespace = "export(read_it)" + ) + + expect_message( + expect_false(package_fn_arg_path(pkg, verbose = FALSE)), + "Found 1 argument" + ) +}) + +test_that("package_fn_arg_path counts hits and offending files", { + pkg <- local_path_pkg( + files = list( + "R/a.R" = c( + 'read_a <- function(path = "~/a") NULL', + 'read_b <- function(file = "~/b") NULL' + ), + "R/b.R" = 'read_c <- function(filename = "~/c") NULL', + "R/clean.R" = 'read_d <- function(path = NULL) NULL' + ), + namespace = c( + "export(read_a)", + "export(read_b)", + "export(read_c)", + "export(read_d)" + ) + ) + + expect_message( + expect_false(package_fn_arg_path(pkg, verbose = FALSE)), + "Found 3 arguments with a default path in 2 of 3 files" + ) +}) + +test_that("package_fn_arg_path ignores functions that are not exported", { + pkg <- local_path_pkg( + files = list( + "R/read.R" = c( + 'read_exported <- function(path = NULL) NULL', + 'read_internal <- function(path = "~/x") NULL' + ) + ), + namespace = "export(read_exported)" + ) + + expect_true(package_fn_arg_path(pkg, verbose = FALSE)) +}) + +test_that("package_fn_arg_path resolves exports declared by exportPattern", { + pkg <- local_path_pkg( + files = list( + "R/read.R" = c( + 'read_data <- function(path = "~/x") NULL', + 'internal_data <- function(path = "~/y") NULL' + ) + ), + namespace = 'exportPattern("^read_")' + ) + + expect_message( + expect_false(package_fn_arg_path(pkg, verbose = FALSE)), + "Found 1 argument" + ) +}) + +test_that("package_fn_arg_path honours a custom dirs argument", { + pkg <- local_path_pkg( + files = list( + "R2/nested/read.R" = 'read_it <- function(path = "~/x") NULL' + ), + namespace = "export(read_it)" + ) + + expect_true(package_fn_arg_path(pkg, dirs = "R", verbose = FALSE)) + expect_false(package_fn_arg_path(pkg, dirs = "R2", verbose = FALSE)) +}) + +test_that("package_fn_arg_path honours the allow list", { + pkg <- local_path_pkg( + files = list("R/read.R" = 'read_it <- function(path = ".") NULL'), + namespace = "export(read_it)" + ) + + expect_false(package_fn_arg_path(pkg, verbose = FALSE)) + expect_true(package_fn_arg_path( + pkg, + allow = c("NULL", '"."'), + verbose = FALSE + )) +}) + +test_that("package_fn_arg_path honours a custom arg_pattern", { + pkg <- local_path_pkg( + files = list( + "R/read.R" = 'read_it <- function(path = NULL) NULL', + "R/save.R" = 'save_it <- function(out_dir = "~/y") NULL' + ), + namespace = c("export(read_it)", "export(save_it)") + ) + + # The default pattern does not cover `out_dir` + expect_true(suppressMessages(package_fn_arg_path(pkg, verbose = FALSE))) + expect_false( + suppressMessages( + package_fn_arg_path(pkg, arg_pattern = "out_dir", verbose = FALSE) + ) + ) +}) + +test_that("package_fn_arg_path only suppresses the per-hit report", { + # `verbose` controls the detailed report; the closing summary is always shown + pkg <- local_path_pkg( + files = list("R/read.R" = 'read_it <- function(path = "~/x") NULL'), + namespace = "export(read_it)" + ) + + expect_message( + expect_false(package_fn_arg_path(pkg, verbose = FALSE)), + "Found 1 argument" + ) +}) + +test_that("package_fn_arg_path returns invisibly", { + pkg <- local_path_pkg( + files = list("R/read.R" = 'read_it <- function(path = NULL) NULL'), + namespace = "export(read_it)" + ) + + expect_invisible(suppressMessages(package_fn_arg_path(pkg, verbose = FALSE))) +}) + +test_that("package_fn_arg_path errors on non-empty dots", { + pkg <- local_path_pkg( + files = list("R/read.R" = 'read_it <- function(path = NULL) NULL'), + namespace = "export(read_it)" + ) + + expect_error(package_fn_arg_path(pkg, unused = 1), class = "rlang_error") +}) diff --git a/tests/testthat/test-ts_cli.R b/tests/testthat/test-ts_cli.R index cb92bc1..a897a0d 100644 --- a/tests/testthat/test-ts_cli.R +++ b/tests/testthat/test-ts_cli.R @@ -8,8 +8,11 @@ test_that("add_timestamp_to_cli prepends timestamp to character messages", { wrapped <- rpkgkit:::add_timestamp_to_cli(mock_cli) wrapped("Hello, world") - # The first message should have the timestamp glue syntax prepended - expect_match(captured[[1L]], "\\{time_stamp\\(\\)\\}Hello, world") + # The first message should have an evaluated timestamp prepended + expect_match( + captured[[1L]], + "^\\[\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}\\] Hello, world$" + ) }) test_that("add_timestamp_to_cli does nothing when no messages", { @@ -47,7 +50,10 @@ test_that("add_timestamp_to_cli only modifies the first message when character", wrapped("First message", "Second message") # First message gets timestamp, second is unchanged - expect_match(captured[[1L]], "\\{time_stamp\\(\\)\\}First message") + expect_match( + captured[[1L]], + "^\\[\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}\\] First message$" + ) expect_equal(captured[[2L]], "Second message") }) @@ -60,7 +66,10 @@ test_that("add_timestamp_to_cli works with named arguments", { wrapped <- rpkgkit:::add_timestamp_to_cli(mock_cli) wrapped("msg text", .envir = rlang::current_env()) - expect_match(captured$msg[[1L]], "\\{time_stamp\\(\\)\\}msg text") + expect_match( + captured$msg[[1L]], + "^\\[\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}\\] msg text$" + ) expect_true(is.environment(captured$.envir)) }) @@ -107,7 +116,10 @@ test_that("add_timestamp_to_cli wraps named arguments correctly with mock", { env <- rlang::new_environment() wrapped("A", "B", .envir = env) - expect_match(captured_msgs[[1L]], "\\{time_stamp\\(\\)\\}A") + expect_match( + captured_msgs[[1L]], + "^\\[\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}\\] A$" + ) expect_equal(captured_msgs[[2L]], "B") expect_identical(captured_env, env) }) diff --git a/tests/testthat/test-use_tidy_addin.R b/tests/testthat/test-use_tidy_addin.R new file mode 100644 index 0000000..f34a053 --- /dev/null +++ b/tests/testthat/test-use_tidy_addin.R @@ -0,0 +1,434 @@ +# --------------------------------------------------------------------------- +# use_tidy_addin() and its internal helpers +# --------------------------------------------------------------------------- + +# Build a minimal package that defines `fn` in R/fn.R and (optionally) exports +# it from NAMESPACE. +local_addin_pkg <- function( + fn = "my_addin", + body = "rstudioapi::getActiveDocumentContext()", + namespace = NULL, + write_namespace = TRUE, + env = parent.frame() +) { + pkg <- withr::local_tempdir(.local_envir = env) + writeLines( + c("Package: testpkg", "Version: 0.0.1"), + file.path(pkg, "DESCRIPTION") + ) + if (write_namespace) { + if (is.null(namespace)) { + namespace <- paste0("export(", fn, ")") + } + writeLines(namespace, file.path(pkg, "NAMESPACE")) + } + dir.create(file.path(pkg, "R")) + writeLines( + c(paste0(fn, " <- function(...) {"), paste0(" ", body), "}"), + file.path(pkg, "R", "fn.R") + ) + pkg +} + +test_that("use_tidy_addin writes the addin registration", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg() + + expect_message( + use_tidy_addin("my_addin", "Open my gadget", path = pkg), + "Wrote addin" + ) + + dcf <- file.path(pkg, "inst", "rstudio", "addins.dcf") + expect_true(file.exists(dcf)) + expect_equal( + readLines(dcf, warn = FALSE), + c( + "Name: my_addin", + "Description: Open my gadget", + "Binding: my_addin", + "Interactive: false" + ) + ) +}) + +test_that("use_tidy_addin returns the dcf path invisibly", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg() + + expect_invisible( + suppressMessages(use_tidy_addin("my_addin", "gadget", path = pkg)) + ) + expect_equal( + suppressMessages(use_tidy_addin("my_addin", "gadget", path = pkg)), + file.path(pkg, "inst", "rstudio", "addins.dcf") + ) +}) + +test_that("use_tidy_addin collapses newlines in the description", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg() + + suppressMessages( + use_tidy_addin("my_addin", "line one\n line two", path = pkg) + ) + + lines <- readLines(file.path(pkg, "inst", "rstudio", "addins.dcf")) + expect_equal(lines[2L], "Description: line one line two") +}) + +test_that("use_tidy_addin puts a new entry above existing ones", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg() + dcf <- file.path(pkg, "inst", "rstudio", "addins.dcf") + dir.create(dirname(dcf), recursive = TRUE) + writeLines( + c( + "Name: old_addin", + "Description: Old", + "Binding: old_addin", + "Interactive: false" + ), + dcf + ) + + suppressMessages(use_tidy_addin("my_addin", "New", path = pkg)) + + expect_equal( + readLines(dcf, warn = FALSE), + c( + "Name: my_addin", + "Description: New", + "Binding: my_addin", + "Interactive: false", + "", + "Name: old_addin", + "Description: Old", + "Binding: old_addin", + "Interactive: false" + ) + ) +}) + +test_that("use_tidy_addin does not register the same addin twice", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg() + dcf <- file.path(pkg, "inst", "rstudio", "addins.dcf") + dir.create(dirname(dcf), recursive = TRUE) + writeLines(c("Name: my_addin", "Binding: my_addin"), dcf) + + expect_message( + expect_equal( + use_tidy_addin("my_addin", "again", path = pkg), + dcf + ), + "already registered" + ) + expect_equal( + readLines(dcf, warn = FALSE), + c("Name: my_addin", "Binding: my_addin") + ) +}) + +test_that("use_tidy_addin records Interactive = TRUE", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg(body = "shiny::runApp()") + + suppressMessages( + use_tidy_addin("my_addin", "gadget", Interactive = TRUE, path = pkg) + ) + + lines <- readLines(file.path(pkg, "inst", "rstudio", "addins.dcf")) + expect_true("Interactive: true" %in% lines) +}) + +test_that("use_tidy_addin warns and continues when no rstudioapi call is found", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg(body = "invisible(NULL)") + local_mocked_bindings( + .uta_confirm = function(msg, .envir = parent.frame()) TRUE, + .package = "rpkgkit" + ) + + suppressMessages(use_tidy_addin("my_addin", "gadget", path = pkg)) + + expect_true( + file.exists(file.path(pkg, "inst", "rstudio", "addins.dcf")) + ) +}) + +test_that("use_tidy_addin writes nothing when the prompt is declined", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg(body = "invisible(NULL)") + local_mocked_bindings( + .uta_confirm = function(msg, .envir = parent.frame()) FALSE, + .package = "rpkgkit" + ) + + expect_message( + expect_null(use_tidy_addin("my_addin", "gadget", path = pkg)), + "Cancelled" + ) + expect_false( + file.exists(file.path(pkg, "inst", "rstudio", "addins.dcf")) + ) +}) + +test_that("use_tidy_addin cancels an Interactive addin without shiny", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg() + local_mocked_bindings( + .uta_confirm = function(msg, .envir = parent.frame()) FALSE, + .package = "rpkgkit" + ) + + expect_null( + suppressMessages( + use_tidy_addin("my_addin", "gadget", Interactive = TRUE, path = pkg) + ) + ) + expect_false( + file.exists(file.path(pkg, "inst", "rstudio", "addins.dcf")) + ) +}) + +test_that("use_tidy_addin accepts an Interactive addin that uses miniUI", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg(body = "miniUI::miniPage()") + + suppressMessages( + use_tidy_addin("my_addin", "gadget", Interactive = TRUE, path = pkg) + ) + + lines <- readLines(file.path(pkg, "inst", "rstudio", "addins.dcf")) + expect_true("Interactive: true" %in% lines) +}) + +test_that("use_tidy_addin falls back to scanning R/ when not installed", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg() + # Documented package: roxygen header in NAMESPACE plus a man page, while + # `testpkg` itself is (obviously) not installed + writeLines( + c( + "# Generated by roxygen2: do not edit by hand", + "export(my_addin)" + ), + file.path(pkg, "NAMESPACE") + ) + dir.create(file.path(pkg, "man")) + writeLines("\\name{my_addin}", file.path(pkg, "man", "my_addin.Rd")) + + expect_true(rpkgkit:::.uta_is_documented(pkg)) + suppressMessages(use_tidy_addin("my_addin", "gadget", path = pkg)) + expect_true(file.exists(file.path(pkg, "inst", "rstudio", "addins.dcf"))) +}) + +test_that("use_tidy_addin aborts when path is not an R package", { + non_pkg <- withr::local_tempdir() + + expect_error( + use_tidy_addin("my_addin", "gadget", path = non_pkg), + "is not an R package" + ) +}) + +test_that("use_tidy_addin aborts when NAMESPACE is missing", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg(write_namespace = FALSE) + + expect_error(use_tidy_addin("my_addin", "gadget", path = pkg), "Cannot find") +}) + +test_that("use_tidy_addin aborts when the function is not exported", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg(namespace = "export(other_addin)") + + expect_error( + use_tidy_addin("my_addin", "gadget", path = pkg), + "not exported" + ) +}) + +test_that("use_tidy_addin aborts when no definition can be found", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg(namespace = "export(my_addin)") + writeLines("other <- function() NULL", file.path(pkg, "R", "fn.R")) + + expect_error( + use_tidy_addin("my_addin", "gadget", path = pkg), + "Cannot find a definition" + ) +}) + +test_that("use_tidy_addin validates its arguments", { + skip_if_not_installed("desc") + pkg <- local_addin_pkg() + + expect_error(use_tidy_addin(1, "gadget", path = pkg), class = "rlang_error") + expect_error(use_tidy_addin("my_addin", 1, path = pkg), class = "rlang_error") + expect_error( + use_tidy_addin("my_addin", "gadget", Interactive = "yes", path = pkg), + class = "rlang_error" + ) +}) + +# ------------------------------- helpers ----------------------------------- + +test_that(".uta_parse_namespace reads exports, patterns and imports", { + ns_file <- withr::local_tempfile( + lines = c( + "export(a, b)", + 'exportPattern("^foo")', + "import(cli)", + "importFrom(rlang, check_string, abort)" + ) + ) + + ns <- rpkgkit:::.uta_parse_namespace(ns_file) + + expect_setequal(ns$exports, c("a", "b")) + expect_equal(ns$export_patterns, "^foo") + expect_equal(ns$imports_all, "cli") + expect_equal(ns$imports_from$pkg, c("rlang", "rlang")) + expect_setequal(ns$imports_from$sym, c("check_string", "abort")) +}) + +test_that(".uta_parse_namespace returns empty results for an empty NAMESPACE", { + ns_file <- withr::local_tempfile(lines = character()) + + ns <- rpkgkit:::.uta_parse_namespace(ns_file) + + expect_length(ns$exports, 0L) + expect_length(ns$export_patterns, 0L) + expect_length(ns$imports_all, 0L) + expect_equal(nrow(ns$imports_from), 0L) +}) + +test_that(".uta_is_documented requires both a roxygen header and a man page", { + pkg <- local_addin_pkg() + expect_false(rpkgkit:::.uta_is_documented(pkg)) + + writeLines( + c("# Generated by roxygen2: do not edit by hand", "export(my_addin)"), + file.path(pkg, "NAMESPACE") + ) + expect_false(rpkgkit:::.uta_is_documented(pkg)) + + dir.create(file.path(pkg, "man")) + writeLines("\\name{my_addin}", file.path(pkg, "man", "my_addin.Rd")) + expect_true(rpkgkit:::.uta_is_documented(pkg)) +}) + +test_that(".uta_find_fn_body finds bodies assigned with <-, = and <<-", { + pkg <- withr::local_tempdir() + dir.create(file.path(pkg, "R")) + writeLines( + c( + "f_arrow <- function(a) {", + " a + 1", + "}", + "f_equal = function(b) b * 2", + "f_super <<- function() NULL" + ), + file.path(pkg, "R", "fns.R") + ) + + expect_identical( + rpkgkit:::.uta_find_fn_body("f_arrow", pkg)[[1L]], + as.name("{") + ) + expect_identical(rpkgkit:::.uta_find_fn_body("f_equal", pkg), quote(b * 2)) + expect_null(rpkgkit:::.uta_find_fn_body("f_super", pkg)) + expect_null(rpkgkit:::.uta_find_fn_body("missing_fn", pkg)) +}) + +test_that(".uta_find_fn_body skips files that cannot be parsed", { + pkg <- withr::local_tempdir() + dir.create(file.path(pkg, "R")) + writeLines("this is ( not R", file.path(pkg, "R", "broken.R")) + writeLines("ok_fn <- function() 1", file.path(pkg, "R", "ok.R")) + + expect_identical(rpkgkit:::.uta_find_fn_body("ok_fn", pkg), 1) +}) + +test_that(".uta_find_fn_body returns NULL when R/ is absent", { + pkg <- withr::local_tempdir() + expect_null(rpkgkit:::.uta_find_fn_body("anything", pkg)) +}) + +test_that(".uta_uses_pkg detects pkg::, library() and imported symbols", { + ns <- list( + exports = character(), + export_patterns = character(), + imports_all = character(), + imports_from = data.frame( + pkg = "rstudioapi", + sym = "getActiveDocumentContext" + ) + ) + body <- quote({ + rstudioapi::getActiveDocumentContext() + }) + expect_true(rpkgkit:::.uta_uses_pkg(body, "rstudioapi", ns)) + + body <- quote(library(rstudioapi)) + expect_true(rpkgkit:::.uta_uses_pkg(body, "rstudioapi", ns)) + + # Symbol reached through importFrom() + body <- quote(getActiveDocumentContext()) + expect_true(rpkgkit:::.uta_uses_pkg(body, "rstudioapi", ns)) + + body <- quote(invisible(NULL)) + expect_false(rpkgkit:::.uta_uses_pkg(body, "rstudioapi", ns)) +}) + +test_that(".uta_uses_pkg checks the whole namespace for import()", { + ns <- list( + exports = character(), + export_patterns = character(), + imports_all = "cli", + imports_from = data.frame(pkg = character(), sym = character()) + ) + + expect_true(rpkgkit:::.uta_uses_pkg(quote(cli_alert_info("hi")), "cli", ns)) +}) + +test_that(".uta_confirm continues in a non-interactive session", { + local_mocked_bindings( + is_interactive = function() FALSE, + .package = "rlang" + ) + + messages <- character() + result <- withCallingHandlers( + rpkgkit:::.uta_confirm("Continue?"), + message = function(m) { + messages <<- c(messages, conditionMessage(m)) + invokeRestart("muffleMessage") + } + ) + + expect_true(result) + expect_match(paste(messages, collapse = " "), "Non-interactive session") +}) + +test_that(".uta_read_bindings returns the registered bindings", { + dcf <- withr::local_tempfile( + lines = c( + "Name: a", + "Binding: fn_a", + "", + "Name: b", + "Binding: fn_b" + ) + ) + + expect_equal(rpkgkit:::.uta_read_bindings(dcf), c("fn_a", "fn_b")) +}) + +test_that(".uta_read_bindings returns character() for an unreadable file", { + dcf <- withr::local_tempfile(lines = "this is not a dcf file at all") + + expect_equal(rpkgkit:::.uta_read_bindings(dcf), character()) +}) diff --git a/vignettes/code_convertion.Rmd b/vignettes/code_convertion.Rmd index f18ae65..4f2927d 100644 --- a/vignettes/code_convertion.Rmd +++ b/vignettes/code_convertion.Rmd @@ -1,6 +1,6 @@ --- title: "Code Convertion" -subtitle: "rpkgkit 0.1.21" +subtitle: "rpkgkit 0.1.23" author: "Yuxi Yang" date: "`r Sys.Date()`" lang: en-US @@ -59,7 +59,8 @@ readLines(file) |> cli::cli_code() # Find unmatched glue braces `detect_lost_glue_brace()` checks one file; `package_lost_glue_brace()` checks -an entire package. Both support `glue` and `cli` expressions. +an entire package. Both support `glue` and `cli` expressions, and print the +offending source line with `cli` syntax highlighting. ```{r} #| label = "detect_lost_glue_brace" @@ -105,7 +106,8 @@ readLines(file) |> cli::cli_code() `detect_print_and_cat()` reports `print()` and `cat()` calls in one file. `package_print_and_cat()` checks an entire package. Set `fix = TRUE` to replace -those calls in the selected file with `message()`. +those calls in the selected file with `message()`. As for the glue brace +detection, the reported source line is syntax highlighted. ```{r} #| label = "detect_print_and_cat" @@ -173,6 +175,49 @@ writeLines(c("g <- function(y) y", "# nocov end"), file.path(pkg, "R", "g.R")) package_unmatched_nocov_marker(pkg) ``` +# Detect default paths in exported arguments + +CRAN does not allow a path-like argument of an exported function to default to a +concrete location such as `"."` or `"~/data.csv"`. `detect_fn_arg_path()` checks +one file and `package_fn_arg_path()` checks every `.R` file of a package, using +the exports declared in `NAMESPACE`. + +```{r} +#| label = "detect_fn_arg_path" +file <- tempfile(fileext = ".R") +writeLines( + c( + 'read_csv <- function(path = "~/data.csv", n = 1L) NULL', + 'read_all <- function(file = "data.txt") NULL', + 'read_tsv <- function(path = NULL, n = 1L) NULL' + ), + file +) + +detect_fn_arg_path(file) +``` + +An argument is reported when its name matches `arg_pattern` and its default is +not listed in `allow`, so `read_tsv()` above is clean: its default is `NULL`. An +argument without a default is always fine. Narrow the pattern when a loose match +is not wanted: + +```{r} +#| label = "detect_fn_arg_path_pattern" +detect_fn_arg_path(file, arg_pattern = "^path$") +``` + +`detect_fn_arg_path()` uses the active document when `path` is `NULL`, and checks +every top-level function of that file unless `exports` or `export_patterns` say +which ones count as exported. Use the package-wide function to see all the +occurrences at once: + +```{r} +#| label = "package_fn_arg_path", +#| eval = FALSE +package_fn_arg_path() +``` + # Convert function syntax Convert between `function()` and the short `\()` syntax. diff --git a/vignettes/news.Rmd b/vignettes/news.Rmd index efd61c7..4483464 100644 --- a/vignettes/news.Rmd +++ b/vignettes/news.Rmd @@ -1,6 +1,6 @@ --- title: "Edit NEWS" -subtitle: "rpkgkit 0.1.21" +subtitle: "rpkgkit 0.1.23" author: "Yuxi Yang" date: "`r Sys.Date()`" lang: en-US diff --git a/vignettes/pkg_maintain.Rmd b/vignettes/pkg_maintain.Rmd index fbc8fbe..8420324 100644 --- a/vignettes/pkg_maintain.Rmd +++ b/vignettes/pkg_maintain.Rmd @@ -1,6 +1,6 @@ --- title: "Package Setup & Maintenace" -subtitle: "rpkgkit 0.1.21" +subtitle: "rpkgkit 0.1.23" author: "Yuxi Yang" date: "`r Sys.Date()`" lang: en-US @@ -111,6 +111,55 @@ for options such as `select`, `ignore` and `per-file-ignores`, and the [continuous integration guide](https://jarl.etiennebacher.com/howto/ci) to run `jarl check` on every push with the `etiennebacher/setup-jarl` action. +# RStudio addins + +An addin is an exported function registered in `inst/rstudio/addins.dcf`; RStudio +then lists it in the `Addins` menu and runs it in the current session. +`use_tidy_addin()` writes that entry for you: + +```{r} +#| label = "use_tidy_addin", +#| eval = FALSE +use_tidy_addin( + fn_name = "check_my_pkg", + desc = "Check my package", + path = dir +) +``` + +The entry is appended above the existing ones, so the newest addin comes first, +and a `Binding` that is already registered is never added twice: + +``` +Name: check_my_pkg +Description: Check my package +Binding: check_my_pkg +Interactive: false +``` + +Before writing, the function checks that `path` is a package and that `fn_name` +is exported in `NAMESPACE`, reads the body of the function (from the installed +package, or from `R/` when the package has not been documented yet), and warns +when that body calls no `rstudioapi` function, or, for an `Interactive = TRUE` +addin, no `shiny`/`miniUI` function. In an interactive session the warning asks +whether to continue; a non-interactive session only reports it and writes the +entry. + +`rpkgkit` registers its own addins in `inst/rstudio/addins.dcf`, so every +detector can be run from the menu without typing the call: + +| Addin | What it checks | +|---|---| +| `detect_lost_glue_brace` / `package_lost_glue_brace` | unmatched `{}` in `glue()`/`cli` strings | +| `detect_print_and_cat` / `package_print_and_cat` | CRAN-unsafe `print()`/`cat()` calls | +| `detect_fn_arg_path` / `package_fn_arg_path` | path-like arguments of exported functions that default to a concrete location | +| `package_unmatched_nocov_marker` | unmatched `# nocov start` / `# nocov end` markers | +| `check_pkgdown_reference` | exported functions missing from the `_pkgdown.yml` reference | + +The `detect_*` addins work on the active editor, the package-wide ones on the +current package directory. They only report; none of them rewrites a file. In +Positron, addins need a third-party extension such as Positron R Wizard. + # Vendor permissively licensed code `use_vendor()` records attribution and licensing information when incorporating diff --git a/vignettes/readme_and_doc.Rmd b/vignettes/readme_and_doc.Rmd index bcbfe3a..21a56bc 100644 --- a/vignettes/readme_and_doc.Rmd +++ b/vignettes/readme_and_doc.Rmd @@ -1,6 +1,6 @@ --- title: "Tools for README & Documentation" -subtitle: "rpkgkit 0.1.21" +subtitle: "rpkgkit 0.1.23" author: "Yuxi Yang" date: "`r Sys.Date()`" lang: en-US diff --git a/vignettes/standalone_tools.Rmd b/vignettes/standalone_tools.Rmd index 27653d8..6ccfd88 100644 --- a/vignettes/standalone_tools.Rmd +++ b/vignettes/standalone_tools.Rmd @@ -1,6 +1,6 @@ --- title: "rpkgkit standalone scripts" -subtitle: "rpkgkit 0.1.21" +subtitle: "rpkgkit 0.1.23" author: "Yuxi Yang" date: "`r Sys.Date()`" lang: en-US @@ -109,6 +109,20 @@ color_cli2$cli_alert_success( ) ``` +The wrapped functions also take `.envir`, defaulting to `parent.frame()` and +forwarded to the cli function, so `{}` interpolation is resolved in the caller's +environment instead of inside the wrapper: + +```{r} +#| label = "colorful_cli_envir", +#| eval = FALSE +name <- "world" +color_cli$cli_alert_info("Hello, {name}") + +msg_env <- list2env(list(who = "Positron"), parent = emptyenv()) +color_cli$cli_alert_info("Hello, {who}", .envir = msg_env) +``` + ## Add timestamps to cli output The `ts_cli.R` standalone script creates timestamped `cli` functions. From 5a7769019d70d2cdbcf2ca5c33689b653a4aaafe Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Mon, 2 Nov 2026 03:22:58 -0500 Subject: [PATCH 11/35] fix test --- tests/testthat/test-use_tidy_addin.R | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/tests/testthat/test-use_tidy_addin.R b/tests/testthat/test-use_tidy_addin.R index f34a053..53d4286 100644 --- a/tests/testthat/test-use_tidy_addin.R +++ b/tests/testthat/test-use_tidy_addin.R @@ -30,6 +30,14 @@ local_addin_pkg <- function( pkg } +# `use_tidy_addin()` returns a path built on `normalizePath(path)`, which +# resolves symlinks on macOS (`/var` -> `/private/var`) and expands 8.3 short +# names on Windows (`RUNNER~1` -> `runneradmin`). Normalize both sides before +# comparing so the tests are portable. +norm_path <- function(path) { + normalizePath(path, winslash = "/", mustWork = FALSE) +} + test_that("use_tidy_addin writes the addin registration", { skip_if_not_installed("desc") pkg <- local_addin_pkg() @@ -60,8 +68,8 @@ test_that("use_tidy_addin returns the dcf path invisibly", { suppressMessages(use_tidy_addin("my_addin", "gadget", path = pkg)) ) expect_equal( - suppressMessages(use_tidy_addin("my_addin", "gadget", path = pkg)), - file.path(pkg, "inst", "rstudio", "addins.dcf") + norm_path(suppressMessages(use_tidy_addin("my_addin", "gadget", path = pkg))), + norm_path(file.path(pkg, "inst", "rstudio", "addins.dcf")) ) }) @@ -119,8 +127,8 @@ test_that("use_tidy_addin does not register the same addin twice", { expect_message( expect_equal( - use_tidy_addin("my_addin", "again", path = pkg), - dcf + norm_path(use_tidy_addin("my_addin", "again", path = pkg)), + norm_path(dcf) ), "already registered" ) From c92a1c19876e581cd6e51f23da797b491c5fb44c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Mon, 2 Nov 2026 08:29:20 +0000 Subject: [PATCH 12/35] chore: bump version to 0.1.23 [skip ci] --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index a2b3a12..5e86d01 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: rpkgkit Title: Create and Maintain R Packages -Version: 0.1.22 +Version: 0.1.23 Authors@R: c( person("Yuxi", "Yang", , "15364051195@163.com", role = c("aut", "cre")), person("Jacob", "Scott", role = c("ctb", "cph"), From 2706809a60d20901a81fa1330b58e8d939caab3d Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Mon, 2 Nov 2026 03:45:32 -0500 Subject: [PATCH 13/35] provide a cheatsheet --- README.Rmd | 92 ++++++++++++++++++++++++++++++ README.md | 92 ++++++++++++++++++++++++++++++ inst/translations/README.es.md | 94 +++++++++++++++++++++++++++++++ inst/translations/README.zh-cn.md | 94 +++++++++++++++++++++++++++++++ 4 files changed, 372 insertions(+) diff --git a/README.Rmd b/README.Rmd index 3915f2f..008f9f0 100644 --- a/README.Rmd +++ b/README.Rmd @@ -90,6 +90,98 @@ It's recommended to use following packages together with `rpkgkit`: - [`usethis`](https://usethis.r-lib.org/): manage package metadata. - [`devtools`](https://devtools.r-lib.org/): build and check package. +## Cheat sheet + +### Convert and check code + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `add_double_colons()` | `add_double_colons(code)` | Add `pkg::` qualifiers to calls in a code string | +| `make_func_call_explicit()` | `make_func_call_explicit("R/foo.R")` | Add `pkg::` qualifiers to every call in one file | +| `package_func_call_explicit()` | `package_func_call_explicit()` | Same, for every file under `R/` | +| `make_func_arg_explicit()` | `make_func_arg_explicit("R/foo.R")` | Add argument names to calls in one file | +| `package_func_arg_explicit()` | `package_func_arg_explicit()` | Same, for every file under `R/` | +| `rename_func()` | `rename_func("R/foo.R", style = "snake_case")` | Rename function definitions to a naming style | +| `convert_func_syntax()` | `convert_func_syntax("R/foo.R", direction = "to_lambda")` | Switch between `function()` and `\()` syntax | +| `convert_pipe()` | `convert_pipe("R/foo.R", direction = "to_base")` | Switch between the magrittr and base pipes in one file | +| `package_convert_pipe()` | `package_convert_pipe(direction = "to_base")` | Same, for every file under `R/` | +| `convert_int_literals()` | `convert_int_literals("R/foo.R")` | Add the integer `L` suffix in one file | +| `package_convert_int_literals()` | `package_convert_int_literals()` | Same, for every file under `R/` | +| `convert_nonascii_code()` | `convert_nonascii_code(code, reverse = FALSE)` | Escape non-ASCII characters (or restore them) | +| `convert_knitr_chunk_header()` | `convert_knitr_chunk_header()` | Modernize knitr chunk headers in `.Rmd` files | +| `optimize_rmd_yaml()` | `optimize_rmd_yaml("README.Rmd")` | Fill one YAML header from the package `DESCRIPTION` | +| `package_optimize_rmd_yaml()` | `package_optimize_rmd_yaml()` | Same, for `README.Rmd` and all vignettes | +| `detect_print_and_cat()` | `detect_print_and_cat("R/foo.R", fix = TRUE)` | Find (and fix) CRAN-unsafe `print()` and `cat()` calls | +| `package_print_and_cat()` | `package_print_and_cat(fix = TRUE)` | Same, across `R/` and `tests/testthat/` | +| `detect_lost_glue_brace()` | `detect_lost_glue_brace("R/foo.R")` | Find lost braces in `glue` and `cli` strings | +| `package_lost_glue_brace()` | `package_lost_glue_brace()` | Same, across `R/` and `tests/testthat/` | +| `detect_unmatched_nocov_marker()` | `detect_unmatched_nocov_marker("R/foo.R")` | Find unmatched `# nocov` markers in one file | +| `package_unmatched_nocov_marker()` | `package_unmatched_nocov_marker()` | Same, across `R/` | +| `detect_fn_arg_path()` | `detect_fn_arg_path("R/foo.R")` | Find default `path` or `file` arguments in exported functions | +| `package_fn_arg_path()` | `package_fn_arg_path()` | Same, across exported functions of the package | +| `check_pkgdown_reference()` | `check_pkgdown_reference()` | Check that every export appears in `_pkgdown.yml` | +| `check_sysdeps()` | `check_sysdeps(c("libpng-dev"))` | Check whether system libraries are installed | +| `check_air_installed()` | `check_air_installed()` | Check that the `air` formatter is on the `PATH` | +| `flir_fix()` | `flir_fix("R/foo.R")` | Fix R code with `flir` | +| `air_format()` | `air_format("R/foo.R")` | Deprecated; format R code with `air` | + +### Manage `NEWS.md` + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `news_md_add_entry()` | `news_md_add_entry("Added a new feature.", category = "NEW FEATURES")` | Add an entry, creating the version section when needed | +| `news_md_show()` | `news_md_show(version = "latest")` | Print `NEWS.md`, optionally filtered to one version | +| `news_md_check()` | `news_md_check()` | Deprecated; validate the `NEWS.md` format | + +### Set up and maintain packages + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `use_zzz()` | `use_zzz()` | Create `R/-package.R` from a template | +| `use_r_v4.1.0()` | `use_r_v4.1.0()` | Add `R (>= 4.1.0)` to `Depends` | +| `use_url()` | `use_url()` | Set `URL` from the git remote, plus an optional pkgdown URL | +| `use_bugreports()` | `use_bugreports()` | Set `BugReports` from the git remote | +| `use_vendor()` | `use_vendor("wurli/pedant", "R/utils.R")` | Vendor permissively licensed code from GitHub | +| `add_global_rbuildignore()` | `add_global_rbuildignore()` | Add the global `.Rbuildignore` patterns | +| `add_global_gitgnore()` | `add_global_gitgnore()` | Add a GitHub-style global `.gitignore` | +| `use_jarl()` | `use_jarl()` | Create a `jarl.toml` configuration | +| `use_clangd()` | `use_clangd()` | Create a `.clangd` configuration with Rcpp include paths | +| `use_tidy_addin()` | `use_tidy_addin("my_addin", "Open my gadget")` | Register an exported function in the RStudio Addins menu | +| `use_workflow_version_update()` | `use_workflow_version_update()` | Add the version-bumper GitHub Actions workflow | +| `use_workflow_test_branch()` | `use_workflow_test_branch()` | Add a workflow that syncs `main` to the `test` branch | +| `use_workflow_rust_compatible_check()` | `use_workflow_rust_compatible_check()` | Add a Rust-compatible R-CMD-check workflow | +| `open_cffinit()` | `open_cffinit()` | Open the `cffinit` `CITATION.cff` generator in the browser | + +### README and documentation + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `badge_to_readme()` | `badge_to_readme(badge)` | Insert a badge into the README badges block | +| `badge_translated_by_ai()` | `badge_translated_by_ai(lang = "zh-cn")` | Generate an AI-translation disclaimer badge | +| `use_multilanguage_readme()` | `use_multilanguage_readme("zh-cn")` | Create translated README files and their badges | +| `render_rmd()` | `render_rmd("README.Rmd")` | Render an `.Rmd` or `.R` file to Markdown | +| `use_hexsticker()` | `use_hexsticker("man/figures/logo.png")` | Deprecated; add a hex sticker to the README title | + +### Standalone files + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `create_standalone()` | `create_standalone("my_utils")` | Create a standalone file with a YAML header | +| `check_standalone()` | `check_standalone("R/standalone-my_utils.R")` | Check the format of a standalone file | +| `update_time_in_standalone()` | `update_time_in_standalone()` | Refresh the last-updated field of standalone files | +| `add_changelog_in_standalone()` | `add_changelog_in_standalone("R/standalone-my_utils.R", "Fix a bug")` | Add or update a changelog entry | +| `inquire_standalone()` | `inquire_standalone("r-lib", "rlang")` | List the standalone files of a GitHub repository | +| `browse_standalone()` | `browse_standalone()` | Search GitHub for standalone files shipped by R packages | + +### Utilities + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `current_packages()` | `current_packages()` | Packages whose calls should be qualified | +| `imported_functions()` | `imported_functions()` | Function names imported in `NAMESPACE` | +| `is_dev_context()` | `is_dev_context()` | Whether the working directory is package development | +| `get_positron_version()` | `get_positron_version()` | Version of the running Positron IDE | + ## Addin After v0.1.23, `rpkgkit` ships an addin that can be used in RStudio. It's diff --git a/README.md b/README.md index a1a1e39..d7e4117 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,98 @@ It’s recommended to use following packages together with `rpkgkit`: - [`usethis`](https://usethis.r-lib.org/): manage package metadata. - [`devtools`](https://devtools.r-lib.org/): build and check package. +## Cheat sheet + +### Convert and check code + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `add_double_colons()` | `add_double_colons(code)` | Add `pkg::` qualifiers to calls in a code string | +| `make_func_call_explicit()` | `make_func_call_explicit("R/foo.R")` | Add `pkg::` qualifiers to every call in one file | +| `package_func_call_explicit()` | `package_func_call_explicit()` | Same, for every file under `R/` | +| `make_func_arg_explicit()` | `make_func_arg_explicit("R/foo.R")` | Add argument names to calls in one file | +| `package_func_arg_explicit()` | `package_func_arg_explicit()` | Same, for every file under `R/` | +| `rename_func()` | `rename_func("R/foo.R", style = "snake_case")` | Rename function definitions to a naming style | +| `convert_func_syntax()` | `convert_func_syntax("R/foo.R", direction = "to_lambda")` | Switch between `function()` and `\()` syntax | +| `convert_pipe()` | `convert_pipe("R/foo.R", direction = "to_base")` | Switch between the magrittr and base pipes in one file | +| `package_convert_pipe()` | `package_convert_pipe(direction = "to_base")` | Same, for every file under `R/` | +| `convert_int_literals()` | `convert_int_literals("R/foo.R")` | Add the integer `L` suffix in one file | +| `package_convert_int_literals()` | `package_convert_int_literals()` | Same, for every file under `R/` | +| `convert_nonascii_code()` | `convert_nonascii_code(code, reverse = FALSE)` | Escape non-ASCII characters (or restore them) | +| `convert_knitr_chunk_header()` | `convert_knitr_chunk_header()` | Modernize knitr chunk headers in `.Rmd` files | +| `optimize_rmd_yaml()` | `optimize_rmd_yaml("README.Rmd")` | Fill one YAML header from the package `DESCRIPTION` | +| `package_optimize_rmd_yaml()` | `package_optimize_rmd_yaml()` | Same, for `README.Rmd` and all vignettes | +| `detect_print_and_cat()` | `detect_print_and_cat("R/foo.R", fix = TRUE)` | Find (and fix) CRAN-unsafe `print()` and `cat()` calls | +| `package_print_and_cat()` | `package_print_and_cat(fix = TRUE)` | Same, across `R/` and `tests/testthat/` | +| `detect_lost_glue_brace()` | `detect_lost_glue_brace("R/foo.R")` | Find lost braces in `glue` and `cli` strings | +| `package_lost_glue_brace()` | `package_lost_glue_brace()` | Same, across `R/` and `tests/testthat/` | +| `detect_unmatched_nocov_marker()` | `detect_unmatched_nocov_marker("R/foo.R")` | Find unmatched `# nocov` markers in one file | +| `package_unmatched_nocov_marker()` | `package_unmatched_nocov_marker()` | Same, across `R/` | +| `detect_fn_arg_path()` | `detect_fn_arg_path("R/foo.R")` | Find default `path` or `file` arguments in exported functions | +| `package_fn_arg_path()` | `package_fn_arg_path()` | Same, across exported functions of the package | +| `check_pkgdown_reference()` | `check_pkgdown_reference()` | Check that every export appears in `_pkgdown.yml` | +| `check_sysdeps()` | `check_sysdeps(c("libpng-dev"))` | Check whether system libraries are installed | +| `check_air_installed()` | `check_air_installed()` | Check that the `air` formatter is on the `PATH` | +| `flir_fix()` | `flir_fix("R/foo.R")` | Fix R code with `flir` | +| `air_format()` | `air_format("R/foo.R")` | Deprecated; format R code with `air` | + +### Manage `NEWS.md` + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `news_md_add_entry()` | `news_md_add_entry("Added a new feature.", category = "NEW FEATURES")` | Add an entry, creating the version section when needed | +| `news_md_show()` | `news_md_show(version = "latest")` | Print `NEWS.md`, optionally filtered to one version | +| `news_md_check()` | `news_md_check()` | Deprecated; validate the `NEWS.md` format | + +### Set up and maintain packages + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `use_zzz()` | `use_zzz()` | Create `R/-package.R` from a template | +| `use_r_v4.1.0()` | `use_r_v4.1.0()` | Add `R (>= 4.1.0)` to `Depends` | +| `use_url()` | `use_url()` | Set `URL` from the git remote, plus an optional pkgdown URL | +| `use_bugreports()` | `use_bugreports()` | Set `BugReports` from the git remote | +| `use_vendor()` | `use_vendor("wurli/pedant", "R/utils.R")` | Vendor permissively licensed code from GitHub | +| `add_global_rbuildignore()` | `add_global_rbuildignore()` | Add the global `.Rbuildignore` patterns | +| `add_global_gitgnore()` | `add_global_gitgnore()` | Add a GitHub-style global `.gitignore` | +| `use_jarl()` | `use_jarl()` | Create a `jarl.toml` configuration | +| `use_clangd()` | `use_clangd()` | Create a `.clangd` configuration with Rcpp include paths | +| `use_tidy_addin()` | `use_tidy_addin("my_addin", "Open my gadget")` | Register an exported function in the RStudio Addins menu | +| `use_workflow_version_update()` | `use_workflow_version_update()` | Add the version-bumper GitHub Actions workflow | +| `use_workflow_test_branch()` | `use_workflow_test_branch()` | Add a workflow that syncs `main` to the `test` branch | +| `use_workflow_rust_compatible_check()` | `use_workflow_rust_compatible_check()` | Add a Rust-compatible R-CMD-check workflow | +| `open_cffinit()` | `open_cffinit()` | Open the `cffinit` `CITATION.cff` generator in the browser | + +### README and documentation + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `badge_to_readme()` | `badge_to_readme(badge)` | Insert a badge into the README badges block | +| `badge_translated_by_ai()` | `badge_translated_by_ai(lang = "zh-cn")` | Generate an AI-translation disclaimer badge | +| `use_multilanguage_readme()` | `use_multilanguage_readme("zh-cn")` | Create translated README files and their badges | +| `render_rmd()` | `render_rmd("README.Rmd")` | Render an `.Rmd` or `.R` file to Markdown | +| `use_hexsticker()` | `use_hexsticker("man/figures/logo.png")` | Deprecated; add a hex sticker to the README title | + +### Standalone files + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `create_standalone()` | `create_standalone("my_utils")` | Create a standalone file with a YAML header | +| `check_standalone()` | `check_standalone("R/standalone-my_utils.R")` | Check the format of a standalone file | +| `update_time_in_standalone()` | `update_time_in_standalone()` | Refresh the last-updated field of standalone files | +| `add_changelog_in_standalone()` | `add_changelog_in_standalone("R/standalone-my_utils.R", "Fix a bug")` | Add or update a changelog entry | +| `inquire_standalone()` | `inquire_standalone("r-lib", "rlang")` | List the standalone files of a GitHub repository | +| `browse_standalone()` | `browse_standalone()` | Search GitHub for standalone files shipped by R packages | + +### Utilities + +| Function | Quick usage | Purpose | +|:---|:---|:---| +| `current_packages()` | `current_packages()` | Packages whose calls should be qualified | +| `imported_functions()` | `imported_functions()` | Function names imported in `NAMESPACE` | +| `is_dev_context()` | `is_dev_context()` | Whether the working directory is package development | +| `get_positron_version()` | `get_positron_version()` | Version of the running Positron IDE | + ## Addin After v0.1.23, `rpkgkit` ships an addin that can be used in RStudio. diff --git a/inst/translations/README.es.md b/inst/translations/README.es.md index 41e9228..0e7a9db 100644 --- a/inst/translations/README.es.md +++ b/inst/translations/README.es.md @@ -61,6 +61,100 @@ Se recomienda usar los siguientes paquetes junto con `rpkgkit`: - [`usethis`](https://usethis.r-lib.org/): gestiona los metadatos del paquete. - [`devtools`](https://devtools.r-lib.org/): construye y comprueba el paquete. +## Hoja de referencia + +Todas las funciones exportadas con una llamada mínima. La mayoría acepta `path = NULL`, que significa «usar el archivo activo o el directorio del paquete actual». + +### Conversión y revisión de código + +| Función | Uso rápido | Propósito | +|:---|:---|:---| +| `add_double_colons()` | `add_double_colons(code)` | Añadir `pkg::` a las llamadas de una cadena de código | +| `make_func_call_explicit()` | `make_func_call_explicit("R/foo.R")` | Añadir `pkg::` a todas las llamadas de un archivo | +| `package_func_call_explicit()` | `package_func_call_explicit()` | Lo mismo, en todos los archivos de `R/` | +| `make_func_arg_explicit()` | `make_func_arg_explicit("R/foo.R")` | Añadir nombres de argumento a las llamadas de un archivo | +| `package_func_arg_explicit()` | `package_func_arg_explicit()` | Lo mismo, en todos los archivos de `R/` | +| `rename_func()` | `rename_func("R/foo.R", style = "snake_case")` | Renombrar las definiciones de función según un estilo | +| `convert_func_syntax()` | `convert_func_syntax("R/foo.R", direction = "to_lambda")` | Alternar entre la sintaxis `function()` y `\()` | +| `convert_pipe()` | `convert_pipe("R/foo.R", direction = "to_base")` | Alternar entre las tuberías de magrittr y la nativa en un archivo | +| `package_convert_pipe()` | `package_convert_pipe(direction = "to_base")` | Lo mismo, en todos los archivos de `R/` | +| `convert_int_literals()` | `convert_int_literals("R/foo.R")` | Añadir el sufijo entero `L` en un archivo | +| `package_convert_int_literals()` | `package_convert_int_literals()` | Lo mismo, en todos los archivos de `R/` | +| `convert_nonascii_code()` | `convert_nonascii_code(code, reverse = FALSE)` | Escapar los caracteres no ASCII (o restaurarlos) | +| `convert_knitr_chunk_header()` | `convert_knitr_chunk_header()` | Modernizar las cabeceras de chunk de knitr en archivos `.Rmd` | +| `optimize_rmd_yaml()` | `optimize_rmd_yaml("README.Rmd")` | Completar una cabecera YAML con el `DESCRIPTION` del paquete | +| `package_optimize_rmd_yaml()` | `package_optimize_rmd_yaml()` | Lo mismo, para `README.Rmd` y todas las viñetas | +| `detect_print_and_cat()` | `detect_print_and_cat("R/foo.R", fix = TRUE)` | Buscar (y corregir) llamadas a `print()` y `cat()` no aptas para CRAN | +| `package_print_and_cat()` | `package_print_and_cat(fix = TRUE)` | Lo mismo, en `R/` y `tests/testthat/` | +| `detect_lost_glue_brace()` | `detect_lost_glue_brace("R/foo.R")` | Buscar llaves perdidas en cadenas de `glue` y `cli` | +| `package_lost_glue_brace()` | `package_lost_glue_brace()` | Lo mismo, en `R/` y `tests/testthat/` | +| `detect_unmatched_nocov_marker()` | `detect_unmatched_nocov_marker("R/foo.R")` | Buscar marcadores `# nocov` sin pareja en un archivo | +| `package_unmatched_nocov_marker()` | `package_unmatched_nocov_marker()` | Lo mismo, en `R/` | +| `detect_fn_arg_path()` | `detect_fn_arg_path("R/foo.R")` | Buscar argumentos `path` o `file` con valor por defecto en funciones exportadas | +| `package_fn_arg_path()` | `package_fn_arg_path()` | Lo mismo, en las funciones exportadas del paquete | +| `check_pkgdown_reference()` | `check_pkgdown_reference()` | Comprobar que cada función exportada aparece en `_pkgdown.yml` | +| `check_sysdeps()` | `check_sysdeps(c("libpng-dev"))` | Comprobar si las librerías del sistema están instaladas | +| `check_air_installed()` | `check_air_installed()` | Comprobar que el formateador `air` está en el `PATH` | +| `flir_fix()` | `flir_fix("R/foo.R")` | Corregir código R con `flir` | +| `air_format()` | `air_format("R/foo.R")` | Obsoleta; formatear código R con `air` | + +### Gestionar `NEWS.md` + +| Función | Uso rápido | Propósito | +|:---|:---|:---| +| `news_md_add_entry()` | `news_md_add_entry("Added a new feature.", category = "NEW FEATURES")` | Añadir una entrada, creando la sección de versión si hace falta | +| `news_md_show()` | `news_md_show(version = "latest")` | Mostrar `NEWS.md`, opcionalmente filtrado a una versión | +| `news_md_check()` | `news_md_check()` | Obsoleta; validar el formato de `NEWS.md` | + +### Configuración y mantenimiento del paquete + +| Función | Uso rápido | Propósito | +|:---|:---|:---| +| `use_zzz()` | `use_zzz()` | Crear `R/-package.R` a partir de una plantilla | +| `use_r_v4.1.0()` | `use_r_v4.1.0()` | Añadir `R (>= 4.1.0)` a `Depends` | +| `use_url()` | `use_url()` | Definir `URL` desde el remoto de git, con una URL de pkgdown opcional | +| `use_bugreports()` | `use_bugreports()` | Definir `BugReports` desde el remoto de git | +| `use_vendor()` | `use_vendor("wurli/pedant", "R/utils.R")` | Incorporar código con licencia permisiva desde GitHub | +| `add_global_rbuildignore()` | `add_global_rbuildignore()` | Añadir los patrones globales de `.Rbuildignore` | +| `add_global_gitgnore()` | `add_global_gitgnore()` | Añadir un `.gitignore` global al estilo de GitHub | +| `use_jarl()` | `use_jarl()` | Crear un archivo de configuración `jarl.toml` | +| `use_clangd()` | `use_clangd()` | Crear un archivo `.clangd` con las rutas de inclusión de Rcpp | +| `use_tidy_addin()` | `use_tidy_addin("my_addin", "Open my gadget")` | Registrar una función exportada en el menú Addins de RStudio | +| `use_workflow_version_update()` | `use_workflow_version_update()` | Añadir el flujo de GitHub Actions que actualiza la versión | +| `use_workflow_test_branch()` | `use_workflow_test_branch()` | Añadir un flujo que sincroniza `main` con la rama `test` | +| `use_workflow_rust_compatible_check()` | `use_workflow_rust_compatible_check()` | Añadir un flujo de R-CMD-check compatible con Rust | +| `open_cffinit()` | `open_cffinit()` | Abrir en el navegador el generador `CITATION.cff` de `cffinit` | + +### README y documentación + +| Función | Uso rápido | Propósito | +|:---|:---|:---| +| `badge_to_readme()` | `badge_to_readme(badge)` | Insertar una insignia en el bloque de insignias del README | +| `badge_translated_by_ai()` | `badge_translated_by_ai(lang = "zh-cn")` | Generar una insignia de aviso de traducción por IA | +| `use_multilanguage_readme()` | `use_multilanguage_readme("zh-cn")` | Crear archivos README traducidos y sus insignias | +| `render_rmd()` | `render_rmd("README.Rmd")` | Renderizar un archivo `.Rmd` o `.R` a Markdown | +| `use_hexsticker()` | `use_hexsticker("man/figures/logo.png")` | Obsoleta; añadir un hex sticker al título del README | + +### Archivos independientes + +| Función | Uso rápido | Propósito | +|:---|:---|:---| +| `create_standalone()` | `create_standalone("my_utils")` | Crear un archivo independiente con cabecera YAML | +| `check_standalone()` | `check_standalone("R/standalone-my_utils.R")` | Comprobar el formato de un archivo independiente | +| `update_time_in_standalone()` | `update_time_in_standalone()` | Actualizar el campo de última modificación | +| `add_changelog_in_standalone()` | `add_changelog_in_standalone("R/standalone-my_utils.R", "Fix a bug")` | Añadir o actualizar una entrada del registro de cambios | +| `inquire_standalone()` | `inquire_standalone("r-lib", "rlang")` | Listar los archivos independientes de un repositorio de GitHub | +| `browse_standalone()` | `browse_standalone()` | Buscar en GitHub archivos independientes publicados por paquetes R | + +### Utilidades + +| Función | Uso rápido | Propósito | +|:---|:---|:---| +| `current_packages()` | `current_packages()` | Paquetes cuyas llamadas conviene calificar | +| `imported_functions()` | `imported_functions()` | Nombres de funciones importadas en `NAMESPACE` | +| `is_dev_context()` | `is_dev_context()` | Si el directorio actual es un entorno de desarrollo de paquetes | +| `get_positron_version()` | `get_positron_version()` | Versión del IDE Positron en ejecución | + ## Addin A partir de la v0.1.23, `rpkgkit` incluye un addin que se puede usar en RStudio. Está disponible en el menú `Addins` y también se puede abrir con `Ctrl+Shift+P` (Windows/Linux) o `Cmd+Shift+P` (macOS). diff --git a/inst/translations/README.zh-cn.md b/inst/translations/README.zh-cn.md index a052059..2f63dad 100644 --- a/inst/translations/README.zh-cn.md +++ b/inst/translations/README.zh-cn.md @@ -61,6 +61,100 @@ pak::pak("WangLabCSU/rpkgkit") - [`usethis`](https://usethis.r-lib.org/):管理包元数据。 - [`devtools`](https://devtools.r-lib.org/):构建和检查包。 +## 速查表 + +下表列出所有导出函数及其最简调用方式。多数函数接受 `path = NULL`,表示“使用当前活动文件或当前包目录”。 + +### 代码转换与检查 + +| 函数名 | 简单用法 | 用途 | +|:---|:---|:---| +| `add_double_colons()` | `add_double_colons(code)` | 为代码字符串中的调用添加 `pkg::` 限定 | +| `make_func_call_explicit()` | `make_func_call_explicit("R/foo.R")` | 为单个文件中的所有调用添加 `pkg::` 限定 | +| `package_func_call_explicit()` | `package_func_call_explicit()` | 同上,处理 `R/` 下的所有文件 | +| `make_func_arg_explicit()` | `make_func_arg_explicit("R/foo.R")` | 为单个文件中的调用补全参数名 | +| `package_func_arg_explicit()` | `package_func_arg_explicit()` | 同上,处理 `R/` 下的所有文件 | +| `rename_func()` | `rename_func("R/foo.R", style = "snake_case")` | 按指定命名风格重命名函数定义 | +| `convert_func_syntax()` | `convert_func_syntax("R/foo.R", direction = "to_lambda")` | 在 `function()` 与 `\()` 语法之间转换 | +| `convert_pipe()` | `convert_pipe("R/foo.R", direction = "to_base")` | 在 magrittr 管道与原生管道之间转换单个文件 | +| `package_convert_pipe()` | `package_convert_pipe(direction = "to_base")` | 同上,处理 `R/` 下的所有文件 | +| `convert_int_literals()` | `convert_int_literals("R/foo.R")` | 为单个文件中的整数补上 `L` 后缀 | +| `package_convert_int_literals()` | `package_convert_int_literals()` | 同上,处理 `R/` 下的所有文件 | +| `convert_nonascii_code()` | `convert_nonascii_code(code, reverse = FALSE)` | 将非 ASCII 字符转义(或还原) | +| `convert_knitr_chunk_header()` | `convert_knitr_chunk_header()` | 将 `.Rmd` 中的 knitr 旧式代码块头部转换为新语法 | +| `optimize_rmd_yaml()` | `optimize_rmd_yaml("README.Rmd")` | 用 DESCRIPTION 补全单个文件的 YAML 头部 | +| `package_optimize_rmd_yaml()` | `package_optimize_rmd_yaml()` | 同上,处理 `README.Rmd` 和所有 vignette | +| `detect_print_and_cat()` | `detect_print_and_cat("R/foo.R", fix = TRUE)` | 查找(并修复)CRAN 不允许的 `print()` 和 `cat()` 调用 | +| `package_print_and_cat()` | `package_print_and_cat(fix = TRUE)` | 同上,范围包括 `R/` 和 `tests/testthat/` | +| `detect_lost_glue_brace()` | `detect_lost_glue_brace("R/foo.R")` | 查找 `glue` 和 `cli` 字符串中丢失的花括号 | +| `package_lost_glue_brace()` | `package_lost_glue_brace()` | 同上,范围包括 `R/` 和 `tests/testthat/` | +| `detect_unmatched_nocov_marker()` | `detect_unmatched_nocov_marker("R/foo.R")` | 查找单个文件中未配对的 `# nocov` 标记 | +| `package_unmatched_nocov_marker()` | `package_unmatched_nocov_marker()` | 同上,处理 `R/` 下的所有文件 | +| `detect_fn_arg_path()` | `detect_fn_arg_path("R/foo.R")` | 查找导出函数中默认值为 `path` 或 `file` 的参数 | +| `package_fn_arg_path()` | `package_fn_arg_path()` | 同上,检查包内所有导出函数 | +| `check_pkgdown_reference()` | `check_pkgdown_reference()` | 检查所有导出函数是否都出现在 `_pkgdown.yml` 中 | +| `check_sysdeps()` | `check_sysdeps(c("libpng-dev"))` | 检查系统库是否已安装 | +| `check_air_installed()` | `check_air_installed()` | 检查 `air` 格式化工具是否在 `PATH` 中 | +| `flir_fix()` | `flir_fix("R/foo.R")` | 使用 `flir` 修复 R 代码 | +| `air_format()` | `air_format("R/foo.R")` | 已弃用;使用 `air` 格式化 R 代码 | + +### 管理 `NEWS.md` + +| 函数名 | 简单用法 | 用途 | +|:---|:---|:---| +| `news_md_add_entry()` | `news_md_add_entry("Added a new feature.", category = "NEW FEATURES")` | 添加条目,必要时自动创建版本小节 | +| `news_md_show()` | `news_md_show(version = "latest")` | 显示 `NEWS.md`,可只显示某个版本 | +| `news_md_check()` | `news_md_check()` | 已弃用;校验 `NEWS.md` 格式 | + +### 包设置与维护 + +| 函数名 | 简单用法 | 用途 | +|:---|:---|:---| +| `use_zzz()` | `use_zzz()` | 由模板创建 `R/-package.R` | +| `use_r_v4.1.0()` | `use_r_v4.1.0()` | 在 `Depends` 中添加 `R (>= 4.1.0)` | +| `use_url()` | `use_url()` | 由 git 远程地址设置 `URL`,可附加 pkgdown 网址 | +| `use_bugreports()` | `use_bugreports()` | 由 git 远程地址设置 `BugReports` | +| `use_vendor()` | `use_vendor("wurli/pedant", "R/utils.R")` | 从 GitHub 引入宽松许可证代码 | +| `add_global_rbuildignore()` | `add_global_rbuildignore()` | 添加全局 `.Rbuildignore` 规则 | +| `add_global_gitgnore()` | `add_global_gitgnore()` | 添加 GitHub 风格的全局 `.gitignore` | +| `use_jarl()` | `use_jarl()` | 创建 `jarl.toml` 配置文件 | +| `use_clangd()` | `use_clangd()` | 创建包含 Rcpp 头文件路径的 `.clangd` 配置 | +| `use_tidy_addin()` | `use_tidy_addin("my_addin", "Open my gadget")` | 将导出函数注册到 RStudio Addins 菜单 | +| `use_workflow_version_update()` | `use_workflow_version_update()` | 添加自动更新版本号的 GitHub Actions 工作流 | +| `use_workflow_test_branch()` | `use_workflow_test_branch()` | 添加将 `main` 同步到 `test` 分支的工作流 | +| `use_workflow_rust_compatible_check()` | `use_workflow_rust_compatible_check()` | 添加兼容 Rust 的 R-CMD-check 工作流 | +| `open_cffinit()` | `open_cffinit()` | 在浏览器中打开 `cffinit` 的 `CITATION.cff` 生成器 | + +### README 与文档 + +| 函数名 | 简单用法 | 用途 | +|:---|:---|:---| +| `badge_to_readme()` | `badge_to_readme(badge)` | 将徽章插入 README 徽章区 | +| `badge_translated_by_ai()` | `badge_translated_by_ai(lang = "zh-cn")` | 生成“AI 翻译”免责声明徽章 | +| `use_multilanguage_readme()` | `use_multilanguage_readme("zh-cn")` | 创建多语言 README 文件及其徽章 | +| `render_rmd()` | `render_rmd("README.Rmd")` | 将 `.Rmd` 或 `.R` 文件渲染为 Markdown | +| `use_hexsticker()` | `use_hexsticker("man/figures/logo.png")` | 已弃用;在 README 标题处添加六边形贴纸 | + +### 独立脚本 + +| 函数名 | 简单用法 | 用途 | +|:---|:---|:---| +| `create_standalone()` | `create_standalone("my_utils")` | 创建带 YAML 头部的独立脚本文件 | +| `check_standalone()` | `check_standalone("R/standalone-my_utils.R")` | 检查独立脚本文件的格式 | +| `update_time_in_standalone()` | `update_time_in_standalone()` | 更新独立脚本的最后修改时间字段 | +| `add_changelog_in_standalone()` | `add_changelog_in_standalone("R/standalone-my_utils.R", "Fix a bug")` | 添加或更新变更日志条目 | +| `inquire_standalone()` | `inquire_standalone("r-lib", "rlang")` | 列出某个 GitHub 仓库中的独立脚本文件 | +| `browse_standalone()` | `browse_standalone()` | 在 GitHub 上搜索 R 包提供的独立脚本文件 | + +### 工具函数 + +| 函数名 | 简单用法 | 用途 | +|:---|:---|:---| +| `current_packages()` | `current_packages()` | 需要为其调用添加命名空间的包 | +| `imported_functions()` | `imported_functions()` | `NAMESPACE` 中导入的函数名 | +| `is_dev_context()` | `is_dev_context()` | 当前目录是否为包开发环境 | +| `get_positron_version()` | `get_positron_version()` | 当前运行的 Positron IDE 版本 | + ## Addin 自 v0.1.23 起,`rpkgkit` 附带了一个可在 RStudio 中使用的 addin。它位于 `Addins` 菜单中,也可以通过 `Ctrl+Shift+P`(Windows/Linux)或 `Cmd+Shift+P`(macOS)访问。 From 0a4ff144c428917a4c5b31e10b448aa187f8d0b5 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Thu, 5 Nov 2026 06:36:20 -0500 Subject: [PATCH 14/35] patch update: * Added `use_air_table()` to lay out long `c()` and `list()` calls as column-aligned tables with `air` 0.8.0 or newer. A first `air format` run leaves every element on its own line; the experimental `# fmt: table` directive is then inserted above every call holding more than `min_length` elements and the elements are re-flowed so that each row holds `ncol` of them, by collapsing the line breaks inside a row or, for a definition that air kept on a single line, by splitting it into rows. A second `air format` run pads the cells and aligns the columns. Only calls whose elements are all unnamed are converted, because air expands named elements one per line whatever the directive says; only the outermost call of a statement is converted, because air ignores the directive on nested calls; a line ending in a comment is never joined with the next one, which would swallow the following element; and a call that already carries the directive is left untouched, so the function is idempotent. `path = NULL` falls back to the active RStudio document, `air` must be on the `PATH` (checked with `check_air_installed()`), and the normalized path is returned invisibly. * The startup message is now a `cli` progress step: `.onLoad()` starts `cli::cli_progress_step()` and `.onAttach()` closes it with `cli::cli_process_done()`, which also covers the time spent loading the namespace. The hand-written `cli_timestamp_formatter()` helper, which formatted the elapsed time by hand, is gone, and the `use_zzz()` template (`inst/R_template/zzz_template.R`) follows the same pattern. * The `code_convertion` vignette gained a "Lay out long vectors and lists as tables" section covering `use_air_table()` and its requirements. * `use_air_table()` is listed in the README, in both translations under `inst/translations/`, and in the `_pkgdown.yml` reference index. * The package is now spell-checked: `spelling` was added to `Suggests` together with `Language: en-US`, `inst/WORDLIST` holds the accepted words, and `tests/spelling.R` runs `spelling::spell_check_test()`. --- DESCRIPTION | 1 + NAMESPACE | 1 + NEWS.md | 40 +++ R/54_use_air_table_.R | 527 ++++++++++++++++++++++++++++ R/rpkgkit-package.R | 41 +-- README.Rmd | 1 + README.md | 1 + _pkgdown.yml | 1 + inst/R_template/zzz_template.R | 41 +-- inst/WORDLIST | 113 ++++++ inst/translations/README.es.md | 1 + inst/translations/README.zh-cn.md | 1 + man/dot-at_call_ids.Rd | 18 + man/dot-at_call_info.Rd | 25 ++ man/dot-at_collapse.Rd | 24 ++ man/dot-at_has_call_ancestor.Rd | 22 ++ man/dot-at_join_flags.Rd | 28 ++ man/dot-at_parse.Rd | 20 ++ man/dot-at_rows.Rd | 20 ++ man/dot-at_run_air.Rd | 18 + man/dot-at_split_lines.Rd | 24 ++ man/dot-at_targets.Rd | 26 ++ man/use_air_table.Rd | 79 +++++ tests/spelling.R | 3 + tests/testthat/test-use_air_table.R | 454 ++++++++++++++++++++++++ vignettes/code_convertion.Rmd | 37 ++ 26 files changed, 1505 insertions(+), 62 deletions(-) create mode 100644 R/54_use_air_table_.R create mode 100644 inst/WORDLIST create mode 100644 man/dot-at_call_ids.Rd create mode 100644 man/dot-at_call_info.Rd create mode 100644 man/dot-at_collapse.Rd create mode 100644 man/dot-at_has_call_ancestor.Rd create mode 100644 man/dot-at_join_flags.Rd create mode 100644 man/dot-at_parse.Rd create mode 100644 man/dot-at_rows.Rd create mode 100644 man/dot-at_run_air.Rd create mode 100644 man/dot-at_split_lines.Rd create mode 100644 man/dot-at_targets.Rd create mode 100644 man/use_air_table.Rd create mode 100644 tests/spelling.R create mode 100644 tests/testthat/test-use_air_table.R diff --git a/DESCRIPTION b/DESCRIPTION index 5e86d01..19dc330 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -39,6 +39,7 @@ Suggests: knitr, pkgload, rmarkdown, + spelling, stats, testthat (>= 3.0.0), usethis, diff --git a/NAMESPACE b/NAMESPACE index 7bc7c0c..0b68a32 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -47,6 +47,7 @@ export(package_unmatched_nocov_marker) export(rename_func) export(render_rmd) export(update_time_in_standalone) +export(use_air_table) export(use_bugreports) export(use_clangd) export(use_hexsticker) diff --git a/NEWS.md b/NEWS.md index 8abe18b..3ebea8f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,43 @@ +# rpkgkit 0.1.24 (2026-11-08) + +## NEW FEATURES + +* Added `use_air_table()` to lay out long `c()` and `list()` calls as + column-aligned tables with `air` 0.8.0 or newer. A first `air format` run + leaves every element on its own line; the experimental `# fmt: table` + directive is then inserted above every call holding more than `min_length` + elements and the elements are re-flowed so that each row holds `ncol` of them, + by collapsing the line breaks inside a row or, for a definition that air kept + on a single line, by splitting it into rows. A second `air format` run pads + the cells and aligns the columns. Only calls whose elements are all unnamed + are converted, because air expands named elements one per line whatever the + directive says; only the outermost call of a statement is converted, because + air ignores the directive on nested calls; a line ending in a comment is never + joined with the next one, which would swallow the following element; and a + call that already carries the directive is left untouched, so the function is + idempotent. `path = NULL` falls back to the active RStudio document, `air` + must be on the `PATH` (checked with `check_air_installed()`), and the + normalized path is returned invisibly. + +## MINOR IMPROVEMENTS + +* The startup message is now a `cli` progress step: `.onLoad()` starts + `cli::cli_progress_step()` and `.onAttach()` closes it with + `cli::cli_process_done()`, which also covers the time spent loading the + namespace. The hand-written `cli_timestamp_formatter()` helper, which + formatted the elapsed time by hand, is gone, and the `use_zzz()` template + (`inst/R_template/zzz_template.R`) follows the same pattern. + +## DOCUMENTATION + +* The `code_convertion` vignette gained a "Lay out long vectors and lists as + tables" section covering `use_air_table()` and its requirements. +* `use_air_table()` is listed in the README, in both translations under + `inst/translations/`, and in the `_pkgdown.yml` reference index. +* The package is now spell-checked: `spelling` was added to `Suggests` together + with `Language: en-US`, `inst/WORDLIST` holds the accepted words, and + `tests/spelling.R` runs `spelling::spell_check_test()`. + # rpkgkit 0.1.23 (2026-11-01) ## NEW FEATURES diff --git a/R/54_use_air_table_.R b/R/54_use_air_table_.R new file mode 100644 index 0000000..9a72b57 --- /dev/null +++ b/R/54_use_air_table_.R @@ -0,0 +1,527 @@ +#' Format Long Vectors and Lists as Aligned Tables with Air +#' +#' @description +#' Air (\eqn{\geq} 0.8.0) can align the elements of a call column by column, +#' giving the same layout as \code{tibble::tribble()} or +#' \code{data.table::fcase()}. The feature is switched on by the experimental +#' \code{# fmt: table} comment directive placed right above the call, but air +#' never re-flows the elements on its own: whatever sits on one source line +#' stays there. +#' +#' [use_air_table()] does the two things air does not do by itself: +#' +#' 1. runs \code{air format} on \code{path}, so every long vector and list is +#' laid out with one element per line; +#' 2. inserts the directive above every \code{c()} / \code{list()} call that +#' has more than \code{min_length} elements, and re-flows the elements so +#' that each row holds \code{ncol} of them. Multi-line definitions are +#' collapsed by deleting the line breaks between the elements of a row; +#' a definition that air kept on a single line is split into rows instead. +#' +#' A second \code{air format} run then pads the cells and aligns the columns. +#' +#' @param path Path to an R file to modify. If \code{NULL} and RStudio is +#' available, the path of the active document is used. +#' @param ncol Number of elements placed on each table row. +#' @param min_length A vector or list is only converted when it has strictly +#' more than this many elements. +#' @param marker The comment directive that enables table formatting in air. +#' @param ... Additional arguments. Currently unused and must be empty. +#' +#' @return Invisibly returns the normalized \code{path}. +#' +#' @details +#' Requirements and scope: +#' +#' - \code{air} must be installed and on the \code{PATH} (see +#' [check_air_installed()]), and the directive requires air 0.8.0 or newer. +#' - Only calls whose elements are **all unnamed** are rewritten. Air expands +#' named elements (\code{list(a = 1)}) one per line no matter what the +#' directive says, so named calls are skipped to avoid a marker that has no +#' effect. +#' - Calls that already carry \code{marker} on the preceding line are left +#' untouched, so the function is idempotent. +#' - Air only honours the directive on the outermost call of a statement, so a +#' vector or list nested inside another call (for example an argument of +#' \code{x <- list(a = c(...))}) is skipped. +#' +#' @examples +#' \dontrun{ +#' tf <- tempfile(fileext = ".R") +#' writeLines( +#' 'x <- c("alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta")', +#' tf +#' ) +#' use_air_table(tf, ncol = 3L, min_length = 6L) +#' readLines(tf) |> cli::cli_code() +#' } +#' +#' @export +use_air_table <- function( + path = NULL, + ncol = 3L, + min_length = 12L, + marker = "# fmt: table", + ... +) { + rlang::check_dots_empty() + rlang::check_number_whole(ncol, min = 1) + rlang::check_number_whole(min_length, min = 0) + rlang::check_string(marker) + check_air_installed() + + path <- path %||% + if (rstudioapi::isAvailable()) rstudioapi::getActiveDocumentContext()$path + if (is.null(path) || !nzchar(path)) { + cli::cli_abort(c("x" = "{.arg path} is required")) + } + if (!file.exists(path)) { + cli::cli_abort(c("x" = "{.file {path}} does not exist.")) + } + path <- normalizePath(path = path, mustWork = TRUE) + + # Fail fast with a readable message instead of air's verbose diagnostics. + .at_parse( + lines = readLines(con = path, warn = FALSE), + path = path + ) + .at_run_air(path = path) + + lines <- readLines(con = path, warn = FALSE) + targets <- .at_targets( + lines = lines, + path = path, + min_length = min_length, + marker = marker + ) + if (nrow(targets) == 0L) { + cli::cli_alert_info( + "No vector or list with more than {min_length} element{?s} found in {.file {path}}." + ) + return(invisible(path)) + } + + new_lines <- .at_collapse( + lines = lines, + targets = targets, + ncol = ncol, + marker = marker + ) + writeLines(text = new_lines, con = path) + + .at_run_air(path = path) + + cli::cli_alert_success( + "Converted {nrow(targets)} vector{?s}/list{?s} to {ncol}-column table{?s} in {.file {path}}." + ) + + invisible(path) +} + + +#' Internal: run `air format` and abort on failure +#' +#' @param path Path to the file to format. +#' +#' @return Invisibly returns `path`. +#' +#' @keywords internal +.at_run_air <- function(path) { + out <- suppressWarnings( + system2( + command = "air", + args = c("format", shQuote(path)), + stdout = TRUE, + stderr = TRUE + ) + ) + status <- attr(out, "status") %||% 0L + if (!identical(as.integer(status), 0L)) { + details <- utils::head(out[nzchar(out)], 5L) + cli::cli_abort(c( + "x" = "{.pkg air} failed to format {.file {path}}.", + "i" = "{paste(details, collapse = '\n')}" + )) + } + + invisible(path) +} + + +#' Internal: parse a file, aborting on invalid R code +#' +#' @param lines Character vector of the file contents. +#' @param path Path of the file, used in the error message. +#' +#' @return The parsed expressions. +#' +#' @keywords internal +.at_parse <- function(lines, path) { + tryCatch( + suppressWarnings( + parse(text = paste(lines, collapse = "\n"), keep.source = TRUE) + ), + error = function(e) { + cli::cli_abort(c( + "x" = "{.file {path}} is not valid R code.", + "i" = "{conditionMessage(e)}" + )) + } + ) +} + + +#' Internal: locate long vector and list definitions +#' +#' @param lines Character vector of the file contents. +#' @param path Path of the file, used in error messages. +#' @param min_length Minimum number of elements (exclusive). +#' @param marker The air table directive. +#' +#' @return A data frame with one row per target and the list-column +#' `elements` (position of every element), or an empty data frame with the +#' same columns when nothing qualifies. +#' +#' @keywords internal +.at_targets <- function(lines, path, min_length, marker) { + empty <- data.frame( + line1 = integer(), + line2 = integer(), + col1 = integer(), + n = integer(), + multiline = logical(), + stringsAsFactors = FALSE + ) + empty$elements <- list() + + exprs <- .at_parse(lines = lines, path = path) + if (length(exprs) == 0L) { + return(empty) + } + pd <- utils::getParseData(exprs) + if (is.null(pd) || nrow(pd) == 0L) { + return(empty) + } + + fn_syms <- pd[ + pd$token == "SYMBOL_FUNCTION_CALL" & pd$text %in% c("c", "list"), + , + drop = FALSE + ] + if (nrow(fn_syms) == 0L) { + return(empty) + } + + call_ids <- .at_call_ids(pd) + found <- vector("list", nrow(fn_syms)) + for (i in seq_len(nrow(fn_syms))) { + info <- .at_call_info( + pd = pd, + sym_id = fn_syms$id[[i]], + call_ids = call_ids, + min_length = min_length + ) + if (is.null(info)) { + next + } + line <- info$line1 + if (line > 1L && identical(trimws(lines[line - 1L]), marker)) { + next + } + found[[i]] <- info + } + found <- found[!vapply(found, is.null, logical(1L))] + if (length(found) == 0L) { + return(empty) + } + + # Keep the outermost call of nested candidates, and keep source order. + found <- found[order( + vapply(found, `[[`, integer(1L), "line1"), + vapply(found, `[[`, integer(1L), "col1") + )] + keep <- logical(length(found)) + last_line2 <- -Inf + for (i in seq_along(found)) { + if (found[[i]]$line1 > last_line2) { + keep[[i]] <- TRUE + last_line2 <- found[[i]]$line2 + } + } + found <- found[keep] + + out <- data.frame( + line1 = vapply(found, `[[`, integer(1L), "line1"), + line2 = vapply(found, `[[`, integer(1L), "line2"), + col1 = vapply(found, `[[`, integer(1L), "col1"), + n = vapply(found, `[[`, integer(1L), "n"), + multiline = vapply(found, `[[`, logical(1L), "multiline"), + stringsAsFactors = FALSE + ) + out$elements <- lapply(found, `[[`, "elements") + + out +} + + +#' Internal: describe one `c()` / `list()` call +#' +#' @param pd Parse data as returned by `getParseData()`. +#' @param sym_id Id of the `SYMBOL_FUNCTION_CALL` row. +#' @param call_ids Ids returned by `.at_call_ids()`. +#' @param min_length Minimum number of elements (exclusive). +#' +#' @return `NULL` when the call does not qualify, otherwise a list with +#' `line1`, `line2`, `col1`, `n`, `multiline` and `elements`. +#' +#' @keywords internal +.at_call_info <- function(pd, sym_id, call_ids, min_length) { + fn_expr_id <- pd$parent[pd$id == sym_id] + if (length(fn_expr_id) != 1L) { + return(NULL) + } + call_id <- pd$parent[pd$id == fn_expr_id] + if (length(call_id) != 1L) { + return(NULL) + } + call_row <- pd[pd$id == call_id, , drop = FALSE] + if (nrow(call_row) != 1L || call_row$token != "expr") { + return(NULL) + } + + kids <- pd[pd$parent == call_id, , drop = FALSE] + if (any(kids$token %in% c("SYMBOL_SUB", "EQ_SUB"))) { + # Air refuses to build a table out of named elements. + return(NULL) + } + if ( + .at_has_call_ancestor( + pd = pd, + call_id = call_id, + call_ids = call_ids + ) + ) { + # Air only honours the directive for the outermost call of a statement. + return(NULL) + } + is_separator <- kids$terminal & kids$text %in% c("(", ")", ",") + is_comment <- kids$token == "COMMENT" + is_element <- !kids$id %in% fn_expr_id & !is_separator & !is_comment + elements <- kids[is_element, c("line1", "col1", "line2", "col2")] + elements <- elements[order(elements$line1, elements$col1), , drop = FALSE] + n <- nrow(elements) + if (n <= min_length) { + return(NULL) + } + + list( + line1 = as.integer(call_row$line1), + line2 = as.integer(call_row$line2), + col1 = as.integer(call_row$col1), + n = as.integer(n), + multiline = call_row$line2 > call_row$line1, + elements = elements + ) +} + + +#' Internal: ids of all call expressions +#' +#' @param pd Parse data as returned by `getParseData()`. +#' +#' @return An integer vector of `expr` ids that are function calls. +#' +#' @keywords internal +.at_call_ids <- function(pd) { + fn_expr <- pd$parent[pd$token == "SYMBOL_FUNCTION_CALL"] + call_ids <- pd$parent[match(fn_expr, pd$id)] + + unique(call_ids[!is.na(call_ids)]) +} + + +#' Internal: is the call nested inside another call? +#' +#' @param pd Parse data as returned by `getParseData()`. +#' @param call_id Id of the call expression. +#' @param call_ids Ids returned by `.at_call_ids()`. +#' +#' @return A single logical. +#' +#' @keywords internal +.at_has_call_ancestor <- function(pd, call_id, call_ids) { + parent <- pd$parent[pd$id == call_id] + while (length(parent) == 1L && parent > 0L) { + if (parent %in% call_ids) { + return(TRUE) + } + parent <- pd$parent[pd$id == parent] + } + + FALSE +} + + +#' Internal: insert the directive and re-flow the elements +#' +#' @param lines Character vector of the file contents. +#' @param targets Data frame returned by `.at_targets()`. +#' @param ncol Number of elements per row. +#' @param marker The air table directive to insert. +#' +#' @return A character vector with the modified file contents. +#' +#' @keywords internal +.at_collapse <- function(lines, targets, ncol, marker) { + n_lines <- length(lines) + insert <- rep(NA_character_, n_lines) + join <- logical(n_lines) + replace <- vector("list", n_lines) + + for (i in seq_len(nrow(targets))) { + first <- targets$line1[[i]] + indent <- sub("^([ \t]*).*$", "\\1", lines[[first]]) + marker_line <- paste0(indent, marker) + + if (isTRUE(targets$multiline[[i]])) { + insert[[first]] <- marker_line + join <- .at_join_flags( + join = join, + elements = targets$elements[[i]], + ncol = ncol, + lines = lines + ) + } else { + replace[[first]] <- c( + marker_line, + .at_split_lines( + line = lines[[first]], + call_col1 = targets$col1[[i]], + elements = targets$elements[[i]], + ncol = ncol + ) + ) + } + } + + out <- list() + pos <- 0L + for (i in seq_len(n_lines)) { + if (!is.null(replace[[i]])) { + for (chunk in replace[[i]]) { + pos <- pos + 1L + out[[pos]] <- chunk + } + next + } + if (!is.na(insert[[i]])) { + pos <- pos + 1L + out[[pos]] <- insert[[i]] + } + if (join[[i]] && pos > 0L) { + out[[pos]] <- paste0(out[[pos]], " ", trimws(lines[[i]])) + } else { + pos <- pos + 1L + out[[pos]] <- lines[[i]] + } + } + + unlist(out, use.names = FALSE) +} + + +#' Internal: rows of element indices +#' +#' @param n Number of elements. +#' @param ncol Number of elements per row. +#' +#' @return A list of integer vectors. +#' +#' @keywords internal +.at_rows <- function(n, ncol) { + split( + seq_len(n), + rep(seq_len(ceiling(n / ncol)), each = ncol, length.out = n) + ) +} + + +#' Internal: flag the line breaks that disappear when rows are collapsed +#' +#' @param join Logical vector of line-break flags to update. +#' @param elements Data frame of element positions. +#' @param ncol Number of elements per row. +#' @param lines Character vector of the file contents. +#' +#' @return The updated `join` vector. +#' +#' @details +#' A line ending in a comment is never joined with the next one: the joined +#' element would be swallowed by the comment and silently disappear. +#' +#' @keywords internal +.at_join_flags <- function(join, elements, ncol, lines) { + for (row in .at_rows(nrow(elements), ncol)) { + if (length(row) < 2L) { + next + } + for (k in seq_len(length(row) - 1L)) { + from <- elements$line2[[row[[k]]]] + to <- elements$line1[[row[[k + 1L]]]] + if (to != from + 1L) { + next + } + trailing <- substring( + lines[[from]], + elements$col2[[row[[k]]]] + 1L, + nchar(lines[[from]]) + ) + if (!grepl("#", trailing, fixed = TRUE)) { + join[[to]] <- TRUE + } + } + } + + join +} + + +#' Internal: rewrite a single-line definition as a table +#' +#' @param line The source line holding the whole call. +#' @param call_col1 Column where the call starts. +#' @param elements Data frame of element positions. +#' @param ncol Number of elements per row. +#' +#' @return A character vector of replacement lines, without the directive. +#' +#' @keywords internal +.at_split_lines <- function(line, call_col1, elements, ncol) { + indent <- sub("^([ \t]*).*$", "\\1", line) + prefix <- substr(line, 1L, call_col1 - 1L) + open <- trimws( + substr(line, call_col1, elements$col1[[1L]] - 1L), + which = "right" + ) + cells <- substring( + line, + elements$col1, + elements$col2 + ) + close_col <- elements$col2[[nrow(elements)]] + 1L + close <- substring(line, close_col, nchar(line)) + + rows <- .at_rows(length(cells), ncol) + row_text <- vapply( + rows, + function(row) paste0(cells[row], collapse = ", "), + character(1L) + ) + row_text <- paste0(row_text, c(rep(",", length(row_text) - 1L), "")) + + c( + paste0(prefix, open), + paste0(indent, " ", row_text), + paste0(indent, close) + ) +} diff --git a/R/rpkgkit-package.R b/R/rpkgkit-package.R index 22fa741..68bd604 100644 --- a/R/rpkgkit-package.R +++ b/R/rpkgkit-package.R @@ -21,19 +21,21 @@ .onAttach <- function(libname, pkgname) { if (startup_message_allowed()) { - pkg_version <- utils::packageVersion(pkgname) - end <- Sys.time() - elapsed <- cli_timestamp_formatter(as.numeric(end - .time_record$start)) - cli::cli_alert_success(sprintf( - "{.pkg {pkgname}} v{pkg_version} loaded {cli::col_grey('[%s]')}", - elapsed - )) + cli::cli_process_done(.envir = .time_record) } } .onLoad <- function(libname, pkgname) { if (startup_message_allowed()) { - .time_record$start <- Sys.time() + pkg_version <- utils::packageVersion(pkgname) + .time_record$pkgname <- pkgname + .time_record$pkg_version <- pkg_version + cli::cli_progress_step( + msg = "Loading {.pkg {pkgname}} v{pkg_version}", + msg_done = "{.pkg {pkgname}} v{pkg_version} loaded", + spinner = TRUE, + .envir = .time_record + ) } invisible() @@ -41,29 +43,6 @@ .time_record <- new.env() -cli_timestamp_formatter <- function(x) { - stopifnot( - length(x) == 1L, - is.numeric(x), - !is.na(x), - x >= 0L - ) - - if (x < 1L) { - sprintf("%d ms", as.integer(x * 1000L)) - } else if (x < 60L) { - sprintf("%d s", as.integer(x)) - } else if (x < 3600L) { - sprintf("%d min %d s", floor(x / 60L), as.integer(x %% 60L)) - } else { - sprintf( - "%d h %02d min %d s", - floor(x / 3600L), - floor((x %% 3600L) / 60L), - as.integer(x %% 60L) - ) - } -} startup_message_allowed <- function() { allowed <- FALSE diff --git a/README.Rmd b/README.Rmd index 008f9f0..a5e4c17 100644 --- a/README.Rmd +++ b/README.Rmd @@ -123,6 +123,7 @@ It's recommended to use following packages together with `rpkgkit`: | `check_sysdeps()` | `check_sysdeps(c("libpng-dev"))` | Check whether system libraries are installed | | `check_air_installed()` | `check_air_installed()` | Check that the `air` formatter is on the `PATH` | | `flir_fix()` | `flir_fix("R/foo.R")` | Fix R code with `flir` | +| `use_air_table()` | `use_air_table("R/foo.R", ncol = 3)` | Lay out long `c()` and `list()` calls as aligned tables with `air` | | `air_format()` | `air_format("R/foo.R")` | Deprecated; format R code with `air` | ### Manage `NEWS.md` diff --git a/README.md b/README.md index d7e4117..e32a6e4 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,7 @@ It’s recommended to use following packages together with `rpkgkit`: | `check_sysdeps()` | `check_sysdeps(c("libpng-dev"))` | Check whether system libraries are installed | | `check_air_installed()` | `check_air_installed()` | Check that the `air` formatter is on the `PATH` | | `flir_fix()` | `flir_fix("R/foo.R")` | Fix R code with `flir` | +| `use_air_table()` | `use_air_table("R/foo.R", ncol = 3)` | Lay out long `c()` and `list()` calls as aligned tables with `air` | | `air_format()` | `air_format("R/foo.R")` | Deprecated; format R code with `air` | ### Manage `NEWS.md` diff --git a/_pkgdown.yml b/_pkgdown.yml index 1298cc0..ab03467 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -80,6 +80,7 @@ reference: - rename_func - render_rmd - update_time_in_standalone + - use_air_table - use_bugreports - use_clangd - use_hexsticker diff --git a/inst/R_template/zzz_template.R b/inst/R_template/zzz_template.R index 4fd5676..74d4e09 100644 --- a/inst/R_template/zzz_template.R +++ b/inst/R_template/zzz_template.R @@ -15,19 +15,21 @@ .onAttach <- function(libname, pkgname) { if (startup_message_allowed()) { - pkg_version <- utils::packageVersion(pkgname) - end <- Sys.time() - elapsed <- cli_timestamp_formatter(as.numeric(end - .time_record$start)) - cli::cli_alert_success(sprintf( - "{.pkg {pkgname}} v{pkg_version} loaded {cli::col_grey('[%s]')}", - elapsed - )) + cli::cli_process_done(.envir = .time_record) } } .onLoad <- function(libname, pkgname) { if (startup_message_allowed()) { - .time_record$start <- Sys.time() + pkg_version <- utils::packageVersion(pkgname) + .time_record$pkgname <- pkgname + .time_record$pkg_version <- pkg_version + cli::cli_progress_step( + msg = "Loading {.pkg {pkgname}} v{pkg_version}", + msg_done = "{.pkg {pkgname}} v{pkg_version} loaded", + spinner = TRUE, + .envir = .time_record + ) } invisible() @@ -35,29 +37,6 @@ .time_record <- new.env() -cli_timestamp_formatter <- function(x) { - stopifnot( - length(x) == 1L, - is.numeric(x), - !is.na(x), - x >= 0L - ) - - if (x < 1L) { - sprintf("%d ms", as.integer(x * 1000L)) - } else if (x < 60L) { - sprintf("%d s", as.integer(x)) - } else if (x < 3600L) { - sprintf("%d min %d s", floor(x / 60L), as.integer(x %% 60L)) - } else { - sprintf( - "%d h %02d min %d s", - floor(x / 3600L), - floor((x %% 3600L) / 60L), - as.integer(x %% 60L) - ) - } -} startup_message_allowed <- function() { allowed <- FALSE diff --git a/inst/WORDLIST b/inst/WORDLIST new file mode 100644 index 0000000..fff2d02 --- /dev/null +++ b/inst/WORDLIST @@ -0,0 +1,113 @@ +AST +Acknowledgements +Addin +Addins +CFF +CLI +CMD +Codecov +Codesize +Convertion +DeepWiki +Español +Github +Homebrew +Knitr +MSVC +MacOS +Magrittr +Maintenace +NSE +PascalCase +PowerShell +README +RStudio +Rbuildignore +Rcpp +Rmd +Roxygen +Rtools +SHA +SPDX +Tidyverse +Unrecognised +VignetteIndexEntry +YYYY +acknowledgement +addin +addins +al +arg +behaviour +blockquote +callee +camelCase +cancelled +cff +changelog +clangd +clangd's +cli +coercions +cov +covr +css +dcf +desc +dev +dieghernan +et +extensibility +flavour +flir +formatter +gfm +github +honoured +https +initializer +io +jarl +knitr +labelled +linter +magrittr +matcher +md +namespacing +nocov +params +parseable +pkgdev +pkgdown +pkgname +pre +quadratically +readme +recurse +rescanned +rlang +rmarkdown +roxygen +rstudioapi +syntaxes +testcoverage +tibble +tidyverse +toolchain +uXXXX +unanchored +unclosed +unicode +unlicense +unmapped +unmerged +unparseable +usethis +uv +validator +validators +vendored +verion +wurli +zzz diff --git a/inst/translations/README.es.md b/inst/translations/README.es.md index 0e7a9db..fd76642 100644 --- a/inst/translations/README.es.md +++ b/inst/translations/README.es.md @@ -96,6 +96,7 @@ Todas las funciones exportadas con una llamada mínima. La mayoría acepta `path | `check_sysdeps()` | `check_sysdeps(c("libpng-dev"))` | Comprobar si las librerías del sistema están instaladas | | `check_air_installed()` | `check_air_installed()` | Comprobar que el formateador `air` está en el `PATH` | | `flir_fix()` | `flir_fix("R/foo.R")` | Corregir código R con `flir` | +| `use_air_table()` | `use_air_table("R/foo.R", ncol = 3)` | Maquetar llamadas largas a `c()` y `list()` como tablas alineadas con `air` | | `air_format()` | `air_format("R/foo.R")` | Obsoleta; formatear código R con `air` | ### Gestionar `NEWS.md` diff --git a/inst/translations/README.zh-cn.md b/inst/translations/README.zh-cn.md index 2f63dad..77c9137 100644 --- a/inst/translations/README.zh-cn.md +++ b/inst/translations/README.zh-cn.md @@ -96,6 +96,7 @@ pak::pak("WangLabCSU/rpkgkit") | `check_sysdeps()` | `check_sysdeps(c("libpng-dev"))` | 检查系统库是否已安装 | | `check_air_installed()` | `check_air_installed()` | 检查 `air` 格式化工具是否在 `PATH` 中 | | `flir_fix()` | `flir_fix("R/foo.R")` | 使用 `flir` 修复 R 代码 | +| `use_air_table()` | `use_air_table("R/foo.R", ncol = 3)` | 使用 `air` 将较长的 `c()` 和 `list()` 调用排版为对齐的表格 | | `air_format()` | `air_format("R/foo.R")` | 已弃用;使用 `air` 格式化 R 代码 | ### 管理 `NEWS.md` diff --git a/man/dot-at_call_ids.Rd b/man/dot-at_call_ids.Rd new file mode 100644 index 0000000..a8a4378 --- /dev/null +++ b/man/dot-at_call_ids.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_call_ids} +\alias{.at_call_ids} +\title{Internal: ids of all call expressions} +\usage{ +.at_call_ids(pd) +} +\arguments{ +\item{pd}{Parse data as returned by \code{getParseData()}.} +} +\value{ +An integer vector of \code{expr} ids that are function calls. +} +\description{ +Internal: ids of all call expressions +} +\keyword{internal} diff --git a/man/dot-at_call_info.Rd b/man/dot-at_call_info.Rd new file mode 100644 index 0000000..71106f0 --- /dev/null +++ b/man/dot-at_call_info.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_call_info} +\alias{.at_call_info} +\title{Internal: describe one \code{c()} / \code{list()} call} +\usage{ +.at_call_info(pd, sym_id, call_ids, min_length) +} +\arguments{ +\item{pd}{Parse data as returned by \code{getParseData()}.} + +\item{sym_id}{Id of the \code{SYMBOL_FUNCTION_CALL} row.} + +\item{call_ids}{Ids returned by \code{.at_call_ids()}.} + +\item{min_length}{Minimum number of elements (exclusive).} +} +\value{ +\code{NULL} when the call does not qualify, otherwise a list with +\code{line1}, \code{line2}, \code{col1}, \code{n}, \code{multiline} and \code{elements}. +} +\description{ +Internal: describe one \code{c()} / \code{list()} call +} +\keyword{internal} diff --git a/man/dot-at_collapse.Rd b/man/dot-at_collapse.Rd new file mode 100644 index 0000000..bb1db0a --- /dev/null +++ b/man/dot-at_collapse.Rd @@ -0,0 +1,24 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_collapse} +\alias{.at_collapse} +\title{Internal: insert the directive and re-flow the elements} +\usage{ +.at_collapse(lines, targets, ncol, marker) +} +\arguments{ +\item{lines}{Character vector of the file contents.} + +\item{targets}{Data frame returned by \code{.at_targets()}.} + +\item{ncol}{Number of elements per row.} + +\item{marker}{The air table directive to insert.} +} +\value{ +A character vector with the modified file contents. +} +\description{ +Internal: insert the directive and re-flow the elements +} +\keyword{internal} diff --git a/man/dot-at_has_call_ancestor.Rd b/man/dot-at_has_call_ancestor.Rd new file mode 100644 index 0000000..432e098 --- /dev/null +++ b/man/dot-at_has_call_ancestor.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_has_call_ancestor} +\alias{.at_has_call_ancestor} +\title{Internal: is the call nested inside another call?} +\usage{ +.at_has_call_ancestor(pd, call_id, call_ids) +} +\arguments{ +\item{pd}{Parse data as returned by \code{getParseData()}.} + +\item{call_id}{Id of the call expression.} + +\item{call_ids}{Ids returned by \code{.at_call_ids()}.} +} +\value{ +A single logical. +} +\description{ +Internal: is the call nested inside another call? +} +\keyword{internal} diff --git a/man/dot-at_join_flags.Rd b/man/dot-at_join_flags.Rd new file mode 100644 index 0000000..5bbef14 --- /dev/null +++ b/man/dot-at_join_flags.Rd @@ -0,0 +1,28 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_join_flags} +\alias{.at_join_flags} +\title{Internal: flag the line breaks that disappear when rows are collapsed} +\usage{ +.at_join_flags(join, elements, ncol, lines) +} +\arguments{ +\item{join}{Logical vector of line-break flags to update.} + +\item{elements}{Data frame of element positions.} + +\item{ncol}{Number of elements per row.} + +\item{lines}{Character vector of the file contents.} +} +\value{ +The updated \code{join} vector. +} +\description{ +Internal: flag the line breaks that disappear when rows are collapsed +} +\details{ +A line ending in a comment is never joined with the next one: the joined +element would be swallowed by the comment and silently disappear. +} +\keyword{internal} diff --git a/man/dot-at_parse.Rd b/man/dot-at_parse.Rd new file mode 100644 index 0000000..3f0c13e --- /dev/null +++ b/man/dot-at_parse.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_parse} +\alias{.at_parse} +\title{Internal: parse a file, aborting on invalid R code} +\usage{ +.at_parse(lines, path) +} +\arguments{ +\item{lines}{Character vector of the file contents.} + +\item{path}{Path of the file, used in the error message.} +} +\value{ +The parsed expressions. +} +\description{ +Internal: parse a file, aborting on invalid R code +} +\keyword{internal} diff --git a/man/dot-at_rows.Rd b/man/dot-at_rows.Rd new file mode 100644 index 0000000..777b71c --- /dev/null +++ b/man/dot-at_rows.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_rows} +\alias{.at_rows} +\title{Internal: rows of element indices} +\usage{ +.at_rows(n, ncol) +} +\arguments{ +\item{n}{Number of elements.} + +\item{ncol}{Number of elements per row.} +} +\value{ +A list of integer vectors. +} +\description{ +Internal: rows of element indices +} +\keyword{internal} diff --git a/man/dot-at_run_air.Rd b/man/dot-at_run_air.Rd new file mode 100644 index 0000000..b14c414 --- /dev/null +++ b/man/dot-at_run_air.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_run_air} +\alias{.at_run_air} +\title{Internal: run \verb{air format} and abort on failure} +\usage{ +.at_run_air(path) +} +\arguments{ +\item{path}{Path to the file to format.} +} +\value{ +Invisibly returns \code{path}. +} +\description{ +Internal: run \verb{air format} and abort on failure +} +\keyword{internal} diff --git a/man/dot-at_split_lines.Rd b/man/dot-at_split_lines.Rd new file mode 100644 index 0000000..79dc108 --- /dev/null +++ b/man/dot-at_split_lines.Rd @@ -0,0 +1,24 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_split_lines} +\alias{.at_split_lines} +\title{Internal: rewrite a single-line definition as a table} +\usage{ +.at_split_lines(line, call_col1, elements, ncol) +} +\arguments{ +\item{line}{The source line holding the whole call.} + +\item{call_col1}{Column where the call starts.} + +\item{elements}{Data frame of element positions.} + +\item{ncol}{Number of elements per row.} +} +\value{ +A character vector of replacement lines, without the directive. +} +\description{ +Internal: rewrite a single-line definition as a table +} +\keyword{internal} diff --git a/man/dot-at_targets.Rd b/man/dot-at_targets.Rd new file mode 100644 index 0000000..0020c6b --- /dev/null +++ b/man/dot-at_targets.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{.at_targets} +\alias{.at_targets} +\title{Internal: locate long vector and list definitions} +\usage{ +.at_targets(lines, path, min_length, marker) +} +\arguments{ +\item{lines}{Character vector of the file contents.} + +\item{path}{Path of the file, used in error messages.} + +\item{min_length}{Minimum number of elements (exclusive).} + +\item{marker}{The air table directive.} +} +\value{ +A data frame with one row per target and the list-column +\code{elements} (position of every element), or an empty data frame with the +same columns when nothing qualifies. +} +\description{ +Internal: locate long vector and list definitions +} +\keyword{internal} diff --git a/man/use_air_table.Rd b/man/use_air_table.Rd new file mode 100644 index 0000000..750aabb --- /dev/null +++ b/man/use_air_table.Rd @@ -0,0 +1,79 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/54_use_air_table_.R +\name{use_air_table} +\alias{use_air_table} +\title{Format Long Vectors and Lists as Aligned Tables with Air} +\usage{ +use_air_table( + path = NULL, + ncol = 3L, + min_length = 12L, + marker = "# fmt: table", + ... +) +} +\arguments{ +\item{path}{Path to an R file to modify. If \code{NULL} and RStudio is +available, the path of the active document is used.} + +\item{ncol}{Number of elements placed on each table row.} + +\item{min_length}{A vector or list is only converted when it has strictly +more than this many elements.} + +\item{marker}{The comment directive that enables table formatting in air.} + +\item{...}{Additional arguments. Currently unused and must be empty.} +} +\value{ +Invisibly returns the normalized \code{path}. +} +\description{ +Air (\eqn{\geq} 0.8.0) can align the elements of a call column by column, +giving the same layout as \code{tibble::tribble()} or +\code{data.table::fcase()}. The feature is switched on by the experimental +\code{# fmt: table} comment directive placed right above the call, but air +never re-flows the elements on its own: whatever sits on one source line +stays there. + +\code{\link[=use_air_table]{use_air_table()}} does the two things air does not do by itself: +\enumerate{ +\item runs \code{air format} on \code{path}, so every long vector and list is +laid out with one element per line; +\item inserts the directive above every \code{c()} / \code{list()} call that +has more than \code{min_length} elements, and re-flows the elements so +that each row holds \code{ncol} of them. Multi-line definitions are +collapsed by deleting the line breaks between the elements of a row; +a definition that air kept on a single line is split into rows instead. +} + +A second \code{air format} run then pads the cells and aligns the columns. +} +\details{ +Requirements and scope: +\itemize{ +\item \code{air} must be installed and on the \code{PATH} (see +\code{\link[=check_air_installed]{check_air_installed()}}), and the directive requires air 0.8.0 or newer. +\item Only calls whose elements are \strong{all unnamed} are rewritten. Air expands +named elements (\code{list(a = 1)}) one per line no matter what the +directive says, so named calls are skipped to avoid a marker that has no +effect. +\item Calls that already carry \code{marker} on the preceding line are left +untouched, so the function is idempotent. +\item Air only honours the directive on the outermost call of a statement, so a +vector or list nested inside another call (for example an argument of +\code{x <- list(a = c(...))}) is skipped. +} +} +\examples{ +\dontrun{ +tf <- tempfile(fileext = ".R") +writeLines( + 'x <- c("alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta")', + tf +) +use_air_table(tf, ncol = 3L, min_length = 6L) +readLines(tf) |> cli::cli_code() +} + +} diff --git a/tests/spelling.R b/tests/spelling.R new file mode 100644 index 0000000..6713838 --- /dev/null +++ b/tests/spelling.R @@ -0,0 +1,3 @@ +if(requireNamespace('spelling', quietly = TRUE)) + spelling::spell_check_test(vignettes = TRUE, error = FALSE, + skip_on_cran = TRUE) diff --git a/tests/testthat/test-use_air_table.R b/tests/testthat/test-use_air_table.R new file mode 100644 index 0000000..8aae74f --- /dev/null +++ b/tests/testthat/test-use_air_table.R @@ -0,0 +1,454 @@ +# Tests for use_air_table() and its internal helpers in +# R/54_use_air_table_.R + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +# Write `lines` to a temporary file that is removed at the end of the test. +air_file <- function(lines, env = parent.frame()) { + withr::local_tempfile(lines = lines, .local_envir = env) +} + +# Pretend that air is installed and that `air format` is a no-op, so the tests +# exercise the rewriting logic alone, never the external binary. +mock_air <- function(env = parent.frame()) { + testthat::local_mocked_bindings( + check_air_installed = function() invisible(TRUE), + .at_run_air = function(path) invisible(path), + .package = "rpkgkit", + .env = env + ) +} + +# A vector already laid out by air: one element per line. +air_multiline_vec <- function() { + c( + "x <- c(", + ' "a",', + ' "b",', + ' "c",', + ' "d"', + ")" + ) +} + +# The table that both the single-line and the multi-line input collapse into. +air_table_vec <- function() { + c( + "# fmt: table", + "x <- c(", + ' "a", "b",', + ' "c", "d"', + ")" + ) +} + +# --------------------------------------------------------------------------- +# Argument validation +# --------------------------------------------------------------------------- + +test_that("use_air_table aborts on unused dots", { + mock_air() + tf <- air_file("x <- 1") + + expect_error(use_air_table(tf, foo = 1), "must be empty") +}) + +test_that("use_air_table validates ncol", { + mock_air() + tf <- air_file("x <- 1") + + expect_error(use_air_table(tf, ncol = 0), "ncol") + expect_error(use_air_table(tf, ncol = 1.5), "ncol") + expect_error(use_air_table(tf, ncol = "2"), "ncol") +}) + +test_that("use_air_table validates min_length", { + mock_air() + tf <- air_file("x <- 1") + + expect_error(use_air_table(tf, min_length = -1), "min_length") + expect_error(use_air_table(tf, min_length = 2.5), "min_length") +}) + +test_that("use_air_table validates marker", { + mock_air() + tf <- air_file("x <- 1") + + expect_error(use_air_table(tf, marker = 1), "single string") + expect_error(use_air_table(tf, marker = c("# fmt: table", "# x")), "single") +}) + +test_that("use_air_table aborts when air is not installed", { + tf <- air_file("x <- 1") + local_mocked_bindings( + Sys.which = function(x) "", + .package = "base" + ) + local_mocked_bindings(interactive = function() FALSE, .package = "base") + + expect_error(use_air_table(tf), "is not installed") +}) + +# --------------------------------------------------------------------------- +# Path handling +# --------------------------------------------------------------------------- + +test_that("use_air_table aborts when path is NULL and RStudio is unavailable", { + mock_air() + local_mocked_bindings( + isAvailable = function() FALSE, + .package = "rstudioapi" + ) + + expect_error(use_air_table(), "path.*required") +}) + +test_that("use_air_table uses the active document when path is NULL", { + mock_air() + tf <- air_file("x <- c(1, 2, 3, 4)") + local_mocked_bindings( + isAvailable = function() TRUE, + getActiveDocumentContext = function() list(path = tf), + .package = "rstudioapi" + ) + + expect_message(use_air_table(ncol = 2L, min_length = 3L), "Converted") + expect_identical(readLines(tf)[[1L]], "# fmt: table") +}) + +test_that("use_air_table aborts when the file does not exist", { + mock_air() + tf <- withr::local_tempfile() + + expect_error(use_air_table(tf), "does not exist") +}) + +test_that("use_air_table aborts when the file is not valid R code", { + mock_air() + tf <- air_file("x <- c(1, 2") + + expect_error(use_air_table(tf), "not valid R code") +}) + +test_that("use_air_table returns the normalized path invisibly", { + mock_air() + tf <- air_file(air_table_vec()) + + expect_message( + res <- use_air_table(tf), + "No vector or list" + ) + expect_invisible(use_air_table(tf)) + expect_identical(res, normalizePath(tf, mustWork = TRUE)) +}) + +# --------------------------------------------------------------------------- +# Rewriting behaviour +# --------------------------------------------------------------------------- + +test_that("use_air_table splits a single-line vector into rows", { + mock_air() + tf <- air_file('x <- c("a", "b", "c", "d")') + + expect_message(use_air_table(tf, ncol = 2L, min_length = 2L), "Converted") + expect_identical(readLines(tf), air_table_vec()) +}) + +test_that("use_air_table collapses an already multi-line vector into rows", { + mock_air() + tf <- air_file(air_multiline_vec()) + + expect_message(use_air_table(tf, ncol = 2L, min_length = 2L), "Converted") + expect_identical(readLines(tf), air_table_vec()) +}) + +test_that("use_air_table handles several targets in one file", { + mock_air() + tf <- air_file(c("a <- c(1, 2, 3, 4)", "b <- c(5, 6, 7, 8)")) + + expect_message(use_air_table(tf, ncol = 2L, min_length = 2L), "Converted") + expect_identical( + readLines(tf), + c( + "# fmt: table", + "a <- c(", + " 1, 2,", + " 3, 4", + ")", + "# fmt: table", + "b <- c(", + " 5, 6,", + " 7, 8", + ")" + ) + ) +}) + +test_that("use_air_table keeps indentation of an indented call", { + mock_air() + tf <- air_file(c("f <- function() {", " x <- c(1, 2, 3, 4)", "}")) + + expect_message(use_air_table(tf, ncol = 2L, min_length = 2L), "Converted") + expect_identical( + readLines(tf), + c( + "f <- function() {", + " # fmt: table", + " x <- c(", + " 1, 2,", + " 3, 4", + " )", + "}" + ) + ) +}) + +test_that("use_air_table honours a custom marker", { + mock_air() + tf <- air_file("x <- c(1, 2, 3, 4)") + + expect_message( + use_air_table(tf, ncol = 2L, min_length = 2L, marker = "# fmt: table2"), + "Converted" + ) + expect_identical(readLines(tf)[[1L]], "# fmt: table2") +}) + +test_that("use_air_table is idempotent", { + mock_air() + tf <- air_file(air_table_vec()) + + expect_message( + use_air_table(tf, ncol = 2L, min_length = 2L), + "No vector or list" + ) + expect_identical(readLines(tf), air_table_vec()) +}) + +test_that("use_air_table reports when no target qualifies", { + mock_air() + tf <- air_file(c("x <- 1", "y <- c(1, 2)")) + + expect_message( + use_air_table(tf, min_length = 5L), + "No vector or list with more than 5 elements" + ) + expect_identical(readLines(tf), c("x <- 1", "y <- c(1, 2)")) +}) + +test_that("use_air_table only converts vectors longer than min_length", { + mock_air() + tf <- air_file("x <- c(1, 2, 3, 4)") + + expect_message(use_air_table(tf, min_length = 4L), "No vector or list") + expect_identical(readLines(tf), "x <- c(1, 2, 3, 4)") + + expect_message(use_air_table(tf, min_length = 3L), "Converted") + expect_identical(readLines(tf)[[1L]], "# fmt: table") +}) + +test_that("use_air_table skips calls with named elements", { + mock_air() + lines <- "x <- list(a = 1, b = 2, c = 3, d = 4)" + tf <- air_file(lines) + + expect_message(use_air_table(tf, min_length = 2L), "No vector or list") + expect_identical(readLines(tf), lines) +}) + +test_that("use_air_table skips calls nested inside another call", { + mock_air() + lines <- 'print(c("a", "b", "c", "d"))' + tf <- air_file(lines) + + expect_message(use_air_table(tf, min_length = 2L), "No vector or list") + expect_identical(readLines(tf), lines) +}) + +test_that("use_air_table never joins a line that ends in a comment", { + mock_air() + tf <- air_file(c( + "x <- c(", + ' "a", # first', + ' "b",', + ' "c",', + ' "d"', + ")" + )) + + expect_message(use_air_table(tf, ncol = 2L, min_length = 2L), "Converted") + expect_identical( + readLines(tf), + c( + "# fmt: table", + "x <- c(", + ' "a", # first', + ' "b",', + ' "c", "d"', + ")" + ) + ) +}) + +# --------------------------------------------------------------------------- +# Internal helpers +# --------------------------------------------------------------------------- + +test_that(".at_rows() splits element indices into rows", { + expect_identical(unname(.at_rows(4L, 2L)), list(c(1L, 2L), c(3L, 4L))) + expect_identical(unname(.at_rows(5L, 3L)), list(c(1L, 2L, 3L), c(4L, 5L))) + expect_identical(unname(.at_rows(3L, 1L)), list(1L, 2L, 3L)) +}) + +test_that(".at_parse() returns expressions and aborts on invalid code", { + expect_length(.at_parse("x <- 1", path = "test.R"), 1L) + expect_length(.at_parse(character(0), path = "test.R"), 0L) + expect_error( + .at_parse("x <- (", path = "test.R"), + "not valid R code" + ) +}) + +test_that(".at_targets() returns an empty data frame when nothing qualifies", { + targets <- .at_targets( + lines = c("x <- 1", "y <- c(1, 2)"), + path = "test.R", + min_length = 5L, + marker = "# fmt: table" + ) + + expect_s3_class(targets, "data.frame") + expect_identical(nrow(targets), 0L) + expect_named( + targets, + c("line1", "line2", "col1", "n", "multiline", "elements") + ) +}) + +test_that(".at_targets() describes qualifying calls", { + targets <- .at_targets( + lines = air_multiline_vec(), + path = "test.R", + min_length = 2L, + marker = "# fmt: table" + ) + + expect_identical(nrow(targets), 1L) + expect_identical(targets$line1, 1L) + expect_identical(targets$line2, 6L) + expect_identical(targets$n, 4L) + expect_true(targets$multiline) + expect_identical(nrow(targets$elements[[1L]]), 4L) +}) + +test_that(".at_targets() ignores calls that already carry the marker", { + targets <- .at_targets( + lines = air_table_vec(), + path = "test.R", + min_length = 2L, + marker = "# fmt: table" + ) + + expect_identical(nrow(targets), 0L) +}) + +test_that(".at_split_lines() rewrites a single-line call", { + line <- "x <- c(1, 2, 3, 4)" + elements <- data.frame( + line1 = 1L, + col1 = c(8L, 11L, 14L, 17L), + line2 = 1L, + col2 = c(8L, 11L, 14L, 17L) + ) + + expect_identical( + .at_split_lines( + line = line, + call_col1 = 6L, + elements = elements, + ncol = 2L + ), + c("x <- c(", " 1, 2,", " 3, 4", ")") + ) +}) + +test_that(".at_join_flags() sets a flag only when a row continues", { + elements <- data.frame( + line1 = c(1L, 2L), + col1 = c(3L, 3L), + line2 = c(1L, 2L), + col2 = c(5L, 5L) + ) + + expect_identical( + .at_join_flags( + join = c(FALSE, FALSE), + elements = elements, + ncol = 2L, + lines = c(' "a",', ' "b"') + ), + c(FALSE, TRUE) + ) + + # A trailing comment must keep the line break. + expect_identical( + .at_join_flags( + join = c(FALSE, FALSE), + elements = elements, + ncol = 2L, + lines = c(' "a", # keep', ' "b"') + ), + c(FALSE, FALSE) + ) + + # One element per row never joins anything. + expect_identical( + .at_join_flags( + join = c(FALSE, FALSE), + elements = elements, + ncol = 1L, + lines = c(' "a",', ' "b"') + ), + c(FALSE, FALSE) + ) +}) + +test_that(".at_join_flags() ignores lines that are not adjacent", { + elements <- data.frame( + line1 = c(1L, 3L), + col1 = c(3L, 3L), + line2 = c(1L, 3L), + col2 = c(5L, 5L) + ) + + expect_identical( + .at_join_flags( + join = c(FALSE, FALSE, FALSE), + elements = elements, + ncol = 2L, + lines = c(' "a",', "", ' "b"') + ), + c(FALSE, FALSE, FALSE) + ) +}) + +test_that(".at_run_air() aborts when air fails", { + local_mocked_bindings( + system2 = function(...) structure("error: bad syntax", status = 1L), + .package = "base" + ) + + expect_error(.at_run_air("test.R"), "failed to format") +}) + +test_that(".at_run_air() returns the path invisibly on success", { + local_mocked_bindings( + system2 = function(...) character(), + .package = "base" + ) + + expect_invisible(.at_run_air("test.R")) + expect_identical(.at_run_air("test.R"), "test.R") +}) diff --git a/vignettes/code_convertion.Rmd b/vignettes/code_convertion.Rmd index 4f2927d..571eb16 100644 --- a/vignettes/code_convertion.Rmd +++ b/vignettes/code_convertion.Rmd @@ -310,3 +310,40 @@ convert_nonascii_code({ cli::cli_alert_warning("把酒问青天") }) ``` + +# Lay out long vectors and lists as tables + +Air 0.8.0 and newer can align the elements of a `c()` or `list()` call column by +column, giving the layout of `tibble::tribble()`. The feature is switched on by +the experimental `# fmt: table` directive placed right above the call, but air +never re-flows the elements on its own: whatever sits on one source line stays +there. + +`use_air_table()` does the two things air does not do by itself. It runs +`air format`, inserts the directive above every unnamed `c()`/`list()` call that +holds more than `min_length` elements, and re-flows those elements so that each +row holds `ncol` of them; a second `air format` run then pads the cells and +aligns the columns. + +```{r} +#| label = "use_air_table" +file <- tempfile(fileext = ".R") +writeLines( + 'x <- c("alpha", "beta", "gamma", "delta", "epsilon", "zeta")', + file +) +use_air_table(file, ncol = 3L, min_length = 5L) +readLines(file) |> cli::cli_code() +``` + +Keep in mind that: + +- `air` must be installed and on the `PATH`; `check_air_installed()` reports the + installation command for each operating system. +- Only calls whose elements are all unnamed are rewritten: air expands named + elements one per line whatever the directive says, so a named call is skipped + instead of being decorated with a directive that has no effect. +- A call that already carries the directive is left untouched, so the function + is idempotent. +- Only the outermost call of a statement is converted, because air ignores the + directive on nested calls. From a1bbf433386fde43550e5b8046aec65f4d5f272a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 5 Nov 2026 11:37:17 +0000 Subject: [PATCH 15/35] chore: bump version to 0.1.24 [skip ci] --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 19dc330..61567c6 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: rpkgkit Title: Create and Maintain R Packages -Version: 0.1.23 +Version: 0.1.24 Authors@R: c( person("Yuxi", "Yang", , "15364051195@163.com", role = c("aut", "cre")), person("Jacob", "Scott", role = c("ctb", "cph"), From 2b2903ac94b3b2ffa6b417a1b266a3de012c966d Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Thu, 5 Nov 2026 09:51:42 -0500 Subject: [PATCH 16/35] Added the standalone `standalone-cli_kable.R` script, which provides `cli_kable()` for printing a data frame, a matrix or any object `as.data.frame()` accepts as the pipe table of `knitr::kable()`, the layout `kableExtra::kable()` shows, with `cli` inline classes instead of Markdown. --- NEWS.md | 24 + R/standalone-cli_kable.R | 537 ++++++++++++ inst/WORDLIST | 2 + skills/rpkgkit/SKILL.md | 57 +- .../rpkgkit/references/function-reference.md | 22 +- tests/testthat/test-cli_kable.R | 825 ++++++++++++++++++ vignettes/code_convertion.Rmd | 3 +- vignettes/standalone_tools.Rmd | 42 + 8 files changed, 1508 insertions(+), 4 deletions(-) create mode 100644 R/standalone-cli_kable.R create mode 100644 tests/testthat/test-cli_kable.R diff --git a/NEWS.md b/NEWS.md index 3ebea8f..32b241a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -18,6 +18,26 @@ idempotent. `path = NULL` falls back to the active RStudio document, `air` must be on the `PATH` (checked with `check_air_installed()`), and the normalized path is returned invisibly. +* Added the standalone `standalone-cli_kable.R` script, which provides + `cli_kable()` for printing a data frame, a matrix or any object + `as.data.frame()` accepts as the pipe table of `knitr::kable()`, the layout + `kableExtra::kable()` shows, with `cli` inline classes instead of Markdown. The + layout is the one of `kable()`: cells are padded to the column width, columns + are `padding` spaces wider and at least 3 characters wide, numeric columns are + rounded to `digits` decimals and right aligned while everything else is left + aligned, and the `:---|---:` alignment rule follows the headers. + `header_format` (default `".val"`), `rownames_format` (default `".val"`) and + `value_format` (default `NULL`) accept a single class, a vector of `ncol(x)` + classes, or a named vector or named list: named elements style only the columns + or rows they name and an unnamed element is the fallback of everything that is + not named, which is how a part of the table is highlighted, while the elements + of a `value_format` list can be named vectors of row names to style single + cells. Widths are measured with `cli::ansi_nchar()` after the classes are + applied, so classes that add visible characters (`{.val}`, `{.code}`) keep the + columns aligned, and each distinct class is rendered once instead of once per + cell. `align`, `digits`, `padding`, `sep` and `rule` control the rest of the + table, an unknown name or an invalid class aborts with `cli::cli_abort()`, and + the printed lines are returned invisibly. ## MINOR IMPROVEMENTS @@ -37,6 +57,10 @@ * The package is now spell-checked: `spelling` was added to `Suggests` together with `Language: en-US`, `inst/WORDLIST` holds the accepted words, and `tests/spelling.R` runs `spelling::spell_check_test()`. +* The `standalone_tools` vignette gained a "Print data frames as kable-style + tables" section covering `cli_kable()` and the named formats that highlight a + part of the table, and the package skill (`skills/rpkgkit/`) now lists every + bundled standalone helper with the functions it provides. # rpkgkit 0.1.23 (2026-11-01) diff --git a/R/standalone-cli_kable.R b/R/standalone-cli_kable.R new file mode 100644 index 0000000..e33ac4f --- /dev/null +++ b/R/standalone-cli_kable.R @@ -0,0 +1,537 @@ +# --- +# repo: Exceret/rpkgkit +# file: standalone-cli_kable.R +# last-updated: 2026-11-05 +# license: https://unlicense.org +# imports: [cli] +# --- +# +# This file provides a `cli`-only re-implementation of the pipe table printed +# by `kableExtra::kable()` / `knitr::kable(x, format = "pipe")`: +# `cli_kable()`. The layout is the one of `kable()` (padded cells, `|` +# separators and the `:---|---:` alignment rule), while the column headers, the +# row names and the body values can each be styled with any `cli` inline class. +# +# The three format arguments accept a single class, a named vector or a named +# list, so a part of the table can be highlighted: named elements only style +# the matching columns (or rows), and an unnamed element is the fallback style +# of everything that is not named. +# +# nocov start + +#' Print a data frame as a `kable`-style table with cli styling +#' +#' Prints `x` as a pipe table laid out like `knitr::kable(x, format = "pipe")`, +#' the format used by `kableExtra::kable()`. Headers, row names and values can +#' each be styled with `cli` inline classes, so a whole table or only a part of +#' it can be highlighted. +#' +#' Every format argument accepts, in addition to a single class applied +#' everywhere, a named vector or a named list: only the columns (or rows) +#' whose name is given are styled, which is how a part of the table is +#' highlighted. An element without a name is the fallback style for everything +#' that is not named. +#' +#' @param x A data frame, a matrix, or any object [as.data.frame()] accepts. +#' @param header_format A `cli` inline class for the column headers, e.g. +#' `".val"`, `".field"`, `".strong"`, `".emph"`; the leading dot is +#' optional. `NULL` means no styling. A single string styles every header, +#' and a named vector such as `c(cyl = ".val", wt = ".field")` styles only +#' the `cyl` and `wt` columns, leaving the others unstyled. +#' @param rownames_format Same as `header_format`, but applied to the row names +#' column and matched against the row names, e.g. +#' `c("Hornet 4 Drive" = ".field")`. +#' @param value_format Style of the body values. `NULL` (default) means no +#' styling. It can be a single string, a vector of length `ncol(x)`, a named +#' vector or named list matched against the column names (all values of a +#' column get the same style), or a named list whose elements are named +#' vectors matched against the row names (per cell styling within a column). +#' @param align Column alignment: `NULL` aligns numbers to the right and +#' everything else to the left, as `kable()` does; `"l"`, `"c"`, `"r"` (or +#' `"left"`, `"center"`, `"right"`) are recycled over the columns. The row +#' names column is always left aligned. +#' @param digits Number of decimal places that numeric columns are rounded to +#' before they are formatted, as in `kable()`. Defaults to +#' `getOption("digits")`; `NULL` formats the values without rounding. +#' @param padding Spaces added to the width of each column. `padding = 1` +#' reproduces the layout of `knitr::kable()`; `padding = 0` removes that +#' extra space. Columns are still at least 3 characters wide, as in +#' `kable()`, so the alignment rule stays valid. +#' @param sep Separator between cells, used both between cells and at both +#' ends of each line. +#' @param rule Whether to print the `:---|---:` alignment rule below the +#' headers, as `kable()` does. +#' +#' @return The printed lines, invisibly. +#' @noRd +cli_kable <- function( + x, + header_format = ".val", + rownames_format = ".val", + value_format = NULL, + align = NULL, + digits = NULL, + padding = 1L, + sep = "|", + rule = TRUE +) { + df <- if (is.data.frame(x)) x else as.data.frame(x, stringsAsFactors = FALSE) + n_row <- nrow(df) + n_col <- ncol(df) + if (!is.null(digits)) { + if (!is.numeric(digits) || length(digits) != 1L || is.na(digits)) { + cli::cli_abort("`digits` must be a single number or {.val NULL}.") + } + } + if ( + !is.numeric(padding) || + length(padding) != 1L || + is.na(padding) || + padding < 0 + ) { + cli::cli_abort( + "`padding` must be a single non-negative number." + ) + } + if (!is.character(sep) || length(sep) != 1L || is.na(sep)) { + cli::cli_abort("`sep` must be a single string.") + } + padding <- as.integer(padding) + + # Column names and row names, as used to match the formats. Row names are + # dropped when they are the default `1:n`, as `kable()` does. + cols <- names(df) + if (is.null(cols)) { + cols <- rep("", n_col) + } + blank <- !nzchar(cols) | is.na(cols) + cols[blank] <- paste0("V", which(blank)) + rns <- rownames(df) + if (is.null(rns) || identical(rns, as.character(seq_len(n_row)))) { + rns <- NULL + } + has_rn <- !is.null(rns) + rn_keys <- if (has_rn) rns else as.character(seq_len(n_row)) + + # Plain text of the body, one column at a time so that numeric columns are + # formatted (and aligned on the decimal point) as a whole. + vals <- matrix("", nrow = n_row, ncol = n_col) + for (j in seq_len(n_col)) { + vals[, j] <- .ck_cell_text(x = df[[j]], digits = digits) + } + + head_cls <- .ck_fmt_axis( + fmt = header_format, + keys = cols, + arg = "header_format", + what = "column" + ) + rn_cls <- if (has_rn) { + .ck_fmt_axis( + fmt = rownames_format, + keys = rn_keys, + arg = "rownames_format", + what = "row" + ) + } else { + character() + } + val_cls <- .ck_fmt_cells( + fmt = value_format, + cols = cols, + rns = rn_keys, + arg = "value_format" + ) + + how <- .ck_align(align = align, df = df) + + # Render (styles may add visible characters, e.g. `{.val}` quotes), then + # measure the visible width and pad. + head_txt <- .ck_style(x = cols, cls = head_cls) + rn_txt <- if (has_rn) .ck_style(x = rns, cls = rn_cls) + val_txt <- .ck_style(x = as.vector(vals), cls = as.vector(val_cls)) + dim(val_txt) <- dim(vals) + + w <- vapply( + X = seq_len(n_col), + FUN = function(j) { + max(cli::ansi_nchar(x = c(head_txt[j], val_txt[, j]), type = "width")) + }, + FUN.VALUE = integer(1) + ) + # `kable()` pads every column by `padding` and keeps it at least 3 characters + # wide, so that the `:---` alignment rule stays valid. + w <- pmax(w + ifelse(how == "center", 2L * padding, padding), 3L) + w_rn <- if (has_rn) { + max(3L, max(cli::ansi_nchar(x = rn_txt, type = "width")) + padding) + } else { + 0L + } + + build <- function(cells) { + paste0(sep, paste(cells, collapse = sep), sep) + } + head_line <- build( + c( + if (has_rn) strrep(x = " ", times = w_rn), + .ck_pad(txt = head_txt, w = w, how = how) + ) + ) + rule_line <- build( + c( + if (has_rn) .ck_rule(w = w_rn, how = "left"), + .ck_rule(w = w, how = how) + ) + ) + body_lines <- vapply( + X = seq_len(n_row), + FUN = function(i) { + cells <- .ck_pad(txt = val_txt[i, ], w = w, how = how) + if (has_rn) { + cells <- c(.ck_pad(txt = rn_txt[i], w = w_rn, how = "left"), cells) + } + build(cells) + }, + FUN.VALUE = character(1) + ) + + lines <- c(head_line, if (isTRUE(rule)) rule_line, body_lines) + cli::cli_verbatim(lines) + + invisible(lines) +} + +# ---- Internal helpers ------------------------------------------------------- + +# Plain text of one column, formatted like `kable()`: numerics are rounded to +# `digits` decimals and formatted as a vector (so that decimals line up), +# everything else is coerced to character. +.ck_cell_text <- function(x, digits) { + out <- if (is.factor(x)) { + as.character(x) + } else if (is.numeric(x) || is.complex(x)) { + if (!is.null(digits)) { + x <- round(x, digits = digits) + } + format(x, trim = TRUE) + } else { + as.character(x) + } + out[is.na(out)] <- "NA" + trimws(out) +} + +# Automatic alignment, as `kable()`: numbers right, everything else left. +.ck_align <- function(align, df) { + n <- length(df) + auto <- vapply( + X = df, + FUN = function(col) { + if (is.numeric(col)) "right" else "left" + }, + FUN.VALUE = character(1) + ) + if (is.null(align)) { + return(unname(auto)) + } + if (!is.character(align)) { + cli::cli_abort("`align` must be {.cls character} or {.val NULL}.") + } + map <- c( + l = "left", + left = "left", + c = "center", + center = "center", + r = "right", + right = "right" + ) + out <- unname(map[tolower(rep_len(align, n))]) + if (anyNA(out)) { + cli::cli_abort( + c( + "x" = "`align` must be one of {.val l}, {.val c} or {.val r}.", + "i" = "Got: {.val {setdiff(unique(align), names(map))}}." + ) + ) + } + out +} + +# Resolve a format of the header / row names axis into one class per key. +.ck_fmt_axis <- function(fmt, keys, arg, what) { + n <- length(keys) + if (is.null(fmt)) { + return(rep("", n)) + } + if (is.list(fmt)) { + # One string per element, and no names of its own: `list(a = c(x = ".val"))` + # would otherwise be flattened to the key `a.x`. + scalar <- vapply( + X = fmt, + FUN = function(el) { + is.character(el) && length(el) == 1L && is.null(names(el)) + }, + FUN.VALUE = logical(1) + ) + if (!all(scalar)) { + cli::cli_abort( + c( + "x" = "`{arg}` only accepts single strings when given as a list.", + "i" = "Nested styles are supported by {.arg value_format} only." + ) + ) + } + nms <- names(fmt) + fmt <- unlist(fmt, use.names = FALSE) + names(fmt) <- nms + } + if (!is.character(fmt)) { + cli::cli_abort( + "`{arg}` must be {.cls character}, {.cls list} or {.val NULL}, not {.cls {class(fmt)}}." + ) + } + nms <- names(fmt) + out <- if (!is.null(nms) && any(!is.na(nms) & nzchar(nms))) { + .ck_map_named(vals = fmt, nms = nms, keys = keys, arg = arg, what = what) + } else if (length(fmt) == 1L) { + rep(fmt, n) + } else if (length(fmt) == n) { + unname(fmt) + } else { + cli::cli_abort( + c( + "x" = "`{arg}` must be length {n} (one per {what}) or 1, not {length(fmt)}.", + "i" = "Use a single string, a vector of length {n}, or a named vector." + ) + ) + } + .ck_norm_class(cls = out, arg = arg) +} + +# Resolve `value_format` into one class per cell (a rows x columns matrix). +.ck_fmt_cells <- function(fmt, cols, rns, arg) { + n_row <- length(rns) + n_col <- length(cols) + out <- matrix("", nrow = n_row, ncol = n_col) + if (is.null(fmt)) { + return(out) + } + + # Not a list: a class per column, as for the header axis. + if (!is.list(fmt)) { + per_col <- .ck_fmt_axis(fmt = fmt, keys = cols, arg = arg, what = "column") + return(matrix(rep(per_col, each = n_row), nrow = n_row, ncol = n_col)) + } + + nms <- names(fmt) + # Unnamed list: positional over the columns. + if (is.null(nms) || !any(!is.na(nms) & nzchar(nms))) { + per_col <- .ck_fmt_axis( + fmt = unlist(fmt, use.names = FALSE), + keys = cols, + arg = arg, + what = "column" + ) + return(matrix(rep(per_col, each = n_row), nrow = n_row, ncol = n_col)) + } + + # Named list: one element per column, optionally per row within the column. + keep <- !is.na(nms) & nzchar(nms) + if (any(!keep)) { + fallback <- fmt[!keep] + if (length(fallback) > 1L) { + cli::cli_abort( + c( + "x" = "`{arg}` has {length(fallback)} unnamed elements.", + "i" = "Use at most one unnamed element: it styles every unnamed column." + ) + ) + } + out[] <- .ck_col_cls(el = fallback[[1L]], rns = rns, arg = arg) + } + idx <- match(nms[keep], cols) + if (anyNA(idx)) { + .ck_abort_unknown( + unknown = unique(nms[keep][is.na(idx)]), + keys = cols, + arg = arg, + what = "column" + ) + } + for (p in which(keep)) { + out[, match(nms[p], cols)] <- .ck_col_cls( + el = fmt[[p]], + rns = rns, + arg = arg + ) + } + # assigned back into the matrix, because `.ck_norm_class()` drops `dim` + out[] <- .ck_norm_class(cls = out, arg = arg) + out +} + +# Classes of one column of `value_format`: either one class for the column, or +# one class per row (named by row name, or positional). +.ck_col_cls <- function(el, rns, arg) { + n <- length(rns) + if (is.null(el)) { + return(rep("", n)) + } + if (!is.character(el)) { + cli::cli_abort( + "Elements of `{arg}` must be {.cls character}, not {.cls {class(el)}}." + ) + } + nms <- names(el) + out <- if (!is.null(nms) && any(!is.na(nms) & nzchar(nms))) { + .ck_map_named(vals = el, nms = nms, keys = rns, arg = arg, what = "row") + } else if (length(el) == 1L) { + rep(el, n) + } else if (length(el) == n) { + unname(el) + } else { + cli::cli_abort( + c( + "x" = "An element of `{arg}` must be length {n} (one per row) or 1, not {length(el)}.", + "i" = "Use a single string, a vector of length {n}, or a named vector." + ) + ) + } + .ck_norm_class(cls = out, arg = arg) +} + +# Match the named values of a format onto `keys`. The value without a name, if +# any, is the fallback style of the keys that are not named. +.ck_map_named <- function(vals, nms, keys, arg, what) { + n <- length(keys) + keep <- !is.na(nms) & nzchar(nms) + fallback <- vals[!keep] + if (length(fallback) > 1L) { + cli::cli_abort( + c( + "x" = "`{arg}` has {length(fallback)} unnamed values.", + "i" = "Use at most one unnamed value: it styles everything not named." + ) + ) + } + out <- rep(if (length(fallback) == 1L) fallback else "", n) + idx <- match(nms[keep], keys) + if (anyNA(idx)) { + .ck_abort_unknown( + unknown = unique(nms[keep][is.na(idx)]), + keys = keys, + arg = arg, + what = what + ) + } + out[idx] <- vals[keep] + out +} + +.ck_abort_unknown <- function(unknown, keys, arg, what) { + shown <- keys[seq_len(min(length(keys), 8L))] + more <- if (length(keys) > 8L) ", ..." else "" + cli::cli_abort( + c( + "x" = "`{arg}` refers to unknown {what} name{?s}: {.val {unknown}}.", + "i" = "Known {what} names: {paste0(shown, collapse = ', ')}{more}." + ) + ) +} + +# Normalise and validate cli inline classes: the leading dot is optional, and +# `""` is "no style". +.ck_norm_class <- function(cls, arg) { + cls <- trimws(as.character(cls)) + cls[is.na(cls)] <- "" + bare <- sub("^\\.", "", cls) + bad <- nzchar(bare) & !grepl("^[A-Za-z][A-Za-z0-9_.-]*$", bare) + if (any(bad)) { + cli::cli_abort( + c( + "x" = "`{arg}` contains an invalid cli class: {.val {unique(cls[bad])}}.", + "i" = "Use a cli inline class such as {.val .val}, {.val .field} or {.val .strong}, with or without the leading dot." + ) + ) + } + bare +} + +# Style a vector of strings, one class per element (`""` keeps the element as +# is). The class may add visible characters, e.g. the quotes of `{.val}`. +# +# A cli inline class renders as a prefix, the value, then a suffix, so the +# prefix and suffix of each distinct class are read from a single render call +# and pasted around the values. Formatting each cell with +# `cli::format_inline()` instead would cost a few milliseconds per cell. +.ck_style <- function(x, cls) { + out <- as.character(x) + cls <- rep_len(as.character(cls), length(out)) + uniq <- unique(cls[nzchar(cls)]) + if (!length(uniq)) { + return(out) + } + sentinel <- "ck_sentinel_6a1f" + rendered <- vapply( + X = uniq, + FUN = .ck_style1, + FUN.VALUE = character(1), + txt = sentinel + ) + at <- regexpr(sentinel, rendered, fixed = TRUE) + if (any(at < 1L)) { + # A class that drops the sentinel: render the cells one by one instead. + for (i in seq_along(out)) { + if (nzchar(cls[i])) { + out[i] <- .ck_style1(txt = out[i], cls = cls[i]) + } + } + return(out) + } + prefix <- substring(rendered, 1L, at - 1L) + suffix <- substring(rendered, at + nchar(sentinel)) + idx <- match(cls, uniq) + styled <- !is.na(idx) + out[styled] <- paste0(prefix[idx[styled]], out[styled], suffix[idx[styled]]) + out +} + +.ck_style1 <- function(txt, cls) { + # cli >= 3.4.0 rejects literals that start with a dot, so the leading dot of + # a class such as ".val" is dropped here rather than in the caller. + cls <- sub("^\\.", "", cls) + cli::format_inline( + text = paste0("{.", cls, " {txt}}"), + .envir = environment() + ) +} + +# Pad styled text to `w` visible characters, alignment per element. An unknown +# alignment is treated as left, and `how` is recycled over the elements. +.ck_pad <- function(txt, w, how) { + spare <- pmax(w - cli::ansi_nchar(x = txt, type = "width"), 0L) + how <- rep_len(how, length(spare)) + left <- ifelse( + how == "right", + spare, + ifelse(how == "center", spare %/% 2L, 0L) + ) + paste0( + strrep(x = " ", times = left), + txt, + strrep(x = " ", times = spare - left) + ) +} + +# The `:---` alignment rule of one or more columns. `how` is recycled over the +# columns, and an unknown alignment is treated as left. +.ck_rule <- function(w, how) { + how <- rep_len(how, length(w)) + dash <- pmax(w - 1L, 0L) + left <- paste0(":", strrep(x = "-", times = dash)) + right <- paste0(strrep(x = "-", times = dash), ":") + center <- paste0(":", strrep(x = "-", times = pmax(w - 2L, 0L)), ":") + ifelse(how == "right", right, ifelse(how == "center", center, left)) +} + +# nocov end diff --git a/inst/WORDLIST b/inst/WORDLIST index fff2d02..6b3851d 100644 --- a/inst/WORDLIST +++ b/inst/WORDLIST @@ -64,10 +64,12 @@ formatter gfm github honoured +honours https initializer io jarl +kable knitr labelled linter diff --git a/skills/rpkgkit/SKILL.md b/skills/rpkgkit/SKILL.md index f4bea16..a01019b 100644 --- a/skills/rpkgkit/SKILL.md +++ b/skills/rpkgkit/SKILL.md @@ -1,6 +1,6 @@ --- name: rpkgkit -description: Use rpkgkit functions to create and maintain R packages when the task involves qualifying package calls with pkg::, detecting CRAN-unsafe print()/cat(), lost glue braces, unmatched # nocov start / # nocov end markers or path-like arguments of exported functions that default to a concrete location, modernizing R syntax (base/magrittr pipes, integer L suffix, non-ASCII literals, \\( lambdas, knitr chunk headers), editing or displaying NEWS.md, creating r-lib standalone files, configuring DESCRIPTION fields, .Rbuildignore/.clangd/zzz.R, registering RStudio addins in inst/rstudio/addins.dcf, vendoring upstream code, generating GitHub Actions workflows (R-CMD-check including Rust/extendr builds, version bump, branch sync), or generating multilingual README translations and badges. +description: Use rpkgkit functions to create and maintain R packages when the task involves qualifying package calls with pkg::, detecting CRAN-unsafe print()/cat(), lost glue braces, unmatched # nocov start / # nocov end markers or path-like arguments of exported functions that default to a concrete location, modernizing R syntax (base/magrittr pipes, integer L suffix, non-ASCII literals, \\( lambdas, knitr chunk headers), editing or displaying NEWS.md, creating r-lib standalone files, configuring DESCRIPTION fields, .Rbuildignore/.clangd/zzz.R, registering RStudio addins in inst/rstudio/addins.dcf, vendoring upstream code, generating GitHub Actions workflows (R-CMD-check including Rust/extendr builds, version bump, branch sync), laying out long c()/list() calls as column-aligned tables with air, printing cli-styled frequency tables or kable-style data frames with the bundled cli helpers, or generating multilingual README translations and badges. --- # rpkgkit @@ -27,11 +27,14 @@ Use this skill when the request touches R package housekeeping: - Converting pipes, `function()` ↔ `\(`, integer literals, non-ASCII literals, Rmd chunk headers - Adding, showing, or formatting `NEWS.md` entries - Creating or validating r-lib style `standalone-*.R` files +- Printing frequency tables or `kable`-style data frames in the console with the + bundled `cli` standalone helpers (`cli_table()`, `cli_kable()`) - Adding DESCRIPTION fields (`URL`, `BugReports`, `Depends: R (>= ...)`), `.clangd`, `(pkg)-package.R` - Registering an exported function as an RStudio addin (`inst/rstudio/addins.dcf`) - Vendoring upstream code, or generating `.Rbuildignore` patterns - Multilingual README translations, AI-translation badges, README badges, Rmd YAML headers -- Formatting with air/flir, or checking `_pkgdown.yml` coverage +- Formatting with air/flir, laying out long `c()`/`list()` calls as tables, or + checking `_pkgdown.yml` coverage Do not use rpkgkit for general R programming questions, package installation, or CRAN submission mechanics beyond the functions listed here. @@ -77,6 +80,30 @@ rpkgkit::air_format() # format last Run `package_*` converters one at a time and inspect the diff in between; they all rewrite files on disk. Format only after all conversions are done. +## Workflow: formatting and table layout + +```r +rpkgkit::air_format("R/foo.R") # format with air +rpkgkit::flir_fix("R/foo.R") # lint-driven fixes with flir +rpkgkit::use_air_table("R/foo.R", ncol = 3L) # c()/list() -> aligned table +``` + +`use_air_table(path = NULL, ncol = 3L, min_length = 12L, marker = "# fmt: table")` +turns long vectors and lists into the column layout of `tibble::tribble()`, which +air 0.8.0+ supports through its experimental `# fmt: table` directive but never +builds on its own: the first `air format` run puts one element per line, the +directive is inserted above every `c()`/`list()` call holding more than +`min_length` elements, the elements are re-flowed `ncol` per row, and a second +`air format` run pads the cells and aligns the columns. Only calls whose elements +are all unnamed are rewritten (air expands named elements one per line whatever +the directive says), only the outermost call of a statement is converted (air +ignores the directive on nested calls), a line ending in a comment is never +joined with the next one, and a call that already carries the directive is left +alone, so the function is idempotent. `air` must be on the `PATH` — the function +starts with `check_air_installed()`, which prints the per-OS install command — and +the normalized path is returned invisibly. The write is not undoable, so commit +before running it. + ## Workflow: NEWS.md ```r @@ -103,6 +130,26 @@ The header carries `last modified`, license, imports, dependency, description an changelog block. `inquire_standalone(owner, repo)` lists candidates in a specific repository; `browse_standalone()` searches GitHub-wide (requires `gh`). +## Workflow: console tables with cli + +The bundled `cli` helpers are internal standalone scripts, not exports — vendor +the one you need into the target package first: + +```r +usethis::use_standalone("WangLabCSU/rpkgkit", "cli_kable") # R/standalone-cli_kable.R +``` + +- `cli_table(x)` / `cli_table_oneline(x)` print the frequency table of a vector on + two aligned lines, or on one `header: count` line. +- `cli_kable(df, header_format = ".val", rownames_format = ".val", value_format = NULL)` + prints the pipe table of `knitr::kable()` (the layout `kableExtra::kable()` + shows) with `cli` classes. Each format takes one class, or a named vector or + named list to style only the named columns or rows; an unnamed element is the + fallback of everything not named, and a `value_format` list element may be a + named vector of row names for per-cell styling. `align`, `digits`, `padding`, + `sep` and `rule` control the rest of the layout, and the printed lines are + returned invisibly. + ## Workflow: package infrastructure ```r @@ -130,6 +177,12 @@ packages: it installs a Rust toolchain and the `x86_64-pc-windows-gnu` target, without which the MSVC default cannot link against Rtools and the check ends in a WARNING. +The `use_zzz()` template reports the load time as a `cli` progress step: +`.onLoad()` opens it with `cli::cli_progress_step()` and `.onAttach()` closes it +with `cli::cli_process_done()`, both guarded by `startup_message_allowed()` and +keeping their state in `.time_record`. `use_zzz()` adds `cli` to `Imports` for +you. + ## Workflow: RStudio addins ```r diff --git a/skills/rpkgkit/references/function-reference.md b/skills/rpkgkit/references/function-reference.md index fa65f2c..b868851 100644 --- a/skills/rpkgkit/references/function-reference.md +++ b/skills/rpkgkit/references/function-reference.md @@ -14,6 +14,24 @@ document, falling back to the working directory. Source files are under `R/`. | `browse_standalone(per_page = 100L, limit = 200L, ...)` | `64_browse_standalone.R` | GitHub code search across repositories. Requires `gh`, `dplyr`. | | `check_standalone(path = NULL, ...)` | `65_check_standalone.R` | Validates header fields, `@noRd`, `# nocov start/end`; reports in `devtools::check()` style. | +## Bundled standalone helpers + +Internal scripts under `R/standalone-*.R` (`@noRd`, not exported). Vendor one into +another package with +`usethis::use_standalone("WangLabCSU/rpkgkit", "