Package 'rpkgkit'

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

Help Index


Unpack values into multiple variables

Description

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.

Usage

lhs %<-% rhs

Arguments

lhs

A destructuring target composed of variable names, nested base::c() calls, named missing arguments for name-based extraction, and optional . or ⁠_⁠ placeholders. A single ..name collector may appear anywhere among positional targets; .. is an anonymous collector that discards its matched elements.

rhs

A list, atomic vector, or data frame whose elements are assigned.

Value

The value of rhs, returned invisibly.

Examples

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")

Add or update a changelog entry in a standalone R file

Description

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.

Usage

add_changelog_in_standalone(path = NULL, description = NULL, date = NULL)

Arguments

path

Character. Path to a standalone file, a directory, or NULL. If NULL and rstudioapi is available, uses the currently active document. If a directory, searches for standalone files matching the pattern.

description

Character. Description of the changelog entry. If NULL, an interactive prompt is used (not yet implemented).

date

Character. Date string in YYYY-MM-DD format. Defaults to today.

Value

Invisibly returns the path to the updated file.

Examples

add_changelog_in_standalone(tempdir(), "Added new feature")

Make function calls explicit

Description

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.

Usage

add_double_colons(
  code = NULL,
  use_packages = current_packages(),
  ignore_functions = imported_functions()
)

Arguments

code

Code to transform. Either a character vector or NULL, in which case any highlighted code (in RStudio) will be used.

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

Details

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.

Value

The transformed code as a character string

Examples

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")))

Add .gitignore to package

Description

Adds a global .gitgnore file to the package. File based on default .gitignore provided by GitHub.

Usage

add_global_gitgnore(pkg = NULL)

Arguments

pkg

The package to add the .gitignore file to. Defaults to the current working directory.

Value

Invisible, and writes a global .gitignore file

See Also

usethis::use_git_ignore(), usethis::git_vaccinate()

Examples

## Not run: 
add_global_gitgnore()

## End(Not run)

Add global .Rbuildignore patterns

Description

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.

Usage

add_global_rbuildignore(
  ...,
  pattern = GLOBAL_RBUILDIGNORE_PATTERN,
  replace_default = FALSE,
  path = NULL
)

Arguments

...

Additional regex patterns (character strings) to add beyond the selected patterns. Each must already be in .Rbuildignore regex format (e.g. "^\\.myfile$").

pattern

Character vector of .Rbuildignore patterns.

replace_default

Logical. If FALSE (the default), pattern is appended to default setting. If TRUE, pattern is used instead of the defaults.

path

Character. Path to the package root directory. If NULL (the default), uses the current working directory.

Value

Invisibly returns the path to .Rbuildignore.

Examples

## 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)

[Deprecated] Format R code using air

Description

[Deprecated] Format R code using air

Usage

air_format(path = NULL, ...)

Arguments

path

Path to the R file to format. If NULL, attempts to use the active document in RStudio (requires rstudioapi package).

...

Additional arguments passed to system2().

Details

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⁠

Value

The exit status of the ⁠air format⁠ command (invisibly).

Examples

## Not run: 
air_format(system.file("R_template/zzz_template.R", package = "rpkgkit"))

## End(Not run)

Insert a badge into README badges block

Description

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.

Usage

badge_to_readme(badge, path = NULL, ...)

Arguments

badge

Character. Badge markdown, e.g. the output of badger::badge_code_size().

path

Character. Path to the package root. If NULL (the default), uses the current working directory.

...

Not used.

Value

Invisibly returns the path to the modified README file.

Examples

## 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)

Generate AI Translation Disclaimer Badge

