| Title: | Create and Maintain R Packages |
|---|---|
| Description: | Utilities for R package development including NEWS.md management, standalone file creation, and code formatting. Supports popular development workflows and integrates with 'usethis' and 'RStudio'. Includes helper functions for renaming functions and detecting common coding errors. |
| Authors: | Yuxi Yang [aut, cre], Jacob Scott [ctb, cph] (Author of the included pedant code (https://github.com/wurli/pedant)), Christopher T. Kenny [ctb, cph] (Contributor to the included pedant code), Sebastian Lammers [ctb, cph] (Contributor to the included pedant code), Diego Hernangómez [ctb, cph] (Author of the included pkgdev code (https://github.com/dieghernan/pkgdev)) |
| Maintainer: | Yuxi Yang <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.2.0 |
| Built: | 2026-12-02 13:21:14 UTC |
| Source: | https://github.com/WangLabCSU/rpkgkit |
Assign elements of a list, vector, or data frame to variables in the calling
environment. The left-hand side must be a call to base::c() containing
variable names. Nested c() calls unpack nested lists. Named, missing
arguments select elements by name (for example, c(cyl =, wt =)). A
..name collector receives the positional elements not consumed by the other
targets in the same c() call; it may occur at the beginning, middle, or end.
The anonymous .. collector discards those elements. Use . and _ to skip
exactly one element.
lhs %<-% rhslhs %<-% rhs
lhs |
A destructuring target composed of variable names, nested
|
rhs |
A list, atomic vector, or data frame whose elements are assigned. |
The value of rhs, returned invisibly.
c(latitude, longitude) %<-% list(38.061944, -122.643889) c(cyl =, wt =) %<-% mtcars c(first, ..rest) %<-% letters c(..skip, penultimate, last) %<-% 1:5 c(begin, ..middle, end) %<-% 1:5 c(name, c(x, y), .) %<-% list("station", list(1, 2), "unused")c(latitude, longitude) %<-% list(38.061944, -122.643889) c(cyl =, wt =) %<-% mtcars c(first, ..rest) %<-% letters c(..skip, penultimate, last) %<-% 1:5 c(begin, ..middle, end) %<-% 1:5 c(name, c(x, y), .) %<-% list("station", list(1, 2), "unused")
Appends a new changelog entry at the top of the Changelog section in a
standalone file. Also updates the last-updated field in the YAML header
to today's date. If no Changelog section exists, one is created after
the YAML header.
add_changelog_in_standalone(path = NULL, description = NULL, date = NULL)add_changelog_in_standalone(path = NULL, description = NULL, date = NULL)
path |
Character. Path to a standalone file, a directory, or |
description |
Character. Description of the changelog entry.
If |
date |
Character. Date string in |
Invisibly returns the path to the updated file.
add_changelog_in_standalone(tempdir(), "Added new feature")add_changelog_in_standalone(tempdir(), "Added new feature")
This function takes a block of code and seeks to make all function calls
'explicit' through the use of the double-colon operator ::. This function
is bound to the RStudio addin "Make function calls explicit". See examples
for usage.
add_double_colons( code = NULL, use_packages = current_packages(), ignore_functions = imported_functions() )add_double_colons( code = NULL, use_packages = current_packages(), ignore_functions = imported_functions() )
code |
Code to transform. Either a character vector or |
use_packages |
A character vector of package names. The order is important here - see examples for details. |
ignore_functions |
Functions to ignore when applying the transformation |
This function behaves differently depending on the context.
Not package development: If the current
context is not package development, then it will make function calls explicit
using the currently attached packages (i.e. the ones attached by calls to
library()).
Package development: If it detects that the current context is package
development it will make function calls explicit using packages in the
'Imports' field of the package DESCRIPTION. If the package being developed
imports any packages in their entirety (i.e if Import pkg appears in the
NAMESPACE file), calls to functions from these packages will be left
unchanged.
See current_packages() for more information.
The transformed code as a character string
code <- " cars <- as_tibble(mtcars) cars %>% filter(mpg > 20) %>% summarise(across(everything(), n_distinct)) " # Code will be transformed to use the double-colon operator, but notice # that `n_distinct` is not transformed as it is not followed by `()` cat(add_double_colons(code, "dplyr")) # You can specify functions that shouldn't be transformed: cat(add_double_colons(code, "dplyr", ignore_functions = "across")) # Beware namespace conflicts! The following are not the same, mimicking # the effects of reordering calls to `library()`: cat(add_double_colons(code, c("dplyr", "stats"))) cat(add_double_colons(code, c("stats", "dplyr")))code <- " cars <- as_tibble(mtcars) cars %>% filter(mpg > 20) %>% summarise(across(everything(), n_distinct)) " # Code will be transformed to use the double-colon operator, but notice # that `n_distinct` is not transformed as it is not followed by `()` cat(add_double_colons(code, "dplyr")) # You can specify functions that shouldn't be transformed: cat(add_double_colons(code, "dplyr", ignore_functions = "across")) # Beware namespace conflicts! The following are not the same, mimicking # the effects of reordering calls to `library()`: cat(add_double_colons(code, c("dplyr", "stats"))) cat(add_double_colons(code, c("stats", "dplyr")))
.gitignore to packageAdds a global .gitgnore file to the package. File based on default
.gitignore provided by GitHub.
add_global_gitgnore(pkg = NULL)add_global_gitgnore(pkg = NULL)
pkg |
The package to add the |
Invisible, and writes a global .gitignore file
usethis::use_git_ignore(), usethis::git_vaccinate()
## Not run: add_global_gitgnore() ## End(Not run)## Not run: add_global_gitgnore() ## End(Not run)
Appends a curated set of common files and directories to .Rbuildignore
to exclude them from R package builds. This supplements the auto-generated
.Rbuildignore created by usethis::create_package().
Already-present patterns are silently skipped. The curated set covers: R build artifacts, Git files, IDE/dev tool directories, CI/CD config, documentation build artifacts, CRAN/development files, and other common files that should not be shipped with a package.
add_global_rbuildignore( ..., pattern = GLOBAL_RBUILDIGNORE_PATTERN, replace_default = FALSE, path = NULL )add_global_rbuildignore( ..., pattern = GLOBAL_RBUILDIGNORE_PATTERN, replace_default = FALSE, path = NULL )
... |
Additional regex patterns (character strings) to add beyond
the selected patterns. Each must already be in |
pattern |
Character vector of |
replace_default |
Logical. If |
path |
Character. Path to the package root directory. If |
Invisibly returns the path to .Rbuildignore.
## Not run: add_global_rbuildignore() # With additional custom patterns add_global_rbuildignore("^\\.myconfig$", "^data-raw$") # Use only a custom pattern set add_global_rbuildignore( pattern = c("^\\.github$", "^docs$"), replace_default = TRUE ) ## End(Not run)## Not run: add_global_rbuildignore() # With additional custom patterns add_global_rbuildignore("^\\.myconfig$", "^data-raw$") # Use only a custom pattern set add_global_rbuildignore( pattern = c("^\\.github$", "^docs$"), replace_default = TRUE ) ## End(Not run)
air_format(path = NULL, ...)air_format(path = NULL, ...)
path |
Path to the R file to format. If NULL, attempts to use the active
document in RStudio (requires |
... |
Additional arguments passed to |
Install air:
Linux: curl -LsSf https://github.com/posit-dev/air/releases/latest/download/air-installer.sh | sh
Windows: powershell -ExecutionPolicy Bypass -c "irm https://github.com/posit-dev/air/releases/latest/download/air-installer.ps1 | iex"
uv: uv tool install air-formatter
brew (MacOS): brew install air
The exit status of the air format command (invisibly).
## Not run: air_format(system.file("R_template/zzz_template.R", package = "rpkgkit")) ## End(Not run)## Not run: air_format(system.file("R_template/zzz_template.R", package = "rpkgkit")) ## End(Not run)
Adds a markdown badge (typically from badger) to the
<!-- badges: start --> ... <!-- badges: end --> block in
README.Rmd or README.md.
If both files exist, only README.Rmd is updated.
badge_to_readme(badge, path = NULL, ...)badge_to_readme(badge, path = NULL, ...)
badge |
Character. Badge markdown, e.g. the output of
|
path |
Character. Path to the package root. If |
... |
Not used. |
Invisibly returns the path to the modified README file.
## Not run: 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) ## End(Not run)## Not run: 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) ## End(Not run)
Prints a shields.io badge and a blockquote note for each specified language that can be copied into a translated README file to indicate the content was AI-translated and has not been reviewed.
Each language entry consists of:
A badge: []()
A blockquote with the full disclaimer text in that language
badge_translated_by_ai(lang = "en", color = "yellow")badge_translated_by_ai(lang = "en", color = "yellow")
lang |
Character vector of language codes (e.g. |
color |
Color of badge. Defaults to |
Invisibly returns a named list of character vectors, where each element contains the badge line and blockquote note for one language.
## Not run: # All 19 languages badge_translated_by_ai() # Just one language badge_translated_by_ai("de") # A few languages badge_translated_by_ai(c("ja", "ko")) ## End(Not run)## Not run: # All 19 languages badge_translated_by_ai() # Just one language badge_translated_by_ai("de") # A few languages badge_translated_by_ai(c("ja", "ko")) ## End(Not run)
Search GitHub for all standalone-*.R files and return the file
and repository metadata of the matches as a tibble.
browse_standalone(per_page = 100L, limit = 200L, ..., token = NULL)browse_standalone(per_page = 100L, limit = 200L, ..., token = NULL)
per_page |
Number of items to request per page, between 1 and 100.
Defaults to |
limit |
Number of records to return. Defaults to |
... |
No arguments. |
token |
A GitHub personal access token. When |
The crawl runs in Rust. It queries the GitHub Code Search API
(GET /search/code) with
filename:standalone- language:R -filename:import-, pages through the
results until limit rows are collected, drops the hits whose name does
not start with "standalone-" and removes duplicates. The search API ranks by
relevance and exposes at most 1,000 results, which covers the vast majority
of standalone files on GitHub.
A tibble with columns:
Character. Repository identifier in "owner/repo" format.
Character. File name (e.g. "standalone-utils.R").
Character. File path within the repository (e.g. "R/standalone-utils.R").
Character. File SHA.
Character. GitHub API URL for the file.
Character. GitHub HTML URL for the file.
Character. Git blob URL for the file.
Character. Repository URL on GitHub.
Character. Repository description from GitHub.
Without a token GitHub applies strict rate limits (60 requests per
hour). Set GITHUB_PAT in ~/.Renviron to lift them.
## Not run: browse_standalone() ## End(Not run)## Not run: browse_standalone() ## End(Not run)
Verifies that air (the R code formatter from Posit) is available on the
system PATH. In an interactive session, offers to install it when missing.
This prompt is skipped while tests are running. Otherwise, it aborts with
OS-specific installation instructions.
check_air_installed()check_air_installed()
Installation methods per OS:
Linux:
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/posit-dev/air/releases/latest/download/air-installer.sh | sh
Windows:
powershell -ExecutionPolicy Bypass -c "irm https://github.com/posit-dev/air/releases/latest/download/air-installer.ps1 | iex"
macOS:
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/posit-dev/air/releases/latest/download/air-installer.sh | sh
Invisibly returns TRUE if air is found.
Parses the NAMESPACE and _pkgdown.yml (if present) and reports any
exported functions that are missing from the pkgdown reference index.
check_pkgdown_reference(pkg = ".")check_pkgdown_reference(pkg = ".")
pkg |
Character. Path to the package root directory.
Defaults to the current RStudio project or |
Invisibly returns a character vector of missing function names,
or NULL if _pkgdown.yml does not exist. Prints a summary via cli.
## Not run: dir <- tempdir() usethis::create_package(dir) usethis::proj_set(dir) usethis::use_pkgdown() check_pkgdown_reference(dir) ## End(Not run)## Not run: dir <- tempdir() usethis::create_package(dir) usethis::proj_set(dir) usethis::use_pkgdown() check_pkgdown_reference(dir) ## End(Not run)
Checks a standalone file against the layout used by r-lib/rlang
(as consumed by usethis::use_standalone()). Three points are checked:
the header format, and whether each slot has a value;
every documented function carries @noRd (undocumented functions are
skipped);
a # nocov start marker exists and precedes all functions
(# nocov end is optional).
check_standalone(path = NULL, ...)check_standalone(path = NULL, ...)
path |
Path to the standalone file (a single string). |
... |
Unused |
Each check point that reports nothing is announced as a success. Warnings and notes never stop the run, but an error does: the remaining check points are then skipped.
Results are printed in the style of devtools::check().
Invisibly, list(error = , warning = , note = ), where each element
is an integer.
## Not run: check_standalone("R/standalone-purrr.R") ## End(Not run)## Not run: check_standalone("R/standalone-purrr.R") ## End(Not run)
Detects the system package manager, checks each system dependency, and
reports the result with cli. Argument validation uses rlang.
On Windows, winget, choco and scoop are supported (scoop is queried
through PowerShell).
check_sysdeps(deps = NULL, manager = NULL, verbose = TRUE)check_sysdeps(deps = NULL, manager = NULL, verbose = TRUE)
deps |
A character vector of system package names to check. Names must
match the naming convention of the package manager in use. Alternative
names can be given as |
manager |
The package manager: one of |
verbose |
Logical. If |
A named logical vector (package name -> installed or not),
returned invisibly. It carries the attribute "manager" (the manager
used) and, if anything is missing, "install_cmd" (a suggested install
command).
# `deps` must follow the naming convention of the manager in use, and the # managers themselves are OS specific, so every example runs only where the # matching executable is available. # Fedora / RHEL / openSUSE if (nzchar(Sys.which("rpm"))) { check_sysdeps( c("freetype-devel", "libwebp-devel", "glpk-devel"), manager = "rpm" ) } # Debian / Ubuntu, with an alternative name for freetype if (nzchar(Sys.which("dpkg"))) { check_sysdeps( c("libfreetype-dev|libfreetype6-dev", "libpng-dev"), manager = "dpkg" ) } # macOS if (nzchar(Sys.which("brew"))) { check_sysdeps(manager = "brew") } # Windows: `winget`, `choco` and `scoop` have no built-in dependency list, # so `deps` is always required. if (nzchar(Sys.which("winget"))) { check_sysdeps(c("Git.Git", "Kitware.CMake"), manager = "winget") } # The result is a named logical vector that carries the manager used, so the # missing dependencies can be extracted and reused in a script. default_managers <- c("dpkg", "rpm", "pacman", "apk", "brew") available <- default_managers[nzchar(Sys.which(default_managers))] if (length(available) > 0L) { ok <- check_sysdeps(manager = available[[1L]], verbose = FALSE) attr(ok, "manager") ok[!ok] }# `deps` must follow the naming convention of the manager in use, and the # managers themselves are OS specific, so every example runs only where the # matching executable is available. # Fedora / RHEL / openSUSE if (nzchar(Sys.which("rpm"))) { check_sysdeps( c("freetype-devel", "libwebp-devel", "glpk-devel"), manager = "rpm" ) } # Debian / Ubuntu, with an alternative name for freetype if (nzchar(Sys.which("dpkg"))) { check_sysdeps( c("libfreetype-dev|libfreetype6-dev", "libpng-dev"), manager = "dpkg" ) } # macOS if (nzchar(Sys.which("brew"))) { check_sysdeps(manager = "brew") } # Windows: `winget`, `choco` and `scoop` have no built-in dependency list, # so `deps` is always required. if (nzchar(Sys.which("winget"))) { check_sysdeps(c("Git.Git", "Kitware.CMake"), manager = "winget") } # The result is a named logical vector that carries the manager used, so the # missing dependencies can be extracted and reused in a script. default_managers <- c("dpkg", "rpm", "pacman", "apk", "brew") available <- default_managers[nzchar(Sys.which(default_managers))] if (length(available) > 0L) { ok <- check_sysdeps(manager = available[[1L]], verbose = FALSE) attr(ok, "manager") ok[!ok] }
function() and Implicit \() SyntaxConverts all function definitions in an R file between the explicit
function() syntax and the R 4.1+ concise lambda \() syntax.
Handles strings and comments correctly, and supports nested function
definitions via iterative passes.
convert_func_syntax( path = NULL, direction = c("to_lambda", "to_explicit"), ... )convert_func_syntax( path = NULL, direction = c("to_lambda", "to_explicit"), ... )
path |
A character string specifying the path to the R file to modify.
If |
direction |
Conversion direction. One of:
|
... |
Additional arguments. Currently unused and must be empty. |
The conversion correctly handles strings, comments, and nested parentheses
in default argument values (e.g., function(x = foo(y))).
Nested function definitions (e.g., function(x, f = function(y) ...)) are
converted in multiple iterative passes, so all nesting levels are reached.
Invisibly returns the path to the modified file.
temp <- tempfile(fileext = ".R") writeLines("add_one <- function(x) x + 1", temp) convert_func_syntax(temp, direction = "to_lambda") readLines(temp) # "add_one <- \(x) x + 1" convert_func_syntax(temp, direction = "to_explicit") readLines(temp) # "add_one <- function(x) x + 1"temp <- tempfile(fileext = ".R") writeLines("add_one <- function(x) x + 1", temp) convert_func_syntax(temp, direction = "to_lambda") readLines(temp) # "add_one <- \(x) x + 1" convert_func_syntax(temp, direction = "to_explicit") readLines(temp) # "add_one <- function(x) x + 1"
Converts legacy knitr chunk headers in R Markdown (.Rmd) files to the
current header syntax using knitr::convert_chunk_header().
When path points to an R package root (a directory containing a
DESCRIPTION file), the conversion is applied to all .Rmd files found
under the package vignettes/ directory (including subdirectories) and to
the package README.Rmd file when present.
When path points to a single file, that file is converted and written
back in place.
convert_knitr_chunk_header(path = NULL, ...)convert_knitr_chunk_header(path = NULL, ...)
path |
Path to an R package root directory or an R Markdown file.
If |
... |
Additional arguments passed to |
Invisibly returns a character vector of file paths that were converted.
tmp <- tempfile(fileext = ".Rmd") writeLines(c("```{r, echo=TRUE, fig.width=10}", "x <- 1", "```"), tmp) convert_knitr_chunk_header(tmp) readLines(tmp)tmp <- tempfile(fileext = ".Rmd") writeLines(c("```{r, echo=TRUE, fig.width=10}", "x <- 1", "```"), tmp) convert_knitr_chunk_header(tmp) readLines(tmp)
Converts non-ASCII characters in R code to their ASCII escape sequences
(e.g., \uXXXX), or restores ASCII escape sequences back to readable
characters. Accepts either an R expression (via NSE) or a file path
(as a character string).
convert_nonascii_code(code, ..., reverse = FALSE, overwrite = NULL)convert_nonascii_code(code, ..., reverse = FALSE, overwrite = NULL)
code |
An R expression or a file path (character). When a bare expression is supplied, it is captured via NSE and deparsed. When a character string that points to an existing file is supplied, the file content is read and converted. |
... |
Additional arguments (must be empty). |
reverse |
Logical. If |
overwrite |
Logical. Only used when |
Invisibly returns the converted code as a character string.
If code is a file path and overwrite = TRUE, the file is updated
in place and the function returns the path invisibly.
# Convert non-ASCII characters in a bare expression to \u escapes convert_nonascii_code(print('\u4e2d\u6587')) # Reverse: restore \u escapes to readable characters convert_nonascii_code(print('\u4e2d\u6587'), reverse = TRUE)# Convert non-ASCII characters in a bare expression to \u escapes convert_nonascii_code(print('\u4e2d\u6587')) # Reverse: restore \u escapes to readable characters convert_nonascii_code(print('\u4e2d\u6587'), reverse = TRUE)
path is an R package, the file is created in the R/ subdirectory.Creates a new standalone R script with YAML metadata header.
If path is an R package, the file is created in the R/ subdirectory.
create_standalone( standalone_name = NULL, path = NULL, standalone_head = list(license = "https://unlicense.org", imports = NULL, dependency = NULL, description = "This file provides..."), open = rlang::is_interactive(), ... )create_standalone( standalone_name = NULL, path = NULL, standalone_head = list(license = "https://unlicense.org", imports = NULL, dependency = NULL, description = "This file provides..."), open = rlang::is_interactive(), ... )
standalone_name |
Character. The name suffix for the standalone file (e.g., "my_utils" creates "standalone-my_utils.R"). |
path |
Character. Directory path where to create the file.
Defaults to the current working directory ( |
standalone_head |
List. Metadata for the file header with elements:
|
open |
Logical. Whether to open the file in RStudio editor. Defaults to TRUE. |
... |
Additional arguments (must be empty). |
Invisibly returns the path to the created file.
create_standalone("my_utils", path = tempdir())create_standalone("my_utils", path = tempdir())
Automatically detect the type of path (file, package, or directory) and apply the appropriate flir fix function.
flir_fix(path = NULL, ...)flir_fix(path = NULL, ...)
path |
A file path, package directory path, or NULL. If NULL and running in RStudio, uses the active document path. |
... |
Additional arguments passed to the underlying flir fix function. |
The function determines the fix strategy based on the path type:
If path points to an existing file, calls flir::fix()
If path is a package directory (contains DESCRIPTION), calls flir::fix_package()
If path is a directory, calls flir::fix_dir()
Invisibly returns the result from the called flir function.
## Not run: tmp <- tempfile(fileext = ".R") writeLines("a<-1+1", tmp) flir_fix(tmp) cat(readLines(tmp, warn = FALSE), sep = "\n") ## End(Not run)## Not run: tmp <- tempfile(fileext = ".R") writeLines("a<-1+1", tmp) flir_fix(tmp) cat(readLines(tmp, warn = FALSE), sep = "\n") ## End(Not run)
Get the version of the Positron IDE
get_positron_version(long = FALSE)get_positron_version(long = FALSE)
long |
Whether to return the full version including the build number (e.g. "2025.01.0-123"). Defaults to FALSE. |
A character string with the version number, or NA_character_ if not running inside Positron and the version cannot be located.
Recursively traces variable assignments (both from function parameters and function body) to reconstruct and evaluate the expression that produces the variable's value. The trace follows the assignment chain until it reaches literal values or unresolvable symbols.
get_var_value(var_name, func, .env = rlang::current_env())get_var_value(var_name, func, .env = rlang::current_env())
var_name |
Character string, the name of the target variable. |
func |
An R function inside which the variable is defined. |
.env |
Evaluation environment used for resolving function calls
(e.g. |
The computed value of the variable.
f <- function(save_path = "analysis") { save_path_new <- file.path(save_path, "res") return(save_path_new) } get_var_value("save_path_new", f) # returns "./analysis/res" g <- function(a = 1, b = 2){ c <- a * 2 + b * 3 d = c^2 e <<- d - 1 e } get_var_value("e", g) # returns 63 h <- function(a = "A", ...){ a <- 1 return(a) a <- 2 a } get_var_value("a",h) # returns 1 (dead code after return is ignored) i <- function(x = 2) { for (k in 1:3) x <- x * 2 x } get_var_value("x", i) # returns 16 j <- function(x = 2) { while (x < 10) x <- x * 2 x } get_var_value("x", j) # returns 16f <- function(save_path = "analysis") { save_path_new <- file.path(save_path, "res") return(save_path_new) } get_var_value("save_path_new", f) # returns "./analysis/res" g <- function(a = 1, b = 2){ c <- a * 2 + b * 3 d = c^2 e <<- d - 1 e } get_var_value("e", g) # returns 63 h <- function(a = "A", ...){ a <- 1 return(a) a <- 2 a } get_var_value("a",h) # returns 1 (dead code after return is ignored) i <- function(x = 2) { for (k in 1:3) x <- x * 2 x } get_var_value("x", i) # returns 16 j <- function(x = 2) { while (x < 10) x <- x * 2 x } get_var_value("x", j) # returns 16
Retrieve information about all standalone R files in the R/ directory of a GitHub repository. Standalone files are identified by the "standalone-" prefix in their filename.
inquire_standalone(owner, repo, ..., token = NULL)inquire_standalone(owner, repo, ..., token = NULL)
owner |
A character string specifying the repository owner's username. |
repo |
A character string specifying the repository name. |
... |
No arguments. |
token |
A GitHub personal access token. When |
The crawl runs in Rust. One request lists the R/ directory through
the GitHub contents API; the listing is then filtered on the "standalone-"
prefix, sorted by file name and deduplicated, and the provenance header of
each remaining file is read with one download of its raw contents.
A tibble with one row per standalone file:
The fields of the GitHub contents API entry of the file.
Character string, the repository identifier in "owner/repo" format.
Character string, the description extracted from the
file's provenance header (the # --- block written by
usethis::use_standalone()) or from its roxygen documentation, NA when
the file has neither.
Character string, the code to import the standalone file using
usethis::use_standalone().
## Not run: inquire_standalone("r-lib", "rlang") ## End(Not run)## Not run: inquire_standalone("r-lib", "rlang") ## End(Not run)
These functions find the packages/functions to use when running
add_double_colons().
is_dev_context(dir = ".") imported_functions(dir = ".") current_packages( dir = ".", base_packages = getOption("defaultPackages"), include_types = "Imports" )is_dev_context(dir = ".") imported_functions(dir = ".") current_packages( dir = ".", base_packages = getOption("defaultPackages"), include_types = "Imports" )
dir |
The current working directory |
base_packages |
Default packages to include |
include_types |
The types of package imports to return if the current
context is package development. Should be a subset of
|
current_packages() first checks if the current context is package
development. If it is, then it returns the packages which are listed in the
package DESCRIPTION as dependencies, but will not return any packages also
listed as imports in the package NAMESPACE. If the current context is not
package development, the currently attached packages (as given by search())
are used. Note that if {pkgload} is not installed then the latter option is
always used.
imported_functions() looks for a package NAMESPACE file and returns the
names of all imported functions. If a NAMESPACE file is not found, or if
{pkgload} is not loaded, NULL is returned.
TRUE if the current context is package development, FALSE otherwise.
A character vector of imported function names, or NULL if no
NAMESPACE file is found or {pkgload} is not installed.
A character vector of package names.
Functions to help manage the NEWS.md file in R packages according to CRAN guidelines. Includes functions to add new entries and check the format.
Validates the NEWS.md file against CRAN guidelines and common best practices.
Reports issues found and provides suggestions for fixes.
Reads and displays the NEWS.md file content with optional filtering.
Adds a new entry to the NEWS.md file following CRAN guidelines. Can create a new version section if needed or add to an existing one.
news_md_check(path = NULL, strict = FALSE, verbose = TRUE) news_md_show(path = NULL, version = NULL, max_versions = NULL) news_md_add_entry( entry, version = NULL, category = "NEW FEATURES", contributor = NULL, path = NULL, date = NULL, open_section = TRUE )news_md_check(path = NULL, strict = FALSE, verbose = TRUE) news_md_show(path = NULL, version = NULL, max_versions = NULL) news_md_add_entry( entry, version = NULL, category = "NEW FEATURES", contributor = NULL, path = NULL, date = NULL, open_section = TRUE )
path |
Path to the package root. If |
strict |
If TRUE, treats warnings as errors. Default is FALSE. |
verbose |
If TRUE, prints detailed information about checks performed. |
version |
Package version number. If NULL, uses the version from DESCRIPTION. |
max_versions |
Maximum number of versions to display. NULL shows all. |
entry |
Text of the news entry (without leading "* "). |
category |
Category of the change (e.g., "NEW FEATURES", "BUG FIXES", "MINOR IMPROVEMENTS", "DOCUMENTATION", "DEPRECATED", "DEFUNCT", "BREAKING CHANGES", "PERFORMANCE", "TESTING", "INTERNAL CHANGES"). Default is "NEW FEATURES". |
contributor |
GitHub username or name for attribution (optional). |
date |
Date of the release. If NULL, uses today's date (YYYY-MM-DD format). |
open_section |
If TRUE and the version section exists but isn't open (has content after it), creates a new section. If FALSE, adds to existing section. |
The NEWS.md format follows CRAN recommendations:
Version headers use # followed by "package version (date)"
Major changes use ## with category names (e.g., "NEW FEATURES", "BUG FIXES")
Individual items use bullet points starting with *
Contributor acknowledgments use (@username) at the end of items
Dates should be in YYYY-MM-DD format
A list with components:
Logical indicating if NEWS.md passes all checks.
Character vector of error messages.
Character vector of warning messages.
Character vector of improvement suggestions.
Invisibly returns the content as a character vector.
Invisibly returns the path to the NEWS.md file.
## Not run: temp <- tempdir() usethis::create_package(temp) file.create(file.path(temp, "NEWS.md")) result <- news_md_check(temp) if (!result$valid) { print(result$errors) print(result$warnings) } ## End(Not run) ## Not run: temp <- tempdir() usethis::create_package(temp) file.create(file.path(temp, "NEWS.md")) news_md_add_entry("Added `foo()`", path = temp) # Show latest version news news_md_show(version = "latest", path = temp) # Show last 3 versions news_md_show(max_versions = 3, path = temp) ## End(Not run) ## Not run: temp <- tempdir() usethis::create_package(temp) file.create(file.path(temp, "NEWS.md")) # Add a bug fix entry news_md_add_entry("Fixed issue with parsing large files.", category = "BUG FIXES", contributor = "johndoe", path = temp) # Add a new feature with specific version news_md_add_entry("Added new function for data validation.", version = "1.2.0", category = "NEW FEATURES", path = temp) ## End(Not run)## Not run: temp <- tempdir() usethis::create_package(temp) file.create(file.path(temp, "NEWS.md")) result <- news_md_check(temp) if (!result$valid) { print(result$errors) print(result$warnings) } ## End(Not run) ## Not run: temp <- tempdir() usethis::create_package(temp) file.create(file.path(temp, "NEWS.md")) news_md_add_entry("Added `foo()`", path = temp) # Show latest version news news_md_show(version = "latest", path = temp) # Show last 3 versions news_md_show(max_versions = 3, path = temp) ## End(Not run) ## Not run: temp <- tempdir() usethis::create_package(temp) file.create(file.path(temp, "NEWS.md")) # Add a bug fix entry news_md_add_entry("Fixed issue with parsing large files.", category = "BUG FIXES", contributor = "johndoe", path = temp) # Add a new feature with specific version news_md_add_entry("Added new function for data validation.", version = "1.2.0", category = "NEW FEATURES", path = temp) ## End(Not run)
Opens the CFF (Citation File Format) initializer web application in the default browser.
open_cffinit(...)open_cffinit(...)
... |
Unused arguments, for future extensibility. |
Invisible TRUE, called for side effects.
Optimizes the YAML header of a single README.Rmd or vignette. Package
metadata (Package / Title / Version / Authors@R / Date / Language) is read
with the desc package from the DESCRIPTION found by walking up from path.
optimize_rmd_yaml( path = NULL, type = c("auto", "readme", "vignette"), readme_format = c("gfm", "github_document", "html"), date = c("auto", "desc", "none"), extra = NULL, extra_readme = NULL, extra_vignette = NULL )optimize_rmd_yaml( path = NULL, type = c("auto", "readme", "vignette"), readme_format = c("gfm", "github_document", "html"), date = c("auto", "desc", "none"), extra = NULL, extra_readme = NULL, extra_vignette = NULL )
path |
Path to an Rmd file. If |
type |
"auto" (README.Rmd is a readme, everything else a vignette), "readme" or "vignette". |
readme_format |
Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html". |
date |
"auto" -> |
extra |
Named list of extra YAML fields added to the file. It is merged
onto the built-in defaults with |
extra_readme, extra_vignette
|
Same as Extra fields never overwrite a key that already exists in the header;
they are only added when missing. A key that is also generated by default
(e.g. |
Compatibility rules (the usethis template is treated as the "default"):
A field that still has its usethis default value (title "Untitled" or equal
to the file name, a bare output: html_document /
output: rmarkdown::html_vignette, an "Untitled" VignetteIndexEntry) is
replaced by an enriched value.
A field the user has changed is kept. For output, the user's options are
merged on top of the enriched defaults (user values always win), and other
output formats (pdf_document, word_document, ...) are left untouched.
Fields that usethis never writes (author, date, params, bibliography, knit, css, ...) are kept exactly as written when present, and only filled in when missing.
Headers containing !expr in output are never rewritten.
TRUE if the file was changed, FALSE otherwise (invisibly).
## Not run: optimize_rmd_yaml() # active RStudio document optimize_rmd_yaml("vignettes/intro.Rmd") optimize_rmd_yaml("README.Rmd", readme_format = "github_document") ## End(Not run)## Not run: optimize_rmd_yaml() # active RStudio document optimize_rmd_yaml("vignettes/intro.Rmd") optimize_rmd_yaml("README.Rmd", readme_format = "github_document") ## End(Not run)
L to Integer LiteralsConverts bare integer literals to explicit integer form with an L suffix,
e.g. seq_len(10) becomes seq_len(10L). Strings and comments are left
unchanged, and a line can opt out with a # rpkgkit: not int comment (see
the section below).
convert_int_literals() operates on one R file. When path is NULL and
RStudio is available, it uses the currently active document.
package_convert_int_literals() walks selected directories of an R package
and applies the same conversion to every .R / .r file found, except
files generated by Rcpp::compileAttributes() or rextendr::document()
(see exclude).
package_convert_int_literals( path = NULL, dirs = c("R"), recursive = TRUE, exclude = c("RcppExports.R", "extendr-wrappers.R"), ... ) convert_int_literals(path = NULL, verbose = TRUE, ...)package_convert_int_literals( path = NULL, dirs = c("R"), recursive = TRUE, exclude = c("RcppExports.R", "extendr-wrappers.R"), ... ) convert_int_literals(path = NULL, verbose = TRUE, ...)
path |
For For |
dirs |
Character vector of subdirectories relative to |
recursive |
Logical; recurse into subdirectories. Used only by
|
exclude |
Character vector of file names to skip, matched
case-insensitively against the file base name. Used only by
|
... |
Additional arguments. Currently unused and must be empty. |
verbose |
Logical; enable or disable per-file messages. Used only by
|
A token is treated as an integer literal when it is:
a decimal integer (10, 0, - is not part of the token), or
a hexadecimal integer (0xFF, 0X10),
and it is not:
already suffixed with L / l,
a floating-point number (10., 1.0, .5),
scientific notation, including a signed exponent (1e5, 1e-3, 1E-3),
a complex literal (10i),
adjacent to an identifier character (a-zA-Z0-9._).
convert_int_literals() invisibly returns the modified file path.
package_convert_int_literals() invisibly returns a character vector of
modified file paths.
Adding L changes the type of a literal, so some expressions must keep
their double literals (2^31, 2147483648, 1e9 * 4). Write a
# rpkgkit: not int comment on the line just above such a line, and every
literal on that line is left untouched:
# rpkgkit: not int y <- 2^31
The marker covers the immediately following line only, so a block needs one
marker per line. It is matched case-insensitively and tolerates extra
spaces, but it has to be the only thing on its line: a trailing
x <- 1 # rpkgkit: not int opts nothing out.
## Not run: # --- Single file --- temp <- tempfile(fileext = ".R") writeLines("tmp <- seq_len(10)", temp) convert_int_literals(temp) readLines(temp) # "tmp <- seq_len(10L)" # --- Opting a line out --- writeLines(c("# rpkgkit: not int", "y <- 2^31"), temp) convert_int_literals(temp) readLines(temp) # "# rpkgkit: not int" "y <- 2^31" # --- Entire package --- tmp_pkg <- tempdir() usethis::create_package(tmp_pkg, open = FALSE) writeLines("foo <- seq_len(42)", file.path(tmp_pkg, "R/foo.R")) package_convert_int_literals(tmp_pkg) readLines(file.path(tmp_pkg, "R/foo.R")) ## End(Not run)## Not run: # --- Single file --- temp <- tempfile(fileext = ".R") writeLines("tmp <- seq_len(10)", temp) convert_int_literals(temp) readLines(temp) # "tmp <- seq_len(10L)" # --- Opting a line out --- writeLines(c("# rpkgkit: not int", "y <- 2^31"), temp) convert_int_literals(temp) readLines(temp) # "# rpkgkit: not int" "y <- 2^31" # --- Entire package --- tmp_pkg <- tempdir() usethis::create_package(tmp_pkg, open = FALSE) writeLines("foo <- seq_len(42)", file.path(tmp_pkg, "R/foo.R")) package_convert_int_literals(tmp_pkg) readLines(file.path(tmp_pkg, "R/foo.R")) ## End(Not run)
%>% and the Base Pipe |>
Rewrites pipe operators in an R file between the magrittr pipe %>% and the
base pipe |>. Strings, comments, and raw strings are left unchanged, so a
mention of either operator in documentation or a character literal is not
rewritten.
convert_pipe() operates on one R file. When path is NULL and RStudio is
available, it uses the currently active document.
package_convert_pipe() walks selected directories of an R package and
applies the same conversion to every .R / .r file found, except
automatically generated RcppExports.R files.
The placeholder pipe %<>% and the exposition pipe %$% are not pipes in
this sense and are left untouched.
package_convert_pipe( path = NULL, direction = c("to_base", "to_magrittr"), dirs = c("R"), recursive = TRUE, ... ) convert_pipe( path = NULL, direction = c("to_base", "to_magrittr"), verbose = TRUE, ... )package_convert_pipe( path = NULL, direction = c("to_base", "to_magrittr"), dirs = c("R"), recursive = TRUE, ... ) convert_pipe( path = NULL, direction = c("to_base", "to_magrittr"), verbose = TRUE, ... )
path |
For For |
direction |
Conversion direction. One of:
|
dirs |
Character vector of subdirectories relative to |
recursive |
Logical; recurse into subdirectories. Used only by
|
... |
Additional arguments. Currently unused and must be empty. |
verbose |
Logical; enable or disable per-file messages. Used only by
|
Rewriting is a literal match, so only a complete operator is converted:
%>% becomes |>, and |> becomes %>%.
Matching is literal, so % > % (whitespace inside the operator) is not
converted, and %<>%, %$%, and longer operators such as %myop% are
left unchanged.
|> is matched only when % does not immediately precede it, so the tail
of an operator such as %|>% is not treated as a base pipe.
Occurrences inside string literals, raw strings, and comments are left unchanged.
Both functions are called for their side effect and invisibly return TRUE
when they convert something. When there is nothing to convert, FALSE is returned
## Not run: # --- Single file --- temp <- tempfile(fileext = ".R") writeLines("mtcars |> dplyr::filter(cyl > 4)", temp) convert_pipe(temp, direction = "to_magrittr") readLines(temp) # "mtcars %>% dplyr::filter(cyl > 4)" # --- Entire package --- tmp_pkg <- tempdir() usethis::create_package(tmp_pkg, open = FALSE) writeLines("mtcars %>% dplyr::filter(cyl > 4)", file.path(tmp_pkg, "R/foo.R")) package_convert_pipe(tmp_pkg, direction = "to_base") readLines(file.path(tmp_pkg, "R/foo.R")) ## End(Not run)## Not run: # --- Single file --- temp <- tempfile(fileext = ".R") writeLines("mtcars |> dplyr::filter(cyl > 4)", temp) convert_pipe(temp, direction = "to_magrittr") readLines(temp) # "mtcars %>% dplyr::filter(cyl > 4)" # --- Entire package --- tmp_pkg <- tempdir() usethis::create_package(tmp_pkg, open = FALSE) writeLines("mtcars %>% dplyr::filter(cyl > 4)", file.path(tmp_pkg, "R/foo.R")) package_convert_pipe(tmp_pkg, direction = "to_base") readLines(file.path(tmp_pkg, "R/foo.R")) ## End(Not run)
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.
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, ... )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, ... )
path |
For For |
arg_pattern |
Regular expression matched (unanchored) against argument
names. Use e.g. |
allow |
Character vector of default-value expressions (as written in
the source, whitespace trimmed) that are acceptable.
Defaults to |
dirs |
Package-relative directories scanned by
|
verbose |
Whether to emit results to the console. |
... |
Unused. |
exports |
Character vector of exported function names. |
export_patterns |
Character vector of regular expressions, as in
|
Invisibly returns TRUE if no offending defaults are found,
FALSE otherwise.
detect_fn_arg_path()Operates on one R file. Use
exports / export_patterns to say which top-level functions
count as exported; when exports is NULL and no patterns are
given, every top-level function in the file is checked.
package_fn_arg_path()Checks that path is an R
package, reads exports from NAMESPACE, then scans .R files
under dirs (default "R").
file <- tempfile(fileext = ".R") writeLines('read_it <- function(path = "~/data.csv", n = 1) NULL', file) detect_fn_arg_path(file)file <- tempfile(fileext = ".R") writeLines('read_it <- function(path = "~/data.csv", n = 1) NULL', file) detect_fn_arg_path(file)
Transform function calls in R source code so that all arguments are passed with explicit parameter names.
The transformation is a minimal, position-based text edit: only the missing
argument = prefixes are inserted into the original source. Everything
else is preserved verbatim, including comments inside function bodies, blank
lines, indentation and operator spacing.
If the function has a ... formal, positional arguments that are
captured by ... are left in place as-is. Calls that forward
... literally (e.g. g(...)) are skipped, because the number of
arguments that ... expands to cannot be known statically.
Operators (+, -, *, /, etc.), subset operators
([, [[, $), assignment (<-, =,
<<-), and special syntax (if, for, while,
repeat, {, (, function) are not transformed.
package_func_arg_explicit(path = NULL, skip_functions = NULL, ...) make_func_arg_explicit(path = NULL, skip_functions = NULL, ...)package_func_arg_explicit(path = NULL, skip_functions = NULL, ...) make_func_arg_explicit(path = NULL, skip_functions = NULL, ...)
path |
Path to an R file to modify.
If |
skip_functions |
Optional character vector of function or operator names
to skip during transformation (e.g. |
... |
Additional arguments. Currently unused and must be empty. |
Invisible NULL, called for its side effect of writing the
transformed code back to the file.
package_func_arg_explicit(): Processes all .R files in a
package's R/ directory, making function arguments explicit.
The right-hand side of a pipe receives an extra argument from its
left-hand side, so that argument is counted during positional matching:
x %>% str_remove("a") becomes
x %>% str_remove(pattern = "a"), because the piped-in data already
fills the first formal (string).
Placeholders are honoured. When a native pipe (|>) uses the
_ placeholder, the piped value fills the formal named next to
_, so no leading argument is pre-claimed and the remaining
positional arguments are still matched:
x |> lm(y ~ z, data = _) becomes
x |> lm(formula = y ~ z, data = _). When a magrittr pipe
(%>%, %<>%, %T>%) contains . anywhere in
its right-hand side, the piped value is substituted at . instead of
being inserted as the first argument, and again no formal is pre-claimed:
x %>% f(., y) becomes x %>% f(a = ., b = y).
Operates on one R file. When path is NULL and RStudio is
available, the currently active document is used automatically.
tf <- tempfile(fileext = ".R") writeLines("vapply(1:9, function(x) x*2, numeric(1))", tf) make_func_arg_explicit(tf) cat(readLines(tf), sep = "\n") # vapply(X = 1:9, FUN = function(x) x*2, FUN.VALUE = numeric(length = 1))tf <- tempfile(fileext = ".R") writeLines("vapply(1:9, function(x) x*2, numeric(1))", tf) make_func_arg_explicit(tf) cat(readLines(tf), sep = "\n") # vapply(X = 1:9, FUN = function(x) x*2, FUN.VALUE = numeric(length = 1))
Add double colons (::) to function calls from specified packages to make
package dependencies explicit in R code.
package_func_call_explicit( path = NULL, use_packages = current_packages(), ignore_functions = c(imported_functions(path), get_defined_fn(path)), ... ) make_func_call_explicit( path = NULL, use_packages = current_packages(), ignore_functions = c(imported_functions(), get_defined_fn(path)), ... )package_func_call_explicit( path = NULL, use_packages = current_packages(), ignore_functions = c(imported_functions(path), get_defined_fn(path)), ... ) make_func_call_explicit( path = NULL, use_packages = current_packages(), ignore_functions = c(imported_functions(), get_defined_fn(path)), ... )
path |
A character string specifying the path to the R file to modify.
If |
use_packages |
A character vector of package names to process. Defaults to
|
ignore_functions |
A character vector of function names to ignore.
Defaults to |
... |
Additional arguments. Currently unused and must be empty. |
This function reads the specified R file, identifies function calls from the
specified packages, and adds explicit namespace qualifiers (::) to those
calls. Exported datasets from the same packages are qualified as well (e.g.
penguins becomes palmerpenguins::penguins). The modified code is written
back to the original file.
The file is tokenized in Rust, following R's lexical rules for strings, raw
strings, comments and backtick names. A name is qualified only when it is
actually a call or a dataset, so pkg::fun, obj$fun, obj@fun, function
definitions (fun <- function(...)), formal arguments and the identifiers
passed to data() are left untouched. In particular, l$select + 1 is not
rewritten even when dplyr::select is in use_packages.
This function replaces the add_double_colons() engine adapted from the
pedant package by Jacob Scott et al.,
licensed under MIT.
Invisibly TRUE when the file was read successfully; the file is modified in
place as a side effect.
package_func_call_explicit(): Processes all .R files in a
package's R/ directory, adding explicit namespace qualifiers.
file <- tempfile(fileext = ".R") writeLines(" starwars |> mutate(name, bmi = mass / ((height / 100)^2)) |> select(name:mass, bmi) ", file) make_func_call_explicit( path = file, use_packages = c("dplyr"), ignore_functions = c("library", "require") ) readLines(file) |> message()file <- tempfile(fileext = ".R") writeLines(" starwars |> mutate(name, bmi = mass / ((height / 100)^2)) |> select(name:mass, bmi) ", file) make_func_call_explicit( path = file, use_packages = c("dplyr"), ignore_functions = c("library", "require") ) readLines(file) |> message()
glue and cli ExpressionsCheck whether { and } are balanced in all glue() / glue_data()
and cli_*() string arguments within R source files. Each file is scanned
by a Rust tokenizer that understands strings, comments and raw strings, then
every string literal passed to a target function is checked with a
stack-based brace matcher. Any mismatch is reported with its line number and
a visual caret (^^^^) marker under the problematic region.
package_lost_glue_brace( path = NULL, dirs = c("R", file.path("tests", "testthat")), test_included = lifecycle::deprecated(), ... ) detect_lost_glue_brace(path = NULL, verbose = TRUE, ...)package_lost_glue_brace( path = NULL, dirs = c("R", file.path("tests", "testthat")), test_included = lifecycle::deprecated(), ... ) detect_lost_glue_brace(path = NULL, verbose = TRUE, ...)
Invisibly returns TRUE if all expressions are balanced,
FALSE otherwise.
detect_lost_glue_brace()Operates on one R file. When
path is NULL and RStudio is available, the currently active
document path is used.
package_lost_glue_brace()Scans .R files under the
configured package-relative directories. By default, these are R/
and tests/testthat/.
file <- tempfile(fileext = ".R") writeLines('glue("{a")', file) detect_lost_glue_brace(file)file <- tempfile(fileext = ".R") writeLines('glue("{a")', file) detect_lost_glue_brace(file)
Applies optimize_rmd_yaml() to README.Rmd and every .Rmd under
vignettes/, with a progress bar. See optimize_rmd_yaml() for the
compatibility rules and the meaning of the shared arguments.
package_optimize_rmd_yaml( path = NULL, readme = TRUE, vignettes = TRUE, readme_format = c("gfm", "github_document", "html"), date = c("auto", "desc", "none"), extra = NULL, extra_readme = NULL, extra_vignette = NULL )package_optimize_rmd_yaml( path = NULL, readme = TRUE, vignettes = TRUE, readme_format = c("gfm", "github_document", "html"), date = c("auto", "desc", "none"), extra = NULL, extra_readme = NULL, extra_vignette = NULL )
path |
Package root directory. |
readme |
Process README.Rmd? |
vignettes |
Process .Rmd files in vignettes/? |
readme_format |
Format used when a README has the default output: "gfm" (md_document + variant: gfm), "github_document" or "html". |
date |
"auto" -> |
extra |
Named list of extra YAML fields added to the file. It is merged
onto the built-in defaults with |
extra_readme, extra_vignette
|
Same as Extra fields never overwrite a key that already exists in the header;
they are only added when missing. A key that is also generated by default
(e.g. |
The paths of the files that were changed (invisibly).
## Not run: package_optimize_rmd_yaml() package_optimize_rmd_yaml(readme_format = "github_document", date = "desc") package_optimize_rmd_yaml( extra = list(lang = "zh-CN"), # merged with the defaults extra_readme = list(always_allow_html = NULL), # drop a README default extra_vignette = list( bibliography = "refs.bib", `link-citations` = TRUE, params = list(eval = FALSE) ) ) ## End(Not run)## Not run: package_optimize_rmd_yaml() package_optimize_rmd_yaml(readme_format = "github_document", date = "desc") package_optimize_rmd_yaml( extra = list(lang = "zh-CN"), # merged with the defaults extra_readme = list(always_allow_html = NULL), # drop a README default extra_vignette = list( bibliography = "refs.bib", `link-citations` = TRUE, params = list(eval = FALSE) ) ) ## End(Not run)
print() and cat() Calls (CRAN-Unsafe)Check whether R source files contain direct calls to print() or cat(),
which are generally not permitted by CRAN policies. Output should use
message instead.
These functions parse R source code into an AST and identify every
SYMBOL_FUNCTION_CALL token whose text is "print" or
"cat". Each match is reported with the line number, the full source
line, and a caret marker pointing at the offending call.
When fix = TRUE, the function performs a simple text replacement of
print( and cat( with message( on the affected lines.
The replacement uses word-boundary matching to avoid false positives inside
other identifiers (e.g. sprintf or print.myclass).
package_print_and_cat( path = NULL, dirs = c("R", file.path("tests", "testthat")), test_included = lifecycle::deprecated(), fix = FALSE, ... ) 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, ... )package_print_and_cat( path = NULL, dirs = c("R", file.path("tests", "testthat")), test_included = lifecycle::deprecated(), fix = FALSE, ... ) 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, ... )
Invisibly returns TRUE if no calls were found, FALSE
otherwise. Side-effect messages and caret markers are emitted via
cli and message.
detect_print_and_cat()Operates on one R file. When path
is NULL and RStudio is available, the currently active document is
used automatically.
package_print_and_cat()Scans all .R files in a
package's R/ directory, plus tests/testthat/ when
test_included = TRUE. Results are aggregated into a single report
showing per-file summaries.
# --- Single file --- tmp <- tempfile(fileext = ".R") writeLines('print("hello")', tmp) detect_print_and_cat(tmp) # --- With auto-fix --- detect_print_and_cat(tmp, fix = TRUE) # --- Entire package --- pkg <- tempfile() dir.create(file.path(pkg, "R"), recursive = TRUE) writeLines('cat("debug\\n")', file.path(pkg, "R", "example.R")) writeLines(c("Package: example", "Version: 0.0.1"), file.path(pkg, "DESCRIPTION")) package_print_and_cat(pkg)# --- Single file --- tmp <- tempfile(fileext = ".R") writeLines('print("hello")', tmp) detect_print_and_cat(tmp) # --- With auto-fix --- detect_print_and_cat(tmp, fix = TRUE) # --- Entire package --- pkg <- tempfile() dir.create(file.path(pkg, "R"), recursive = TRUE) writeLines('cat("debug\\n")', file.path(pkg, "R", "example.R")) writeLines(c("Package: example", "Version: 0.0.1"), file.path(pkg, "DESCRIPTION")) package_print_and_cat(pkg)
nocov MarkersCheck whether the nocov start and nocov end comment markers in R source
files are consistent.
Every marker is first located on its own line and column, and the markers are then checked against the rules below.
Detection is purely textual: every line is scanned for a marker comment, so a
marker that hides inside a string literal or inside a documentation comment
(a roxygen #' line) is reported as well. This is intentional – such a
marker has no effect on coverage, which usually means it is a leftover that
should be removed by hand.
package_unmatched_nocov_marker(path = NULL, dirs = "R", verbose = TRUE) detect_unmatched_nocov_marker(path = NULL, verbose = TRUE, ...)package_unmatched_nocov_marker(path = NULL, dirs = "R", verbose = TRUE) detect_unmatched_nocov_marker(path = NULL, verbose = TRUE, ...)
path |
For For |
dirs |
Character vector of package-relative directories scanned by
|
verbose |
Whether to emit detection results to the console. |
... |
Unused. |
Invisibly returns TRUE when the markers of the file follow the
rules above, and FALSE otherwise. Each problem is printed with its
line and column, the source line and a caret marker pointing at the
offending comment, so that the fix is left to the user.
A file may contain at most one nocov start and at most one
nocov end marker, so the two counts must be equal: either both are
present or neither is.
nocov start
Reported as a problem: only the first start is meaningful, so every further start is echoed with its line and column.
nocov end
Reported as a problem for the same reason.
nocov start without nocov end
Reported as a problem:
covr::package_coverage() aborts with a "range start but only range
ends" error when a start is never closed, so a lone start must be fixed.
nocov end without nocov start
Reported as a problem: the block it closes does not exist.
nocov end before nocov start
Reported as a problem: the end must come after the start. Markers are compared by line first and then by column, so an end placed later on the same line is accepted.
detect_unmatched_nocov_marker()Operates on one R file. When
path is NULL and RStudio is available, the currently active
document path is used.
package_unmatched_nocov_marker()Scans the .R files
under the configured package-relative directories, by default R/,
and reports every problem together with its file name and line number.
file <- tempfile(fileext = ".R") writeLines(c("f <- function() 1", paste0("# nocov", " end")), file) detect_unmatched_nocov_marker(file)file <- tempfile(fileext = ".R") writeLines(c("f <- function() 1", paste0("# nocov", " end")), file) detect_unmatched_nocov_marker(file)
Renames function definitions in an R file to follow a consistent naming
convention. Supports "snake_case", "camelCase", "PascalCase", and
"google" (dot-separated) naming styles. All references to the renamed
functions within the file are also updated.
rename_func( path = NULL, style = c("snake_case", "camelCase", "PascalCase", "google"), num_to_word = c(`for` = 4L, to = 2L), ... )rename_func( path = NULL, style = c("snake_case", "camelCase", "PascalCase", "google"), num_to_word = c(`for` = 4L, to = 2L), ... )
path |
A character string specifying the path to the R file to modify.
If |
style |
Naming convention to apply. One of:
|
num_to_word |
An optional named vector used to expand digit
abbreviations inside function names into words. Names give the replacement
word and values give the digit abbreviation, defaulting to
|
... |
Additional arguments. Currently unused and must be empty. |
Function definitions are identified using the pattern
name <- function(, name = function(, or the R 4.1+ shorthand
name <- \\( / name = \\(. Both the definition site and all
call sites / references within the file are updated. The conversion handles
mixed existing styles (snake_case, camelCase, PascalCase, dot.separated)
and normalizes function names to the target style.
Digit abbreviations are expanded into words before the target style is
applied, so list2env() becomes list_to_env() and wait4result() becomes
wait_for_result() under style = "snake_case". The expanded words are
formatted following style, e.g. list2env() becomes listToEnv() under
style = "camelCase" and ListToEnv() under style = "PascalCase". Only
digit runs that appear in num_to_word are expanded: an identifier that
contains an unmapped digit run (for example scale_x_log10()) is left
untouched.
Invisibly returns the path to the modified file.
temp <- tempfile(fileext = ".R") writeLines("foo_bar <- function(){message('foo_bar')}", temp) rename_func(temp, style = "camelCase") readLines(temp) rename_func(temp, style = "snake_case") readLines(temp) writeLines("list2env <- function(x) x", temp) rename_func(temp, style = "snake_case") readLines(temp) # "list_to_env <- function(x) x"temp <- tempfile(fileext = ".R") writeLines("foo_bar <- function(){message('foo_bar')}", temp) rename_func(temp, style = "camelCase") readLines(temp) rename_func(temp, style = "snake_case") readLines(temp) writeLines("list2env <- function(x) x", temp) rename_func(temp, style = "snake_case") readLines(temp) # "list_to_env <- function(x) x"
Render an R Markdown or R document to Markdown format
render_rmd(path = NULL, output_format = "md_document", ...)render_rmd(path = NULL, output_format = "md_document", ...)
path |
Path to the input file. If NULL and rstudioapi is available, uses the currently active document in RStudio. |
output_format |
Output format to render to. Defaults to "md_document". |
... |
Additional arguments passed to rmarkdown::render. |
The output file path from rmarkdown::render.
## Not run: rlang::check_installed("rmarkdown") tmp <- tempfile(fileext = ".Rmd") writeLines(c("---", "title: Test", "---", "", "Hello, world!"), tmp) render_rmd(path = tmp) ## End(Not run)## Not run: rlang::check_installed("rmarkdown") tmp <- tempfile(fileext = ".Rmd") writeLines(c("---", "title: Test", "---", "", "Hello, world!"), tmp) render_rmd(path = tmp) ## End(Not run)
Updates the last-updated field in the YAML header of standalone files
to today's date. Supports single file or batch update for all standalone
files in a directory.
update_time_in_standalone(path = NULL)update_time_in_standalone(path = NULL)
path |
Character. Path to a standalone file or a directory. If |
Invisibly returns a character vector of updated file paths.
update_time_in_standalone(tempdir())update_time_in_standalone(tempdir())
Air ( 0.8.0) can align the elements of a call column by column,
giving the same layout as tibble::tribble() or
data.table::fcase(). The feature is switched on by the experimental
# 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:
runs air format on path, so every long vector and list is
laid out with one element per line;
inserts the directive above every c() / list() call that
has more than min_length elements, and re-flows the elements so
that each row holds 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 air format run then pads the cells and aligns the columns.
use_air_table( path = NULL, ncol = 3L, min_length = 12L, marker = "# fmt: table", ... )use_air_table( path = NULL, ncol = 3L, min_length = 12L, marker = "# fmt: table", ... )
path |
Path to an R file to modify. If |
ncol |
Number of elements placed on each table row. |
min_length |
A vector or list is only converted when it has strictly more than this many elements. |
marker |
The comment directive that enables table formatting in air. |
... |
Additional arguments. Currently unused and must be empty. |
Requirements and scope:
air must be installed and on the 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 (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 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
x <- list(a = c(...))) is skipped.
Invisibly returns the normalized path.
## Not run: 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() ## End(Not run)## Not run: 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() ## End(Not run)
BugReports field to a package's DESCRIPTION
Sets the BugReports field of a package's DESCRIPTION file. By default,
the GitHub issues page URL is derived from the configured git remote
(origin).
Requires that the target directory is an R package root (contains a
DESCRIPTION file).
Both https:// and git@ style remotes are supported (see use_url()).
use_bugreports(url = NULL, path = NULL, ...)use_bugreports(url = NULL, path = NULL, ...)
url |
Character. The bug reports URL (usually the GitHub issues
page). If |
path |
Path to the package root. If |
... |
Must be empty. Reserved for future arguments. |
Invisibly returns the URL that was written.
## Not run: tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_bugreports( url = "https://github.com/WangLabCSU/rpkgkit/issues", path = tmpdir ) ## End(Not run)## Not run: tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_bugreports( url = "https://github.com/WangLabCSU/rpkgkit/issues", path = tmpdir ) ## End(Not run)
.clangd configuration fileWrites a .clangd configuration file at path with CompileFlags set to
include headers from the system R installation and from common C++ interface
packages (Rcpp, RcppEigen, RcppArmadillo). If path is the root of an
R package (contains a DESCRIPTION file), an additional If: block is
appended that disables background indexing for the R/ source directory,
since it only contains R code, not C++ source. In that case .clangd is
also added to .Rbuildignore (inside a scoped project, so the active
project of the calling session is restored afterwards).
.clangd is the configuration file read by the clangd language server.
It is typically placed in the project root.
The system R include directory is obtained via base::R.home() with
component "include".
Package include directories are obtained via base::system.file() with
package = <pkg>.
Packages that are not installed (or that have no include/ directory)
are skipped with a cli::cli_warn() warning.
use_clangd( path = NULL, include = c("Rcpp", "RcppEigen", "RcppArmadillo"), overwrite = FALSE, open = rlang::is_interactive(), ... )use_clangd( path = NULL, include = c("Rcpp", "RcppEigen", "RcppArmadillo"), overwrite = FALSE, open = rlang::is_interactive(), ... )
path |
Character. Path to the directory where |
include |
Character vector of package names whose |
overwrite |
Logical. If |
open |
Logical. Whether to open the created file in the editor.
Defaults to |
... |
Must be empty. Reserved for future arguments. |
Invisibly returns the path to the created .clangd file.
tmp <- tempdir() use_clangd(path = tmp) # Custom include library names use_clangd( path = tmp, include = c("Rcpp", "BH"), overwrite = TRUE )tmp <- tempdir() use_clangd(path = tmp) # Custom include library names use_clangd( path = tmp, include = c("Rcpp", "BH"), overwrite = TRUE )
Adds a hex sticker image (optionally wrapped in a hyperlink) at the end of
the top-level heading (the line starting with
# ) in README.md.
This is a common pattern for R package README files.
use_hexsticker( img_path, url = NULL, alt_text = "package logo", height = 139L, align = "right", path = NULL, ... )use_hexsticker( img_path, url = NULL, alt_text = "package logo", height = 139L, align = "right", path = NULL, ... )
img_path |
Character. Path to the image file (e.g.,
|
url |
Character. URL the image should link to. If |
alt_text |
Character. Alt text for the image. Defaults to
|
height |
Numeric or character. Image height in pixels. Defaults to
|
align |
Character. Image alignment attribute. Defaults to |
path |
Character. Path to the package root directory. If |
... |
Additional HTML attributes to include in the |
Invisibly returns TRUE on success.
## Not run: temp <- tempdir() usethis::create_package(path = temp) writeLines("# Package Name", file.path(temp, "README.md")) file.create(file.path(temp, "logo.png")) use_hexsticker(file.path(temp, "logo.png"), url = "https://my-pkg-website.com", path = temp) ## End(Not run)## Not run: temp <- tempdir() usethis::create_package(path = temp) writeLines("# Package Name", file.path(temp, "README.md")) file.create(file.path(temp, "logo.png")) use_hexsticker(file.path(temp, "logo.png"), url = "https://my-pkg-website.com", path = temp) ## End(Not run)
jarl.toml configuration fileWrites a jarl.toml configuration file for jarl,
the R linter written in Rust. The file pins down the linting behaviour of
every jarl invocation in the project, so the command line, the editor
integration and the continuous integration workflow all agree.
jarl.toml is looked up by jarl in the current working directory, then in
its parent directories, and finally in the user configuration directory.
jarl reads a single configuration file, the closest one wins.
All lint options live in the [lint] table. Command line flags always take
precedence over the file.
[lint.per-file-ignores] must come last in the file, otherwise the options
written after it are parsed as glob patterns; the generated file does not
use that table.
When path is the root of an R package (contains a DESCRIPTION file),
jarl.toml is also added to .Rbuildignore (inside a scoped project, so the
active project of the calling session is restored afterwards).
Read the
configuration reference
for the full list of options, and the
continuous integration guide
to run jarl on every push with the etiennebacher/setup-jarl action.
use_jarl(path = NULL, overwrite = FALSE, ...)use_jarl(path = NULL, overwrite = FALSE, ...)
path |
Character. Path to the directory where |
overwrite |
Logical. If |
... |
Must be empty. Reserved for future arguments. |
Invisibly returns the path to the created jarl.toml file.
tmp <- tempdir() use_jarl(path = tmp, overwrite = TRUE) readLines(file.path(tmp, "jarl.toml"))tmp <- tempdir() use_jarl(path = tmp, overwrite = TRUE) readLines(file.path(tmp, "jarl.toml"))
Creates translated README files under inst/ for a target R package and
prints badges that can be pasted into the main README.md to link to each
translation.
The five non-English United Nations official languages are used by
default: Chinese (zh-cn), Spanish (es), French (fr),
Arabic (ar), and Russian (ru). Any language code (including
non-UN languages) can be supplied via the lang argument.
use_multilanguage_readme( lang = c("zh-cn", "es", "fr", "ar", "ru"), color = "blue", ..., path = NULL, overwrite = FALSE )use_multilanguage_readme( lang = c("zh-cn", "es", "fr", "ar", "ru"), color = "blue", ..., path = NULL, overwrite = FALSE )
lang |
Character vector of language codes (e.g. |
color |
Color of badge. Defaults to |
... |
Not used. |
path |
Character. Path to the package root directory. If |
overwrite |
Logical. If |
Invisibly returns a character vector of paths to the created files.
The following codes have built-in display name mappings:
| Code | Display Name |
en |
English |
zh-cn |
Chinese (Simplified) |
zh-tw |
Chinese (Traditional) |
es |
Spanish |
fr |
French |
de |
German |
pt |
Portuguese |
ja |
Japanese |
ko |
Korean |
ar |
Arabic |
ru |
Russian |
it |
Italian |
nl |
Dutch |
pl |
Polish |
tr |
Turkish |
vi |
Vietnamese |
th |
Thai |
id |
Indonesian |
hi |
Hindi |
Unrecognised codes are used verbatim as badge labels.
## Not run: dir <- tempdir() usethis::create_package(dir) use_multilanguage_readme(path = dir) # Custom languages use_multilanguage_readme(c("de", "ja", "ko"), path = dir) ## End(Not run)## Not run: dir <- tempdir() usethis::create_package(dir) use_multilanguage_readme(path = dir) # Custom languages use_multilanguage_readme(c("de", "ja", "ko"), path = dir) ## End(Not run)
R version a package needsuse_r() scans the package sources for base R functions and syntax introduced
in recent R versions, then records the highest version it finds in the
Depends field of DESCRIPTION with usethis::use_package().
use_r_v4.1.0() is a shortcut that always requires R (>= 4.1.0), the
version that introduced \() and |>.
use_r() detects:
R (>= 4.1.0): |>, \(), isa().
R (>= 4.2.0): the _ pipe placeholder in a named argument,
Sys.setLanguage().
R (>= 4.3.0): the _ pipe placeholder heading an extraction chain.
R (>= 4.4.0): %||%, sort_by(), Tailcall(), Exec().
R (>= 4.5.0): use(), grepv(), the penguins dataset.
R (>= 4.6.0): %notin%, messageCondition(),
match.arg(several.ok = "all"), barplot(orderH =).
Names that the package defines itself, such as its own %||%, never raise
the requirement: they are reported and ignored. |>, \() and the _
placeholder are syntax rather than names, so they always count. A
DESCRIPTION that already requires a higher version is never downgraded.
use_r_v4.1.0(path = NULL, ...) use_r(path = NULL, dirs = c("R", file.path("tests", "testthat")), ...)use_r_v4.1.0(path = NULL, ...) use_r(path = NULL, dirs = c("R", file.path("tests", "testthat")), ...)
path |
Path to the package root. If |
... |
Must be empty. Reserved for future arguments. |
dirs |
Package-relative directories scanned by |
use_r() invisibly returns the detected minimum R version, or
NULL when nothing requires a recent R. use_r_v4.1.0() invisibly returns
NULL, called for side effects.
## Not run: tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_r_v4.1.0(path = tmpdir) use_r(path = tmpdir) ## End(Not run)## Not run: tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_r_v4.1.0(path = tmpdir) use_r(path = tmpdir) ## End(Not run)
use_tidy_addin() writes an entry into inst/rstudio/addins.dcf, which
makes an exported function available from the RStudio Addins menu.
use_tidy_addin(fn_name, desc, Interactive = FALSE, path = NULL)use_tidy_addin(fn_name, desc, Interactive = FALSE, path = NULL)
fn_name |
Name of the function (it must already be exported in
|
desc |
Description of the addin. |
Interactive |
Whether this is an interactive addin (maps to the
|
path |
Root directory of the R package. |
Invisibly, the path of the dcf file that was written (NULL if the
operation was cancelled).
## Not run: # Inside a package that exports `my_addin()` use_tidy_addin("my_addin", "Open my Shiny gadget", Interactive = TRUE) ## End(Not run)## Not run: # Inside a package that exports `my_addin()` use_tidy_addin("my_addin", "Open my Shiny gadget", Interactive = TRUE) ## End(Not run)
URL field to a package's DESCRIPTION
Sets the URL field of a package's DESCRIPTION file. By default, the
GitHub repository URL is detected from the configured git remote
(origin). An additional pkgdown website URL can optionally be appended.
Requires that the target directory is an R package root (contains a
DESCRIPTION file).
Both https:// and git@ style remotes are converted to a browser
URL (a trailing .git suffix is removed).
use_url(url = NULL, pkgdown_url = NULL, path = NULL, ...)use_url(url = NULL, pkgdown_url = NULL, path = NULL, ...)
url |
Character. The primary URL (usually the GitHub repository).
If |
pkgdown_url |
Character. An optional pkgdown website URL, appended
after |
path |
Path to the package root. If |
... |
Must be empty. Reserved for future arguments. |
Invisibly returns the URLs that were written.
## Not run: tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_url( url = "https://github.com/WangLabCSU/rpkgkit", pkgdown_url = "https://wanglabcsu.github.io/rpkgkit/", path = tmpdir ) ## End(Not run)## Not run: tmpdir <- tempdir() usethis::create_package(path = tmpdir) use_url( url = "https://github.com/WangLabCSU/rpkgkit", pkgdown_url = "https://wanglabcsu.github.io/rpkgkit/", path = tmpdir ) ## End(Not run)
Reference a permissively-licensed R package from GitHub for inclusion in your own R package. This function:
Creates inst/vendor/pkg/ with LICENSE files and a README
Creates R/vendor-pkg.R with attribution header and optional vendored code
Creates src/vendor-pkg.c, src/vendor-pkg.cpp or
src/rust/src/vendor-pkg.rs for vendored C, C++ or Rust sources
Updates DESCRIPTION (Authors@R and Copyright fields)
Prints an acknowledgement snippet for your README
use_vendor(pkg, ..., branch = "main", path = NULL)use_vendor(pkg, ..., branch = "main", path = NULL)
pkg |
GitHub repository specification in |
... |
File paths within the vendor package to copy into your package.
Files are routed by extension: |
branch |
Github repository branch name. Defaults to |
path |
Path to the target package directory. If |
Invisibly returns NULL, called for side effects.
## Not run: use_vendor("hadley/emo", "R/zzz.R") # C++ and Rust sources are routed to src/ and src/rust/src/ use_vendor("wurli/pedant", "R/utils.R", "src/foo.cpp", "src/lib.rs") ## End(Not run)## Not run: use_vendor("hadley/emo", "R/zzz.R") # C++ and Rust sources are routed to src/ and src/rust/src/ use_vendor("wurli/pedant", "R/utils.R", "src/foo.cpp", "src/lib.rs") ## End(Not run)
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).
use_workflow_rust_compatible_check(path = NULL, overwrite = FALSE)use_workflow_rust_compatible_check(path = NULL, overwrite = FALSE)
path |
Character. Path to the package root directory. If |
overwrite |
Logical. If |
Invisibly returns the path to the created workflow file.
usethis workflowusethis::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.
## Not run: temp <- tempdir() usethis::create_package(temp) use_workflow_rust_compatible_check(temp) use_workflow_rust_compatible_check(temp, overwrite = TRUE) ## End(Not run)## Not run: temp <- tempdir() usethis::create_package(temp) use_workflow_rust_compatible_check(temp) use_workflow_rust_compatible_check(temp, overwrite = TRUE) ## End(Not run)
Copies the built-in sync_test_branch.yml workflow template and the
corresponding sync-test-branch composite action to the target package's
.github/ directory. The workflow runs only after R-CMD-check.yaml
successfully completes for a push to main/master, then force-pushes the
checked commit onto the test branch.
Safety mechanism: If the test branch contains commits that are not
reachable from main (i.e., unmerged work-in-progress), the sync is
skipped to avoid overwriting unmerged changes.
This enables convenient isolated debugging: work on the test branch,
push experimental changes, and each push to main will reset test
to match main (as long as no unmerged work exists on test).
use_workflow_test_branch(path = NULL, overwrite = FALSE)use_workflow_test_branch(path = NULL, overwrite = FALSE)
path |
Character. Path to the package root directory. If |
overwrite |
Logical. If |
Invisibly returns the path to the created workflow file.
## Not run: temp <- tempdir() usethis::create_package(temp) use_workflow_test_branch(temp) use_workflow_test_branch(temp, overwrite = TRUE) ## End(Not run)## Not run: temp <- tempdir() usethis::create_package(temp) use_workflow_test_branch(temp) use_workflow_test_branch(temp, overwrite = TRUE) ## End(Not run)
Copies the built-in version_update.yml workflow template to the target
package's .github/workflows/ directory. The workflow automatically bumps
the R package version based on commit messages, or manually via
workflow_dispatch with a specified version type.
Version bump rules (from commit messages, case-insensitive):
major / breaking - increments the major version (X.0.0)
feat / feature / minor - increments the minor version (x.Y.0)
patch / fix / bug - increments the patch version (x.y.Z)
Otherwise, no version bump occurs
The workflow_dispatch input always overrides commit message detection.
use_workflow_version_update( path = NULL, overwrite = FALSE, color = "blue", ... )use_workflow_version_update( path = NULL, overwrite = FALSE, color = "blue", ... )
path |
Character. Path to the package root directory. If |
overwrite |
Logical. If |
color |
badge color |
... |
pass to |
Invisibly returns the path to the created workflow file.
Before writing anything, the action compares the version it is about to set
with the highest version documented in NEWS.md (heading lines such as
# pkg 1.2.3 (2026-01-01)). The bump is skipped when the new version is
greater than that maximum, so that no release is shipped without a matching
NEWS.md entry. When NEWS.md is missing or holds no version heading, the
check is bypassed with a warning.
When the package ships Rust code, the action also reads the version key of
the [package] table in src/rust/Cargo.toml and rewrites it to the new
version. The rest of the manifest is left untouched and the same NEWS.md
guard applies, so the crate version never exceeds the highest version
documented in NEWS.md. The file is skipped when it is absent or declares no
literal version (for example version.workspace = true).
## Not run: temp <- tempdir() usethis::create_package(temp) use_workflow_version_update(temp) use_workflow_version_update(temp, overwrite = TRUE) ## End(Not run)## Not run: temp <- tempdir() usethis::create_package(temp) use_workflow_version_update(temp) use_workflow_version_update(temp, overwrite = TRUE) ## End(Not run)
Copies the built-in zzz_template.R to the target package's R/ directory
and replaces template placeholders (all-caps words) with values from the
package DESCRIPTION file.
Template placeholders replaced:
PKG — package name
PKG-package — {pkgname}-package
TITLE — package title
DESCRIPTION — package description (multiline values get #' prefix)
LICENSE — license type
Other information:
.onLoad and .onAttach is added to the file.
usethis namespace is added to the file.
use_zzz( path = NULL, file_name = NULL, overwrite = FALSE, open = rlang::is_interactive(), ... )use_zzz( path = NULL, file_name = NULL, overwrite = FALSE, open = rlang::is_interactive(), ... )
path |
Character. Path to the package root directory. If |
file_name |
Character. Output file name. Defaults to |
overwrite |
Logical. If |
open |
Logical. Whether to open the created file in the default editor. |
... |
Not used. |
Invisibly returns the path to the created file.
## Not run: dir <- tempdir() usethis::create_package(dir) use_zzz(dir) ## End(Not run)## Not run: dir <- tempdir() usethis::create_package(dir) use_zzz(dir) ## End(Not run)