Description

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: ⁠[![AI|<LANG>](https://img.shields.io/badge/AI-<LANG>-yellow)]()⁠

  • A blockquote with the full disclaimer text in that language

Usage

badge_translated_by_ai(lang = "en", color = "yellow")

Arguments

lang

Character vector of language codes (e.g. "zh-cn", "ja"). Defaults to NULL, which outputs disclaimers for all 19 supported languages. Pass a single code to get one entry only.

color

Color of badge. Defaults to "yellow"

Value

Invisibly returns a named list of character vectors, where each element contains the badge line and blockquote note for one language.

Examples

## 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)

Browse Standalone R Files Across GitHub

Description

Search GitHub for all ⁠standalone-*.R⁠ files and return the file and repository metadata of the matches as a tibble.

Usage

browse_standalone(per_page = 100L, limit = 200L, ..., token = NULL)

Arguments

per_page

Number of items to request per page, between 1 and 100. Defaults to 100L, the largest page GitHub serves.

limit

Number of records to return. Defaults to 200L; use Inf to request every record GitHub exposes. Each page of per_page records costs one search request, so a large limit can take a while.

...

No arguments.

token

A GitHub personal access token. When NULL (the default) the token is read from the GITHUB_PAT or GITHUB_TOKEN environment variable; without a token GitHub only allows 60 requests per hour.

Details

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.

Value

A tibble with columns:

repo

Character. Repository identifier in "owner/repo" format.

name

Character. File name (e.g. "standalone-utils.R").

path

Character. File path within the repository (e.g. "R/standalone-utils.R").

sha

Character. File SHA.

url

Character. GitHub API URL for the file.

html_url

Character. GitHub HTML URL for the file.

git_url

Character. Git blob URL for the file.

repo_url

Character. Repository URL on GitHub.

repo_description

Character. Repository description from GitHub.

Note

Without a token GitHub applies strict rate limits (60 requests per hour). Set GITHUB_PAT in ~/.Renviron to lift them.

Examples

## Not run: 
  browse_standalone()

## End(Not run)

Check that the air formatter is installed

Description

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.

Usage

check_air_installed()

Details

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⁠

Value

Invisibly returns TRUE if air is found.


Check that all exported functions are listed in pkgdown reference

Description

Parses the NAMESPACE and ⁠_pkgdown.yml⁠ (if present) and reports any exported functions that are missing from the pkgdown reference index.

Usage

check_pkgdown_reference(pkg = ".")

Arguments

pkg

Character. Path to the package root directory. Defaults to the current RStudio project or ".".

Value

Invisibly returns a character vector of missing function names, or NULL if ⁠_pkgdown.yml⁠ does not exist. Prints a summary via cli.

Examples

## Not run: 
dir <- tempdir()
usethis::create_package(dir)
usethis::proj_set(dir)
usethis::use_pkgdown()
check_pkgdown_reference(dir)

## End(Not run)

Check the format of a custom standalone file

Description

Checks a standalone file against the layout used by r-lib/rlang (as consumed by usethis::use_standalone()). Three points are checked:

  1. the header format, and whether each slot has a value;

  2. every documented function carries ⁠@noRd⁠ (undocumented functions are skipped);

  3. a ⁠# nocov start⁠ marker exists and precedes all functions (⁠# nocov end⁠ is optional).

Usage

check_standalone(path = NULL, ...)

Arguments

path

Path to the standalone file (a single string).

...

Unused

Details

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().

Value

Invisibly, list(error = , warning = , note = ), where each element is an integer.

Examples

## Not run: 
check_standalone("R/standalone-purrr.R")

## End(Not run)

Check whether system development dependencies are installed

Description

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).

Usage

check_sysdeps(deps = NULL, manager = NULL, verbose = TRUE)

Arguments

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 "a|b": the dependency counts as installed if any alternative is installed, and the first one is used in the install hint. If NULL, a built-in list of graphics, font and GLPK development libraries is used. There is no built-in list for "winget", "choco" and "scoop", so deps must be supplied for them.

manager

The package manager: one of "dpkg", "rpm", "pacman", "apk", "brew", "winget", "choco", or "scoop". If NULL, it is detected automatically (on Linux via ⁠/etc/os-release⁠, falling back to whichever manager is on the PATH).

verbose

Logical. If TRUE (the default), print the check results. If FALSE, no messages are printed.

Value

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).

Examples

# `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]
}

Switch Between Explicit ⁠function()⁠ and Implicit ⁠\()⁠ Syntax

Description

Converts 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.

Usage

convert_func_syntax(
  path = NULL,
  direction = c("to_lambda", "to_explicit"),
  ...
)

Arguments

path

A character string specifying the path to the R file to modify. If NULL and RStudio is available, the currently active document path is used.

direction

Conversion direction. One of:

  • "to_lambda": convert ⁠function(...)⁠ to ⁠\(...)⁠

  • "to_explicit": convert ⁠\(...)⁠ to ⁠function(...)⁠

...

Additional arguments. Currently unused and must be empty.

Details

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.

Value

Invisibly returns the path to the modified file.

Examples

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"

Convert Knitr Chunk Headers in R Markdown Files

Description

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.

Usage

convert_knitr_chunk_header(path = NULL, ...)

Arguments

path

Path to an R package root directory or an R Markdown file. If NULL (the default), the current working directory is used.

...

Additional arguments passed to knitr::convert_chunk_header().

Value

Invisibly returns a character vector of file paths that were converted.

Examples

tmp <- tempfile(fileext = ".Rmd")
writeLines(c("```{r, echo=TRUE, fig.width=10}", "x <- 1", "```"), tmp)
convert_knitr_chunk_header(tmp)
readLines(tmp)

Convert Non-ASCII Code

Description

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).

Usage

convert_nonascii_code(code, ..., reverse = FALSE, overwrite = NULL)

Arguments

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 TRUE, converts ⁠\uXXXX⁠ escape sequences back to readable Unicode characters. If FALSE (default), encodes non-ASCII characters to ⁠\uXXXX⁠ escapes.

overwrite

Logical. Only used when code is a file path. If TRUE, overwrites the file with the converted content. Default is NULL, which prompts the user interactively.

Value

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.

Examples

# 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)

Creates a new standalone R script with YAML metadata header. If path is an R package, the file is created in the ⁠R/⁠ subdirectory.

Description

Creates a new standalone R script with YAML metadata header. If path is an R package, the file is created in the ⁠R/⁠ subdirectory.

Usage

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(),
  ...
)

Arguments

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:

  • license: Character. License URL or identifier. Defaults to "https://unlicense.org".

  • imports: Character vector. Package dependencies to import. Defaults to NULL.

  • dependency: Character vector. Hard dependencies for the standalone file. Defaults to NULL.

  • description: Character. A short description of the standalone file. Defaults to "To be filled.".

open

Logical. Whether to open the file in RStudio editor. Defaults to TRUE.

...

Additional arguments (must be empty).

Value

Invisibly returns the path to the created file.

Examples

create_standalone("my_utils", path = tempdir())

Fix R code or package using flir

Description

Automatically detect the type of path (file, package, or directory) and apply the appropriate flir fix function.

Usage

flir_fix(path = NULL, ...)

Arguments

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.

Details

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()

Value

Invisibly returns the result from the called flir function.

Examples

## 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

Description

Get the version of the Positron IDE

Usage

get_positron_version(long = FALSE)

Arguments

long

Whether to return the full version including the build number (e.g. "2025.01.0-123"). Defaults to FALSE.

Value

A character string with the version number, or NA_character_ if not running inside Positron and the version cannot be located.


Trace and compute the value of a variable defined inside a function

Description

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.

Usage

get_var_value(var_name, func, .env = rlang::current_env())

Arguments

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. runif from the stats package). Defaults to the caller's environment (rlang::current_env()), which is typically .GlobalEnv and has access to all attached packages.

Value

The computed value of the variable.

Examples

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 16

Inquire Standalone Files from a GitHub Repository

Description

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.

Usage

inquire_standalone(owner, repo, ..., token = NULL)

Arguments

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 NULL (the default) the token is read from the GITHUB_PAT or GITHUB_TOKEN environment variable; without a token GitHub only allows 60 requests per hour.

Details

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.

Value

A tibble with one row per standalone file:

name, path, sha, size, url, html_url, git_url, download_url, type

The fields of the GitHub contents API entry of the file.

repo

Character string, the repository identifier in "owner/repo" format.

description

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.

usage

Character string, the code to import the standalone file using usethis::use_standalone().

Examples

## Not run: 
inquire_standalone("r-lib", "rlang")

## End(Not run)

Get packages from the current context

Description

These functions find the packages/functions to use when running add_double_colons().

Usage

is_dev_context(dir = ".")

imported_functions(dir = ".")

current_packages(
  dir = ".",
  base_packages = getOption("defaultPackages"),
  include_types = "Imports"
)

Arguments

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 c("Imports", "Depends", "Suggests", "Enhances", "LinkingTo")

Details

  • 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.

Value

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.


Manage NEWS.md file for R packages

Description

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.

[Deprecated] 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.

Usage

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
)

Arguments

path

Path to the package root. If NULL (the default), uses the current working directory.

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.

Details

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

Value

A list with components:

valid

Logical indicating if NEWS.md passes all checks.

errors

Character vector of error messages.

warnings

Character vector of warning messages.

suggestions

Character vector of improvement suggestions.

Invisibly returns the content as a character vector.

Invisibly returns the path to the NEWS.md file.

Examples

## 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)

Open the CFF initializer

Description

Opens the CFF (Citation File Format) initializer web application in the default browser.

Usage

open_cffinit(...)

Arguments

...

Unused arguments, for future extensibility.

Value

Invisible TRUE, called for side effects.

See Also

browseURL()


Enrich the YAML header of ONE Rmd file using the package DESCRIPTION

Description

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.

Usage

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
)

Arguments

path

Path to an Rmd file. If NULL, the file open in the active RStudio editor is used.

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" -> Sys.Date(); "desc" -> DESCRIPTION Date field; "none" -> do not add a date.

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 merged recursively, your values win). Built-in default: RStudio editor_options (markdown: wrap: sentence, chunk_output_type: console). To drop a default, set it to NULL, e.g. list(editor_options = NULL).

extra_readme, extra_vignette

Same as extra, but only applied when the file is a README / a vignette. Merge order (later wins): built-in defaults -> extra -> extra_readme / extra_vignette. Built-in README default: always_allow_html: true.

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. lang, date, author) replaces the generated value.

Details

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.

Value

TRUE if the file was changed, FALSE otherwise (invisibly).

Examples

## 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)

Add Explicit Integer Suffix L to Integer Literals

Description

Converts 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).

Usage

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, ...)

Arguments

path

For convert_int_literals(), a character string specifying the R file to modify. If NULL and RStudio is available, the currently active document path is used.

For package_convert_int_literals(), a character string specifying the package root. If NULL, the current working directory is used.

dirs

Character vector of subdirectories relative to path to search. Used only by package_convert_int_literals(). Defaults to c("R").

recursive

Logical; recurse into subdirectories. Used only by package_convert_int_literals(). Default TRUE.

exclude

Character vector of file names to skip, matched case-insensitively against the file base name. Used only by package_convert_int_literals(). Defaults to the auto-generated wrapper files c("RcppExports.R", "extendr-wrappers.R"). Use NULL (or character()) to process all files.

...

Additional arguments. Currently unused and must be empty.

verbose

Logical; enable or disable per-file messages. Used only by convert_int_literals(). Default TRUE.

Details

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._⁠).

Value

convert_int_literals() invisibly returns the modified file path. package_convert_int_literals() invisibly returns a character vector of modified file paths.

Opting a line out

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.

Examples

## 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)

Switch Between the Tidyverse Pipe ⁠%>%⁠ and the Base Pipe ⁠|>⁠

Description

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.

Usage

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,
  ...
)

Arguments

path

For convert_pipe(), a character string specifying the R file to modify. If NULL and RStudio is available, the currently active document path is used.

For package_convert_pipe(), a character string specifying the package root. If NULL, the current working directory is used.

direction

Conversion direction. One of:

  • "to_base": convert ⁠%>%⁠ to ⁠|>⁠

  • "to_magrittr": convert ⁠|>⁠ to ⁠%>%⁠

dirs

Character vector of subdirectories relative to path to search. Used only by package_convert_pipe(). Defaults to c("R").

recursive

Logical; recurse into subdirectories. Used only by package_convert_pipe(). Default TRUE.

...

Additional arguments. Currently unused and must be empty.

verbose

Logical; enable or disable per-file messages. Used only by convert_pipe(). Default TRUE.

Details

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.

Value

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

Examples

## 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)

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.

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

path

For detect_fn_arg_path(): path to an R file. If NULL and RStudio is available, the active document is used.

For package_fn_arg_path(): root directory of an R package. Defaults to the current directory.

arg_pattern

Regular expression matched (unanchored) against argument names. Use e.g. "^(path|file|filename)$" to avoid matching profile.

allow

Character vector of default-value expressions (as written in the source, whitespace trimmed) that are acceptable. Defaults to "NULL".

dirs

Package-relative directories scanned by package_fn_arg_path().

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 exportPattern() in NAMESPACE.

Value

Invisibly returns TRUE if no offending defaults are found, FALSE otherwise.

Single file vs package scope

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").

Examples

file <- tempfile(fileext = ".R")
writeLines('read_it <- function(path = "~/data.csv", n = 1) NULL', file)
detect_fn_arg_path(file)

Make Function Arguments Explicit

Description

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.

Usage

package_func_arg_explicit(path = NULL, skip_functions = NULL, ...)

make_func_arg_explicit(path = NULL, skip_functions = NULL, ...)

Arguments

path

Path to an R file to modify. If NULL and RStudio is available, the active document path is used.

skip_functions

Optional character vector of function or operator names to skip during transformation (e.g. c("my_special_fn")). In addition to user-provided names, all built-in operators (+, -, etc.), special syntax forms (if, for, {, etc.), and all %...% infix operators (%in%, %>%, %||%, etc.) are always skipped automatically.

...

Additional arguments. Currently unused and must be empty.

Value

Invisible NULL, called for its side effect of writing the transformed code back to the file.

Functions

  • package_func_arg_explicit(): Processes all .R files in a package's R/ directory, making function arguments explicit.

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: 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).

Single-file operation

Operates on one R file. When path is NULL and RStudio is available, the currently active document is used automatically.

Examples

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))

Make Function Calls Explicit

Description

Add double colons (::) to function calls from specified packages to make package dependencies explicit in R code.

Usage

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)),
  ...
)

Arguments

path

A character string specifying the path to the R file to modify. If NULL and RStudio is available, the currently active document path is used.

use_packages

A character vector of package names to process. Defaults to current_packages().

ignore_functions

A character vector of function names to ignore. Defaults to c(imported_functions(), get_defined_fn(path)): the functions imported into NAMESPACE plus those defined in the target package, or in the target file when path is not a package root. Pass character() to ignore nothing.

...

Additional arguments. Currently unused and must be empty.

Details

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.

Value

Invisibly TRUE when the file was read successfully; the file is modified in place as a side effect.

Functions

  • package_func_call_explicit(): Processes all .R files in a package's R/ directory, adding explicit namespace qualifiers.

Examples

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()

Detect Lost Glue Brace in glue and cli Expressions

Description

Check 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.

Usage

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, ...)

Arguments

path

For detect_lost_glue_brace(): path to an R file. If NULL and RStudio is available, the active document path is used.

For package_lost_glue_brace(): path to the root directory of an R package. Defaults to the current directory.

dirs

Character vector of package-relative directories scanned by package_lost_glue_brace(). Defaults to "R" and "tests/testthat".

test_included

[Deprecated]. Logical indicating whether to scan tests/testthat/ in addition to R/. Use dirs instead. When supplied, FALSE scans only R/; TRUE scans both default directories.

...

Unused.

verbose

Whether to emit detection results to the console. Package scanning disables this and supplies its own progress and summary output.

Value

Invisibly returns TRUE if all expressions are balanced, FALSE otherwise.

Single file vs package scope

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/.

Examples

file <- tempfile(fileext = ".R")
writeLines('glue("{a")', file)
detect_lost_glue_brace(file)

Enrich the YAML headers of README.Rmd and vignettes/*.Rmd of a package

Description

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.

Usage

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
)

Arguments

path

Package root directory. NULL means the current 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" -> Sys.Date(); "desc" -> DESCRIPTION Date field; "none" -> do not add a date.

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 merged recursively, your values win). Built-in default: RStudio editor_options (markdown: wrap: sentence, chunk_output_type: console). To drop a default, set it to NULL, e.g. list(editor_options = NULL).

extra_readme, extra_vignette

Same as extra, but only applied when the file is a README / a vignette. Merge order (later wins): built-in defaults -> extra -> extra_readme / extra_vignette. Built-in README default: always_allow_html: true.

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. lang, date, author) replaces the generated value.

Value

The paths of the files that were changed (invisibly).

Examples

## 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)

Detect print() and cat() Calls (CRAN-Unsafe)

Description

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).

Usage

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,
  ...
)

Arguments

path

For detect_print_and_cat(): path to an R file. If NULL and RStudio is available, the active document path is used.

For package_print_and_cat(): path to the root directory of an R package. If NULL, the function walks up from the active document to find the package root.

dirs

Character vector of package-relative directories scanned by package_print_and_cat(). Defaults to "R" and "tests/testthat".

test_included

[Deprecated]. Logical indicating whether to scan tests/testthat/ in addition to R/. Use dirs instead. When supplied, FALSE scans only R/; TRUE scans both default directories.

fix

Logical. If TRUE, replace print(/cat( with message( directly in the source file(s). Default is FALSE.

...

Additional arguments passed to utils::methods (currently unused).

pattern_fn_names

Character vector of regular expressions matching function names whose return value is treated as a diagnostic string. A print() whose first argument is a string literal or calls a matching function is flagged as a message. Extra patterns are appended to the default set unless replace_default_pattern = TRUE.

To obtain the default patterns, use rpkgkit:::DEFAULT_PATTERN_FN_NAMES.

replace_default_pattern

Logical. If TRUE, pattern_fn_names fully replaces the default set instead of extending it.

include_s3

Logical. If TRUE, report print() calls whose first argument is not string-like (S3 object printing). Default TRUE.

include_refs

Logical. If TRUE, also report bare print/cat symbols (e.g. lapply(x, print)). Default FALSE.

verbose

Whether to output information in console

Value

Invisibly returns TRUE if no calls were found, FALSE otherwise. Side-effect messages and caret markers are emitted via cli and message.

Single file vs package scope

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.

Examples

# --- 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)

Detect Unmatched nocov Markers

Description

Check 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.

Usage

package_unmatched_nocov_marker(path = NULL, dirs = "R", verbose = TRUE)

detect_unmatched_nocov_marker(path = NULL, verbose = TRUE, ...)

Arguments

path

For detect_unmatched_nocov_marker(): path to an R file. If NULL and RStudio is available, the active document path is used.

For package_unmatched_nocov_marker(): path to the root directory of an R package. Defaults to the current directory.

dirs

Character vector of package-relative directories scanned by package_unmatched_nocov_marker(). Defaults to "R".

verbose

Whether to emit detection results to the console.

...

Unused.

Value

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.

Marker rules

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.

Second and later nocov start

Reported as a problem: only the first start is meaningful, so every further start is echoed with its line and column.

Second and later 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.

Single file vs package scope

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.

Examples

file <- tempfile(fileext = ".R")
writeLines(c("f <- function() 1", paste0("# nocov", " end")), file)
detect_unmatched_nocov_marker(file)

Rename Function Definitions in an R File

Description

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.

Usage

rename_func(
  path = NULL,
  style = c("snake_case", "camelCase", "PascalCase", "google"),
  num_to_word = c(`for` = 4L, to = 2L),
  ...
)

Arguments

path

A character string specifying the path to the R file to modify. If NULL and RStudio is available, the currently active document path is used.

style

Naming convention to apply. One of:

  • "snake_case": all lowercase with underscores (e.g., my_function)

  • "camelCase": lower camel case (e.g., myFunction)

  • "PascalCase": upper camel case (e.g., MyFunction)

  • "google": dot-separated lowercase (e.g., my.function)

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 c("for" = 4, "to" = 2). Any input other than a named vector, NULL, or FALSE is an error. Supply NULL or FALSE to disable the expansion.

...

Additional arguments. Currently unused and must be empty.

Details

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.

Value

Invisibly returns the path to the modified file.

Examples

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"

[Deprecated] Render an R Markdown or R document to Markdown format

Description

[Deprecated] Render an R Markdown or R document to Markdown format

Usage

render_rmd(path = NULL, output_format = "md_document", ...)

Arguments

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.

Value

The output file path from rmarkdown::render.

Examples

## Not run: 
rlang::check_installed("rmarkdown")
tmp <- tempfile(fileext = ".Rmd")
writeLines(c("---", "title: Test", "---", "", "Hello, world!"), tmp)
render_rmd(path = tmp)

## End(Not run)

Update the last-updated field in standalone R files

Description

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.

Usage

update_time_in_standalone(path = NULL)

Arguments

path

Character. Path to a standalone file or a directory. If NULL and rstudioapi is available, uses the currently active document. Defaults to NULL.

Value

Invisibly returns a character vector of updated file paths.

Examples

update_time_in_standalone(tempdir())

Format Long Vectors and Lists as Aligned Tables with Air

Description

Air (≥\geq 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:

  1. runs air format on path, so every long vector and list is laid out with one element per line;

  2. 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.

Usage

use_air_table(
  path = NULL,
  ncol = 3L,
  min_length = 12L,
  marker = "# fmt: table",
  ...
)

Arguments

path

Path to an R file to modify. If NULL and RStudio is available, the path of the active document is used.

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.

Details

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.

Value

Invisibly returns the normalized path.

Examples

## 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)

Add a BugReports field to a package's DESCRIPTION

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()).

Usage

use_bugreports(url = NULL, path = NULL, ...)

Arguments

url

Character. The bug reports URL (usually the GitHub issues page). If NULL (the default), it is derived from the git remote configuration by appending ⁠/issues⁠ to the repository URL.

path

Path to the package root. If NULL (the default), the current working directory is used.

...

Must be empty. Reserved for future arguments.

Value

Invisibly returns the URL that was written.

Examples

## Not run: 
tmpdir <- tempdir()
usethis::create_package(path = tmpdir)
use_bugreports(
  url = "https://github.com/WangLabCSU/rpkgkit/issues",
  path = tmpdir
)

## End(Not run)

Create a .clangd configuration file

Description

Writes 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.

Usage

use_clangd(
  path = NULL,
  include = c("Rcpp", "RcppEigen", "RcppArmadillo"),
  overwrite = FALSE,
  open = rlang::is_interactive(),
  ...
)

Arguments

path

Character. Path to the directory where .clangd should be written. If NULL (the default), the current working directory is used.

include

Character vector of package names whose ⁠include/⁠ directories should be added to CompileFlags.Add. Defaults to c("Rcpp", "RcppEigen", "RcppArmadillo"). Pass character(0) to add only the system R include path. Custom names such as "BH" are supported; if the package is not installed, its include path is skipped and a warning is emitted.

overwrite

Logical. If TRUE, overwrite an existing .clangd file. Defaults to FALSE.

open

Logical. Whether to open the created file in the editor. Defaults to rlang::is_interactive(). Only takes effect when rstudioapi is installed.

...

Must be empty. Reserved for future arguments.

Value

Invisibly returns the path to the created .clangd file.

Examples

tmp <- tempdir()
use_clangd(path = tmp)

# Custom include library names
use_clangd(
  path = tmp,
  include = c("Rcpp", "BH"),
  overwrite = TRUE
)

Use Hex Sticker in README

Description

[Deprecated] 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.

Usage

use_hexsticker(
  img_path,
  url = NULL,
  alt_text = "package logo",
  height = 139L,
  align = "right",
  path = NULL,
  ...
)

Arguments

img_path

Character. Path to the image file (e.g., "man/figures/logo.png").

url

Character. URL the image should link to. If NULL (default), no hyperlink is added.

alt_text

Character. Alt text for the image. Defaults to "package logo".

height

Numeric or character. Image height in pixels. Defaults to 139.

align

Character. Image alignment attribute. Defaults to "right".

path

Character. Path to the package root directory. If NULL (the default), uses the current working directory.

...

Additional HTML attributes to include in the ⁠<img>⁠ tag as named arguments.

Value

Invisibly returns TRUE on success.

Examples

## 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)

Create a jarl.toml configuration file

Description

Writes 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.

Usage

use_jarl(path = NULL, overwrite = FALSE, ...)

Arguments

path

Character. Path to the directory where jarl.toml should be written. If NULL (the default), the current working directory is used.

overwrite

Logical. If TRUE, overwrite an existing jarl.toml file. Defaults to FALSE.

...

Must be empty. Reserved for future arguments.

Value

Invisibly returns the path to the created jarl.toml file.

Examples

tmp <- tempdir()
use_jarl(path = tmp, overwrite = TRUE)
readLines(file.path(tmp, "jarl.toml"))

Create Multilingual README Files

Description

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.

Usage

use_multilanguage_readme(
  lang = c("zh-cn", "es", "fr", "ar", "ru"),
  color = "blue",
  ...,
  path = NULL,
  overwrite = FALSE
)

Arguments

lang

Character vector of language codes (e.g. "zh-cn", "ja"). Defaults to the five non-English UN official languages. Codes must be supported by the internal name mapping (see Language Codes below) or they will be used as-is for badge labels.

color

Color of badge. Defaults to "blue"

...

Not used.

path

Character. Path to the package root directory. If NULL (the default), uses the current working directory.

overwrite

Logical. If TRUE, overwrite existing README translation files. Defaults to FALSE.

Value

Invisibly returns a character vector of paths to the created files.

Language Codes

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.

Examples

## 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)

Set the minimum R version a package needs

Description

use_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.

Usage

use_r_v4.1.0(path = NULL, ...)

use_r(path = NULL, dirs = c("R", file.path("tests", "testthat")), ...)

Arguments

path

Path to the package root. If NULL (the default), the current working directory is used.

...

Must be empty. Reserved for future arguments.

dirs

Package-relative directories scanned by use_r(). Defaults to "R" and "tests/testthat"; missing directories are ignored.

Value

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.

Examples

## Not run: 
tmpdir <- tempdir()
usethis::create_package(path = tmpdir)
use_r_v4.1.0(path = tmpdir)
use_r(path = tmpdir)

## End(Not run)

Create an RStudio Addin registration entry for a package function

Description

use_tidy_addin() writes an entry into inst/rstudio/addins.dcf, which makes an exported function available from the RStudio Addins menu.

Usage

use_tidy_addin(fn_name, desc, Interactive = FALSE, path = NULL)

Arguments

fn_name

Name of the function (it must already be exported in NAMESPACE).

desc

Description of the addin.

Interactive

Whether this is an interactive addin (maps to the Interactive field of the dcf file).

path

Root directory of the R package.

Value

Invisibly, the path of the dcf file that was written (NULL if the operation was cancelled).

Examples

## Not run: 
# Inside a package that exports `my_addin()`
use_tidy_addin("my_addin", "Open my Shiny gadget", Interactive = TRUE)

## End(Not run)

Add a URL field to a package's DESCRIPTION

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).

Usage

use_url(url = NULL, pkgdown_url = NULL, path = NULL, ...)

Arguments

url

Character. The primary URL (usually the GitHub repository). If NULL (the default), it is detected from the git remote configuration.

pkgdown_url

Character. An optional pkgdown website URL, appended after url.

path

Path to the package root. If NULL (the default), the current working directory is used.

...

Must be empty. Reserved for future arguments.

Value

Invisibly returns the URLs that were written.

Examples

## 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)

Use a Vendor Package

Description

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

Usage

use_vendor(pkg, ..., branch = "main", path = NULL)

Arguments

pkg

GitHub repository specification in "owner/repo" form or a full GitHub URL (e.g. "https://github.com/owner/repo").

...

File paths within the vendor package to copy into your package. Files are routed by extension: .R files are appended to R/vendor-pkg.R, .c files to src/vendor-pkg.c, .cpp files to src/vendor-pkg.cpp, and .rs files to src/rust/src/vendor-pkg.rs. Paths without a directory component are looked up in the conventional directory of their language. If empty (default), only the infrastructure is set up.

branch

Github repository branch name. Defaults to "main"

path

Path to the target package directory. If NULL (the default), uses the current working directory.

Value

Invisibly returns NULL, called for side effects.

Examples

## 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)

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).

Usage

use_workflow_rust_compatible_check(path = NULL, overwrite = FALSE)

Arguments

path

Character. Path to the package root directory. If NULL (the default), uses the current working directory.

overwrite

Logical. If TRUE, overwrite an existing workflow file. Defaults to FALSE.

Value

Invisibly returns the path to the created workflow file.

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.

Examples

## 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)

Create a GitHub Actions Workflow to Sync Main to Test Branch

Description

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).

Usage

use_workflow_test_branch(path = NULL, overwrite = FALSE)

Arguments

path

Character. Path to the package root directory. If NULL (the default), uses the current working directory.

overwrite

Logical. If TRUE, overwrite existing workflow and action files. Defaults to FALSE.

Value

Invisibly returns the path to the created workflow file.

Examples

## Not run: 
temp <- tempdir()
usethis::create_package(temp)
use_workflow_test_branch(temp)
use_workflow_test_branch(temp, overwrite = TRUE)

## End(Not run)

Create a GitHub Actions workflow to auto-update R package version

Description

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.

Usage

use_workflow_version_update(
  path = NULL,
  overwrite = FALSE,
  color = "blue",
  ...
)

Arguments

path

Character. Path to the package root directory. If NULL (the default), uses the current working directory.

overwrite

Logical. If TRUE, overwrite an existing workflow file. Defaults to FALSE.

color

badge color

...

pass to badger::badge_devel

Value

Invisibly returns the path to the created workflow file.

NEWS.md guard

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.

Rust crate version

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).

Examples

## Not run: 
temp <- tempdir()
usethis::create_package(temp)
use_workflow_version_update(temp)
use_workflow_version_update(temp, overwrite = TRUE)

## End(Not run)

Create a (pkgname)-package.R file from a template

Description

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.

Usage

use_zzz(
  path = NULL,
  file_name = NULL,
  overwrite = FALSE,
  open = rlang::is_interactive(),
  ...
)

Arguments

path

Character. Path to the package root directory. If NULL (the default), uses the current working directory.

file_name

Character. Output file name. Defaults to "<pkg_name>-package.R".

overwrite

Logical. If TRUE, overwrite an existing file. Defaults to FALSE.

open

Logical. Whether to open the created file in the default editor.

...

Not used.

Value

Invisibly returns the path to the created file.

Examples

## Not run: 
dir <- tempdir()
usethis::create_package(dir)
use_zzz(dir)

## End(Not run)