Title: | Automate Package and Project Setup |
Version: | 3.1.0 |
Description: | Automate package and project setup tasks that are otherwise performed manually. This includes setting up unit testing, test coverage, continuous integration, Git, 'GitHub', licenses, 'Rcpp', 'RStudio' projects, and more. |
License: | MIT + file LICENSE |
URL: | https://usethis.r-lib.org, https://github.com/r-lib/usethis |
BugReports: | https://github.com/r-lib/usethis/issues |
Depends: | R (≥ 3.6) |
Imports: | cli (≥ 3.0.1), clipr (≥ 0.3.0), crayon, curl (≥ 2.7), desc (≥ 1.4.2), fs (≥ 1.3.0), gert (≥ 1.4.1), gh (≥ 1.2.1), glue (≥ 1.3.0), jsonlite, lifecycle (≥ 1.0.0), purrr, rappdirs, rlang (≥ 1.1.0), rprojroot (≥ 1.2), rstudioapi, stats, tools, utils, whisker, withr (≥ 2.3.0), yaml |
Suggests: | covr, knitr, magick, pkgload (≥ 1.3.2.1), rmarkdown, roxygen2 (≥ 7.1.2), spelling (≥ 1.2), styler (≥ 1.2.0), testthat (≥ 3.1.8) |
Config/Needs/website: | r-lib/asciicast, tidyverse/tidytemplate, xml2 |
Config/testthat/edition: | 3 |
Config/testthat/parallel: | TRUE |
Config/testthat/start-first: | github-actions, release |
Encoding: | UTF-8 |
Language: | en-US |
RoxygenNote: | 7.3.2 |
NeedsCompilation: | no |
Packaged: | 2024-11-25 22:12:19 UTC; jenny |
Author: | Hadley Wickham |
Maintainer: | Jennifer Bryan <jenny@posit.co> |
Repository: | CRAN |
Date/Publication: | 2024-11-26 10:20:02 UTC |
usethis: Automate Package and Project Setup
Description
Automate package and project setup tasks that are otherwise performed manually. This includes setting up unit testing, test coverage, continuous integration, Git, 'GitHub', licenses, 'Rcpp', 'RStudio' projects, and more.
Author(s)
Maintainer: Jennifer Bryan jenny@posit.co (ORCID)
Authors:
Hadley Wickham hadley@posit.co (ORCID)
Malcolm Barrett malcolmbarrett@gmail.com (ORCID)
Andy Teucher andy.teucher@posit.co (ORCID)
Other contributors:
Posit Software, PBC [copyright holder, funder]
See Also
Useful links:
Report bugs at https://github.com/r-lib/usethis/issues
README badges
Description
These helpers produce the markdown text you need in your README to include
badges that report information, such as the CRAN version or test coverage,
and link out to relevant external resources. To add badges automatically
ensure your badge block starts with a line containing only
<!-- badges: start -->
and ends with a line containing only
<!-- badges: end -->
.
Usage
use_badge(badge_name, href, src)
use_cran_badge()
use_bioc_badge()
use_lifecycle_badge(stage)
use_binder_badge(ref = git_default_branch(), urlpath = NULL)
use_posit_cloud_badge(url)
Arguments
badge_name |
Badge name. Used in error message and alt text |
href , src |
Badge link and image src |
stage |
Stage of the package lifecycle. One of "experimental", "stable", "superseded", or "deprecated". |
ref |
A Git branch, tag, or SHA |
urlpath |
An optional |
url |
A link to an existing Posit Cloud project. See the Posit Cloud documentation for details on how to set project access and obtain a project link. |
Details
-
use_badge()
: a general helper used in all badge functions -
use_bioc_badge()
: badge indicates BioConductor build status -
use_cran_badge()
: badge indicates what version of your package is available on CRAN, powered by https://www.r-pkg.org -
use_lifecycle_badge()
: badge declares the developmental stage of a package according to https://lifecycle.r-lib.org/articles/stages.html. -
use_binder_badge()
: badge indicates that your repository can be launched in an executable environment on https://mybinder.org/ -
use_posit_cloud_badge()
: badge indicates that your repository can be launched in a Posit Cloud project -
use_rscloud_badge()
:: Use
use_posit_cloud_badge()
instead.
See Also
Functions that configure continuous integration, such as
use_github_actions()
, also create badges.
Examples
## Not run:
use_cran_badge()
use_lifecycle_badge("stable")
## End(Not run)
Visit important project-related web pages
Description
These functions take you to various web pages associated with a project (often, an R package) and return the target URL(s) invisibly. To form these URLs we consult:
Git remotes configured for the active project that appear to be hosted on a GitHub deployment
DESCRIPTION file for the active project or the specified
package
. The DESCRIPTION file is sought first in the local package library and then on CRAN.Fixed templates:
Circle CI:
https://circleci.com/gh/{OWNER}/{PACKAGE}
CRAN landing page:
https://cran.r-project.org/package={PACKAGE}
GitHub mirror of a CRAN package:
https://github.com/cran/{PACKAGE}
Templated URLs aren't checked for existence, so there is no guarantee there will be content at the destination.
Usage
browse_package(package = NULL)
browse_project()
browse_github(package = NULL)
browse_github_issues(package = NULL, number = NULL)
browse_github_pulls(package = NULL, number = NULL)
browse_github_actions(package = NULL)
browse_circleci(package = NULL)
browse_cran(package = NULL)
Arguments
package |
Name of package. If |
number |
Optional, to specify an individual GitHub issue or pull
request. Can be a number or |
Details
-
browse_package()
: Assembles a list of URLs and lets user choose one to visit in a web browser. In a non-interactive session, returns all discovered URLs. -
browse_project()
: Thin wrapper aroundbrowse_package()
that always targets the active usethis project. -
browse_github()
: Visits a GitHub repository associated with the project. In the case of a fork, you might be asked to specify if you're interested in the source repo or your fork. -
browse_github_issues()
: Visits the GitHub Issues index or one specific issue. -
browse_github_pulls()
: Visits the GitHub Pull Request index or one specific pull request. -
browse_circleci()
: Visits the project's page on Circle CI. -
browse_cran()
: Visits the package on CRAN, via the canonical URL.
Examples
# works on the active project
# browse_project()
browse_package("httr")
browse_github("gh")
browse_github_issues("fs")
browse_github_issues("fs", 1)
browse_github_pulls("curl")
browse_github_pulls("curl", 183)
browse_cran("MASS")
Create a project from a GitHub repo
Description
Creates a new local project and Git repository from a repo on GitHub, by
either cloning or
fork-and-cloning.
In the fork-and-clone case, create_from_github()
also does additional
remote and branch setup, leaving you in the perfect position to make a pull
request with pr_init()
, one of several functions for working with pull requests.
create_from_github()
works best when your GitHub credentials are
discoverable. See below for more about authentication.
Usage
create_from_github(
repo_spec,
destdir = NULL,
fork = NA,
rstudio = NULL,
open = rlang::is_interactive(),
protocol = git_protocol(),
host = NULL
)
Arguments
repo_spec |
A string identifying the GitHub repo in one of these forms:
|
destdir |
Destination for the new folder, which will be named according
to the |
fork |
If
If |
rstudio |
Initiate an RStudio Project?
Defaults to |
open |
If
|
protocol |
One of "https" or "ssh" |
host |
GitHub host to target, passed to the If unspecified, gh defaults to "https://api.github.com", although gh's default can be customised by setting the GITHUB_API_URL environment variable. For a hypothetical GitHub Enterprise instance, either "https://github.acme.com/api/v3" or "https://github.acme.com" is acceptable. |
Git/GitHub Authentication
Many usethis functions, including those documented here, potentially interact with GitHub in two different ways:
Via the GitHub REST API. Examples: create a repo, a fork, or a pull request.
As a conventional Git remote. Examples: clone, fetch, or push.
Therefore two types of auth can happen and your credentials must be discoverable. Which credentials do we mean?
A GitHub personal access token (PAT) must be discoverable by the gh package, which is used for GitHub operations via the REST API. See
gh_token_help()
for more about getting and configuring a PAT.If you use the HTTPS protocol for Git remotes, your PAT is also used for Git operations, such as
git push
. Usethis uses the gert package for this, so the PAT must be discoverable by gert. Generally gert and gh will discover and use the same PAT. This ability to "kill two birds with one stone" is why HTTPS + PAT is our recommended auth strategy for those new to Git and GitHub and PRs.If you use SSH remotes, your SSH keys must also be discoverable, in addition to your PAT. The public key must be added to your GitHub account.
Git/GitHub credential management is covered in a dedicated article: Managing Git(Hub) Credentials
See Also
-
use_github()
to go the opposite direction, i.e. create a GitHub repo from your local repo -
git_protocol()
for background onprotocol
(HTTPS vs SSH) -
use_course()
to download a snapshot of all files in a GitHub repo, without the need for any local or remote Git operations
Examples
## Not run:
create_from_github("r-lib/usethis")
# repo_spec can be a URL
create_from_github("https://github.com/r-lib/usethis")
# a URL repo_spec also specifies the host (e.g. GitHub Enterprise instance)
create_from_github("https://github.acme.com/OWNER/REPO")
## End(Not run)
Create a package or project
Description
These functions create an R project:
-
create_package()
creates an R package -
create_project()
creates a non-package project, i.e. a data analysis project
Both functions can be called on an existing project; you will be asked before any existing files are changed.
Usage
create_package(
path,
fields = list(),
rstudio = rstudioapi::isAvailable(),
roxygen = TRUE,
check_name = TRUE,
open = rlang::is_interactive()
)
create_project(
path,
rstudio = rstudioapi::isAvailable(),
open = rlang::is_interactive()
)
Arguments
path |
A path. If it exists, it is used. If it does not exist, it is created, provided that the parent path exists. |
fields |
A named list of fields to add to |
rstudio |
If |
roxygen |
Do you plan to use roxygen2 to document your package? |
check_name |
Whether to check if the name is valid for CRAN and throw an error if not. |
open |
If
|
Value
Path to the newly created project or package, invisibly.
See Also
create_tidy_package()
is a convenience function that extends
create_package()
by immediately applying as many of the tidyverse
development conventions as possible.
Open configuration files
Description
-
edit_r_profile()
opens.Rprofile
-
edit_r_environ()
opens.Renviron
-
edit_r_makevars()
opens.R/Makevars
-
edit_git_config()
opens.gitconfig
or.git/config
-
edit_git_ignore()
opens global (user-level) gitignore file and ensures its path is declared in your global Git config. -
edit_pkgdown_config
opens the pkgdown YAML configuration file for the current Project. -
edit_rstudio_snippets()
opens RStudio's snippet config for the given type. -
edit_rstudio_prefs()
opens RStudio's preference file.
Usage
edit_r_profile(scope = c("user", "project"))
edit_r_environ(scope = c("user", "project"))
edit_r_buildignore()
edit_r_makevars(scope = c("user", "project"))
edit_rstudio_snippets(
type = c("r", "markdown", "c_cpp", "css", "html", "java", "javascript", "python",
"sql", "stan", "tex", "yaml")
)
edit_rstudio_prefs()
edit_git_config(scope = c("user", "project"))
edit_git_ignore(scope = c("user", "project"))
edit_pkgdown_config()
Arguments
scope |
Edit globally for the current user, or locally for the current project |
type |
Snippet type (case insensitive text). |
Details
The edit_r_*()
functions consult R's notion of user's home directory.
The edit_git_*()
functions (and usethis in general) inherit home
directory behaviour from the fs package, which differs from R itself
on Windows. The fs default is more conventional in terms of the
location of user-level Git config files. See fs::path_home()
for more
details.
Files created by edit_rstudio_snippets()
will mask, not supplement,
the built-in default snippets. If you like the built-in snippets, copy them
and include with your custom snippets.
Value
Path to the file, invisibly.
Open file for editing
Description
Opens a file for editing in RStudio, if that is the active environment, or
via utils::file.edit()
otherwise. If the file does not exist, it is
created. If the parent directory does not exist, it is also created.
edit_template()
specifically opens templates in inst/templates
for use
with use_template()
.
Usage
edit_file(path, open = rlang::is_interactive())
edit_template(template = NULL, open = rlang::is_interactive())
Arguments
path |
Path to target file. |
open |
Whether to open the file for interactive editing. |
template |
The target template file. If not specified, existing template files are offered for interactive selection. |
Value
Target path, invisibly.
Examples
## Not run:
edit_file("DESCRIPTION")
edit_file("~/.gitconfig")
## End(Not run)
Deprecated Git functions
Description
git_branch_default()
has been replaced by git_default_branch()
.
Usage
git_branch_default()
See or set the default Git protocol
Description
Git operations that address a remote use a so-called "transport protocol". usethis supports HTTPS and SSH. The protocol dictates the Git URL format used when usethis needs to configure the first GitHub remote for a repo:
-
protocol = "https"
implieshttps://github.com/<OWNER>/<REPO>.git
-
protocol = "ssh"
impliesgit@github.com:<OWNER>/<REPO>.git
Two helper functions are available:
-
git_protocol()
reveals the protocol "in force". As of usethis v2.0.0, this defaults to "https". You can change this for the duration of the R session withuse_git_protocol()
. Change the default for all R sessions with code like this in your.Rprofile
(easily editable viaedit_r_profile()
):options(usethis.protocol = "ssh")
-
use_git_protocol()
sets the Git protocol for the current R session
This protocol only affects the Git URL for newly configured remotes. All existing Git remote URLs are always respected, whether HTTPS or SSH.
Usage
git_protocol()
use_git_protocol(protocol)
Arguments
protocol |
One of "https" or "ssh" |
Value
The protocol, either "https" or "ssh"
Examples
## Not run:
git_protocol()
use_git_protocol("ssh")
git_protocol()
use_git_protocol("https")
git_protocol()
## End(Not run)
Git/GitHub sitrep
Description
Get a situation report on your current Git/GitHub status. Useful for
diagnosing problems. The default is to report all values; provide values
for tool
or scope
to be more specific.
Usage
git_sitrep(tool = c("git", "github"), scope = c("user", "project"))
Arguments
tool |
Report for git, or github |
scope |
Report globally for the current user, or locally for the current project |
Examples
## Not run:
# report all
git_sitrep()
# report git for current user
git_sitrep("git", "user")
## End(Not run)
Vaccinate your global gitignore file
Description
Adds .Rproj.user
, .Rhistory
, .Rdata
, .httr-oauth
, .DS_Store
, and
.quarto
to your global (a.k.a. user-level) .gitignore
. This is good
practice as it decreases the chance that you will accidentally leak
credentials to GitHub. git_vaccinate()
also tries to detect and fix the
situation where you have a global gitignore file, but it's missing from your
global Git config.
Usage
git_vaccinate()
Get or set the default Git branch
Description
The git_default_branch*()
functions put some structure around the somewhat
fuzzy (but definitely real) concept of the default branch. In particular,
they support new conventions around the Git default branch name, globally or
in a specific project / Git repository.
Usage
git_default_branch()
git_default_branch_configure(name = "main")
git_default_branch_rediscover(current_local_default = NULL)
git_default_branch_rename(from = NULL, to = "main")
Arguments
name |
Default name for the initial branch in new Git repositories. |
current_local_default |
Name of the local branch that is currently functioning as the default branch. If unspecified, this can often be inferred. |
from |
Name of the branch that is currently functioning as the default branch. |
to |
New name for the default branch. |
Value
Name of the default branch.
Background on the default branch
Technically, Git has no official concept of the default branch. But in
reality, almost all Git repos have an effective default branch. If there's
only one branch, this is it! It is the branch that most bug fixes and
features get merged in to. It is the branch you see when you first visit a
repo on a site such as GitHub. On a Git remote, it is the branch that HEAD
points to.
Historically, master
has been the most common name for the default branch,
but main
is an increasingly popular choice.
git_default_branch_configure()
This configures init.defaultBranch
at the global (a.k.a user) level. This
setting determines the name of the branch that gets created when you make the
first commit in a new Git repo. init.defaultBranch
only affects the local
Git repos you create in the future.
git_default_branch()
This figures out the default branch of the current Git repo, integrating
information from the local repo and, if applicable, the upstream
or
origin
remote. If there is a local vs. remote mismatch,
git_default_branch()
throws an error with advice to call
git_default_branch_rediscover()
to repair the situation.
For a remote repo, the default branch is the branch that HEAD
points to.
For the local repo, if there is only one branch, that must be the default! Otherwise we try to identify the relevant local branch by looking for specific branch names, in this order:
whatever the default branch of
upstream
ororigin
is, if applicable-
main
-
master
the value of the Git option
init.defaultBranch
, with the usual deal where a local value, if present, takes precedence over a global (a.k.a. user-level) value
git_default_branch_rediscover()
This consults an external authority – specifically, the remote source
repo on GitHub – to learn the default branch of the current project /
repo. If that doesn't match the apparent local default branch (for example,
the project switched from master
to main
), we do the corresponding branch
renaming in your local repo and, if relevant, in your fork.
See https://happygitwithr.com/common-remote-setups.html for more about
GitHub remote configurations and, e.g., what we mean by the source repo. This
function works for the configurations "ours"
, "fork"
, and "theirs"
.
git_default_branch_rename()
Note: this only works for a repo that you effectively own. In terms of
GitHub, you must own the source repo personally or, if
organization-owned, you must have admin
permission on the source repo.
This renames the default branch in the source repo on GitHub and then
calls git_default_branch_rediscover()
, to make any necessary changes in the
local repo and, if relevant, in your personal fork.
See https://happygitwithr.com/common-remote-setups.html for more about
GitHub remote configurations and, e.g., what we mean by the source repo. This
function works for the configurations "ours"
, "fork"
, and "no_github"
.
Regarding "no_github"
: Of course, this function does what you expect for a
local repo with no GitHub remotes, but that is not the primary use case.
Examples
## Not run:
git_default_branch()
## End(Not run)
## Not run:
git_default_branch_configure()
## End(Not run)
## Not run:
git_default_branch_rediscover()
# you can always explicitly specify the local branch that's been playing the
# role of the default
git_default_branch_rediscover("unconventional_default_branch_name")
## End(Not run)
## Not run:
git_default_branch_rename()
# you can always explicitly specify one or both branch names
git_default_branch_rename(from = "this", to = "that")
## End(Not run)
Get help with GitHub personal access tokens
Description
A personal access token (PAT) is needed for certain tasks usethis does via the GitHub API, such as creating a repository, a fork, or a pull request. If you use HTTPS remotes, your PAT is also used when interacting with GitHub as a conventional Git remote. These functions help you get and manage your PAT:
-
gh_token_help()
guides you through token troubleshooting and setup. -
create_github_token()
opens a browser window to the GitHub form to generate a PAT, with suggested scopes pre-selected. It also offers advice on storing your PAT. -
gitcreds::gitcreds_set()
helps you register your PAT with the Git credential manager used by your operating system. Later, other packages, such as usethis, gert, and gh can automatically retrieve that PAT and use it to work with GitHub on your behalf.
Usually, the first time the PAT is retrieved in an R session, it is cached in an environment variable, for easier reuse for the duration of that R session. After initial acquisition and storage, all of this should happen automatically in the background. GitHub is encouraging the use of PATs that expire after, e.g., 30 days, so prepare yourself to re-generate and re-store your PAT periodically.
Git/GitHub credential management is covered in a dedicated article: Managing Git(Hub) Credentials
Usage
create_github_token(
scopes = c("repo", "user", "gist", "workflow"),
description = "DESCRIBE THE TOKEN'S USE CASE",
host = NULL
)
gh_token_help(host = NULL)
Arguments
scopes |
Character vector of token scopes, pre-selected in the web form. Final choices are made in the GitHub form. Read more about GitHub API scopes at https://docs.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/. |
description |
Short description or nickname for the token. You might (eventually) have multiple tokens on your GitHub account and a label can help you keep track of what each token is for. |
host |
GitHub host to target, passed to the For a hypothetical GitHub Enterprise instance, either "https://github.acme.com/api/v3" or "https://github.acme.com" is acceptable. |
Details
create_github_token()
has previously gone by some other names:
browse_github_token()
and browse_github_pat()
.
Value
Nothing
See Also
gh::gh_whoami()
for information on an existing token and
gitcreds::gitcreds_set()
and gitcreds::gitcreds_get()
for a secure way
to store and retrieve your PAT.
Examples
## Not run:
create_github_token()
## End(Not run)
## Not run:
gh_token_help()
## End(Not run)
Helpers for GitHub issues
Description
The issue_*
family of functions allows you to perform common operations on
GitHub issues from within R. They're designed to help you efficiently deal
with large numbers of issues, particularly motivated by the challenges faced
by the tidyverse team.
-
issue_close_community()
closes an issue, because it's not a bug report or feature request, and points the author towards Posit Community as a better place to discuss usage (https://forum.posit.co). -
issue_reprex_needed()
labels the issue with the "reprex" label and gives the author some advice about what is needed.
Usage
issue_close_community(number, reprex = FALSE)
issue_reprex_needed(number)
Arguments
number |
Issue number |
reprex |
Does the issue also need a reprex? |
Saved replies
Unlike GitHub's "saved replies", these functions can:
Be shared between people
Perform other actions, like labelling, or closing
Have additional arguments
Include randomness (like friendly gifs)
Examples
## Not run:
issue_close_community(12, reprex = TRUE)
issue_reprex_needed(241)
## End(Not run)
License a package
Description
Adds the necessary infrastructure to declare your package as licensed with one of these popular open source licenses:
Permissive:
-
MIT: simple and permissive.
-
Apache 2.0: MIT + provides patent protection.
Copyleft:
-
GPL v2: requires sharing of improvements.
-
GPL v3: requires sharing of improvements.
-
AGPL v3: requires sharing of improvements.
-
LGPL v2.1: requires sharing of improvements.
-
LGPL v3: requires sharing of improvements.
Creative commons licenses appropriate for data packages:
See https://choosealicense.com for more details and other options.
Alternatively, for code that you don't want to share with others,
use_proprietary_license()
makes it clear that all rights are reserved,
and the code is not open source.
Usage
use_mit_license(copyright_holder = NULL)
use_gpl_license(version = 3, include_future = TRUE)
use_agpl_license(version = 3, include_future = TRUE)
use_lgpl_license(version = 3, include_future = TRUE)
use_apache_license(version = 2, include_future = TRUE)
use_cc0_license()
use_ccby_license()
use_proprietary_license(copyright_holder)
Arguments
copyright_holder |
Name of the copyright holder or holders. This
defaults to |
version |
License version. This defaults to latest version all licenses. |
include_future |
If |
Details
CRAN does not permit you to include copies of standard licenses in your
package, so these functions save the license as LICENSE.md
and add it
to .Rbuildignore
.
See Also
For more details, refer to the the license chapter in R Packages.
Activate a project
Description
Activates a project in usethis, R session, and (if relevant) RStudio senses. If you are in RStudio, this will open a new RStudio session. If not, it will change the working directory and active project.
Usage
proj_activate(path)
Arguments
path |
Project directory |
Value
Single logical value indicating if current session is modified.
Report working directory and usethis/RStudio project
Description
proj_sitrep()
reports
current working directory
the active usethis project
the active RStudio Project
Call this function if things seem weird and you're not sure
what's wrong or how to fix it. Usually, all three of these should coincide
(or be unset) and proj_sitrep()
provides suggested commands for getting
back to this happy state.
Usage
proj_sitrep()
Value
A named list, with S3 class sitrep
(for printing purposes),
reporting current working directory, active usethis project, and active
RStudio Project
See Also
Other project functions:
proj_utils
Examples
proj_sitrep()
Utility functions for the active project
Description
Most use_*()
functions act on the active project. If it is
unset, usethis uses rprojroot to
find the project root of the current working directory. It establishes the
project root by looking for a .here
file, an RStudio Project, a package
DESCRIPTION
, Git infrastructure, a remake.yml
file, or a .projectile
file. It then stores the active project for use for the remainder of the
session.
In general, end user scripts should not contain direct calls to
usethis::proj_*()
utility functions. They are internal functions that are
exported for occasional interactive use or use in packages that extend
usethis. End user code should call functions in
rprojroot or its simpler companion,
here, to programmatically detect a project and
build paths within it.
If you are puzzled why a path (usually the current working directory) does
not appear to be inside project, it can be helpful to call
here::dr_here()
to get much more verbose feedback.
Usage
proj_get()
proj_set(path = ".", force = FALSE)
proj_path(..., ext = "")
with_project(
path = ".",
code,
force = FALSE,
setwd = TRUE,
quiet = getOption("usethis.quiet", default = FALSE)
)
local_project(
path = ".",
force = FALSE,
setwd = TRUE,
quiet = getOption("usethis.quiet", default = FALSE),
.local_envir = parent.frame()
)
Arguments
path |
Path to set. This |
force |
If |
... |
character vectors, if any values are NA, the result will also be NA. The paths follow the recycling rules used in the tibble package, namely that only length 1 arguments are recycled. |
ext |
An optional extension to append to the generated path. |
code |
Code to run with temporary active project |
setwd |
Whether to also temporarily set the working directory to the
active project, if it is not |
quiet |
Whether to suppress user-facing messages, while operating in the temporary active project |
.local_envir |
The environment to use for scoping. Defaults to current execution environment. |
Functions
-
proj_get()
: Retrieves the active project and, if necessary, attempts to set it in the first place. -
proj_set()
: Sets the active project. -
proj_path()
: Builds paths within the active project returned byproj_get()
. Thin wrapper aroundfs::path()
. -
with_project()
: Runs code with a temporary active project and, optionally, working directory. It is an example of thewith_*()
functions in withr. -
local_project()
: Sets an active project and, optionally, working directory until the current execution environment goes out of scope, e.g. the end of the current function or test. It is an example of thelocal_*()
functions in withr.
See Also
Other project functions:
proj_sitrep()
Examples
## Not run:
## see the active project
proj_get()
## manually set the active project
proj_set("path/to/target/project")
## build a path within the active project (both produce same result)
proj_path("R/foo.R")
proj_path("R", "foo", ext = "R")
## build a path within SOME OTHER project
with_project("path/to/some/other/project", proj_path("blah.R"))
## convince yourself that with_project() temporarily changes the project
with_project("path/to/some/other/project", print(proj_sitrep()))
## End(Not run)
Helpers for GitHub pull requests
Description
The pr_*
family of functions is designed to make working with GitHub pull
requests (PRs) as painless as possible for both contributors and package
maintainers.
To use the pr_*
functions, your project must be a Git repo and have one of
these GitHub remote configurations:
"ours": You can push to the GitHub remote configured as
origin
and it's not a fork."fork": You can push to the GitHub remote configured as
origin
, it's a fork, and its parent is configured asupstream
.origin
points to your personal copy andupstream
points to the source repo.
"Ours" and "fork" are two of several GitHub remote configurations examined in Common remote setups in Happy Git and GitHub for the useR.
The Pull Request Helpers
article walks through the process of making a pull request with the pr_*
functions.
The pr_*
functions also use your Git/GitHub credentials to carry out
various remote operations; see below for more about auth. The pr_*
functions also proactively check for agreement re: the default branch in your
local repo and the source repo. See git_default_branch()
for more.
Usage
pr_init(branch)
pr_resume(branch = NULL)
pr_fetch(number = NULL, target = c("source", "primary"))
pr_push()
pr_pull()
pr_merge_main()
pr_view(number = NULL, target = c("source", "primary"))
pr_pause()
pr_finish(number = NULL, target = c("source", "primary"))
pr_forget()
Arguments
branch |
Name of a new or existing local branch. If creating a new
branch, note this should usually consist of lower case letters, numbers,
and |
number |
Number of PR. |
target |
Which repo to target? This is only a question in the case of a
fork. In a fork, there is some slim chance that you want to consider pull
requests against your fork (the primary repo, i.e. |
Git/GitHub Authentication
Many usethis functions, including those documented here, potentially interact with GitHub in two different ways:
Via the GitHub REST API. Examples: create a repo, a fork, or a pull request.
As a conventional Git remote. Examples: clone, fetch, or push.
Therefore two types of auth can happen and your credentials must be discoverable. Which credentials do we mean?
A GitHub personal access token (PAT) must be discoverable by the gh package, which is used for GitHub operations via the REST API. See
gh_token_help()
for more about getting and configuring a PAT.If you use the HTTPS protocol for Git remotes, your PAT is also used for Git operations, such as
git push
. Usethis uses the gert package for this, so the PAT must be discoverable by gert. Generally gert and gh will discover and use the same PAT. This ability to "kill two birds with one stone" is why HTTPS + PAT is our recommended auth strategy for those new to Git and GitHub and PRs.If you use SSH remotes, your SSH keys must also be discoverable, in addition to your PAT. The public key must be added to your GitHub account.
Git/GitHub credential management is covered in a dedicated article: Managing Git(Hub) Credentials
For contributors
To contribute to a package, first use create_from_github("OWNER/REPO")
.
This forks the source repository and checks out a local copy.
Next use pr_init()
to create a branch for your PR. It is best practice to
never make commits to the default branch branch of a fork (usually named
main
or master
), because you do not own it. A pull request should always
come from a feature branch. It will be much easier to pull upstream changes
from the fork parent if you only allow yourself to work in feature branches.
It is also much easier for a maintainer to explore and extend your PR if you
create a feature branch.
Work locally, in your branch, making changes to files, and committing your
work. Once you're ready to create the PR, run pr_push()
to push your local
branch to GitHub, and open a webpage that lets you initiate the PR (or draft
PR).
To learn more about the process of making a pull request, read the Pull Request Helpers vignette.
If you are lucky, your PR will be perfect, and the maintainer will accept it.
You can then run pr_finish()
to delete your PR branch. In most cases,
however, the maintainer will ask you to make some changes. Make the changes,
then run pr_push()
to update your PR.
It's also possible that the maintainer will contribute some code to your PR:
to get those changes back onto your computer, run pr_pull()
. It can also
happen that other changes have occurred in the package since you first
created your PR. You might need to merge the default branch (usually named
main
or master
) into your PR branch. Do that by running
pr_merge_main()
: this makes sure that your PR is compatible with the
primary repo's main line of development. Both pr_pull()
and
pr_merge_main()
can result in merge conflicts, so be prepared to resolve
before continuing.
For maintainers
To download a PR locally so that you can experiment with it, run
pr_fetch()
and select the PR or, if you already know its number, call
pr_fetch(<pr_number>)
. If you make changes, run pr_push()
to push them
back to GitHub. After you have merged the PR, run pr_finish()
to delete the
local branch and remove the remote associated with the contributor's fork.
Overview of all the functions
-
pr_init()
: As a contributor, start work on a new PR by ensuring that your local repo is up-to-date, then creating and checking out a new branch. Nothing is pushed to or created on GitHub until you callpr_push()
. -
pr_fetch()
: As a maintainer, review or contribute changes to an existing PR by creating a local branch that tracks the remote PR.pr_fetch()
does as little work as possible, so you can also use it to resume work on an PR that already has a local branch (where it will also ensure your local branch is up-to-date). If called with no arguments, up to 9 open PRs are offered for interactive selection. -
pr_resume()
: Resume work on a PR by switching to an existing local branch and pulling any changes from its upstream tracking branch, if it has one. If called with no arguments, up to 9 local branches are offered for interactive selection, with a preference for branches connected to PRs and for branches with recent activity. -
pr_push()
: The first time it's called, a PR branch is pushed to GitHub and you're taken to a webpage where a new PR (or draft PR) can be created. This also sets up the local branch to track its remote counterpart. Subsequent calls topr_push()
make sure the local branch has all the remote changes and, if so, pushes local changes, thereby updating the PR. -
pr_pull()
: Pulls changes from the local branch's remote tracking branch. If a maintainer has extended your PR, this is how you bring those changes back into your local work. -
pr_merge_main()
: Pulls changes from the default branch of the source repo into the current local branch. This can be used when the local branch is the default branch or when it's a PR branch. -
pr_pause()
: Makes sure you're up-to-date with any remote changes in the PR. Then switches back to the default branch and pulls from the source repo. Usepr_resume()
with name of branch or usepr_fetch()
to resume using PR number. -
pr_view()
: Visits the PR associated with the current branch in the browser (default) or the specific PR identified bynumber
. (FYIbrowse_github_pulls()
is a handy way to visit the list of all PRs for the current project.) -
pr_forget()
: Does local clean up when the current branch is an actual or notional PR that you want to abandon. Maybe you initiated it yourself, viapr_init()
, or you usedpr_fetch()
to explore a PR from GitHub. Only does local operations: does not update or delete any remote branches, nor does it close any PRs. Alerts the user to any uncommitted or unpushed work that is at risk of being lost. If user chooses to proceed, switches back to the default branch, pulls changes from source repo, and deletes local PR branch. Any associated Git remote is deleted, if the "forgotten" PR was the only branch using it. -
pr_finish()
: Does post-PR clean up, but does NOT actually merge or close a PR (maintainer should do this in the browser). Ifnumber
is not given, infers the PR from the upstream tracking branch of the current branch. Ifnumber
is given, it does not matter whether the PR exists locally. If PR exists locally, alerts the user to uncommitted or unpushed changes, then switches back to the default branch, pulls changes from source repo, and deletes local PR branch. If the PR came from an external fork, any associated Git remote is deleted, provided it's not in use by any other local branches. If the PR has been merged and user has permission, deletes the remote branch (this is the only remote operation thatpr_finish()
potentially does).
Examples
## Not run:
pr_fetch(123)
## End(Not run)
Automatically rename paired R/
and test/
files
Description
Moves
R/{old}.R
toR/{new}.R
Moves
src/{old}.*
tosrc/{new}.*
Moves
tests/testthat/test-{old}.R
totests/testthat/test-{new}.R
Moves
tests/testthat/test-{old}-*.*
totests/testthat/test-{new}-*.*
and updates paths in the test file.Removes
context()
calls from the test file, which are unnecessary (and discouraged) as of testthat v2.1.0.
This is a potentially dangerous operation, so you must be using Git in order to use this function.
Usage
rename_files(old, new)
Arguments
old , new |
Old and new file names (with or without |
Helpers to make useful changes to .Rprofile
Description
All functions open your .Rprofile
and give you the code you need to
paste in.
-
use_devtools()
: makes devtools available in interactive sessions. -
use_usethis()
: makes usethis available in interactive sessions. -
use_reprex()
: makes reprex available in interactive sessions. -
use_conflicted()
: makes conflicted available in interactive sessions. -
use_partial_warnings()
: warns on partial matches.
Usage
use_conflicted()
use_reprex()
use_usethis()
use_devtools()
use_partial_warnings()
Suppress usethis's messaging
Description
Execute a bit of code without usethis's normal messaging.
Usage
ui_silence(code)
Arguments
code |
Code to execute with usual UI output silenced. |
Value
Whatever code
returns.
Examples
# compare the messaging you see from this:
browse_github("usethis")
# vs. this:
ui_silence(
browse_github("usethis")
)
Legacy functions related to user interface
Description
These functions are now superseded. External users of the usethis::ui_*()
functions are encouraged to use the cli package
instead. The cli package did not have the required functionality when the
usethis::ui_*()
functions were created, but it has had that for a while
now and it's the superior option. There is even a cli vignette about how to
make this transition: vignette("usethis-ui", package = "cli")
.
usethis itself now uses cli internally for its UI, but these new functions are not exported and presumably never will be. There is a developer-focused article on the process of transitioning usethis's own UI to use cli: Converting usethis's UI to use cli.
Usage
ui_line(x = character(), .envir = parent.frame())
ui_todo(x, .envir = parent.frame())
ui_done(x, .envir = parent.frame())
ui_oops(x, .envir = parent.frame())
ui_info(x, .envir = parent.frame())
ui_code_block(x, copy = rlang::is_interactive(), .envir = parent.frame())
ui_stop(x, .envir = parent.frame())
ui_warn(x, .envir = parent.frame())
ui_field(x)
ui_value(x)
ui_path(x, base = NULL)
ui_code(x)
ui_unset(x = "unset")
Arguments
x |
A character vector. For block styles, conditions, and questions, each element of the
vector becomes a line, and the result is processed by |
.envir |
Used to ensure that |
copy |
If |
base |
If specified, paths will be displayed relative to this path. |
Details
The ui_
functions can be broken down into four main categories:
block styles:
ui_line()
,ui_done()
,ui_todo()
,ui_oops()
,ui_info()
.conditions:
ui_stop()
,ui_warn()
.inline styles:
ui_field()
,ui_value()
,ui_path()
,ui_code()
,ui_unset()
.
The question functions ui_yeah()
and ui_nope()
have their own help page.
All UI output (apart from ui_yeah()
/ui_nope()
prompts) can be silenced
by setting options(usethis.quiet = TRUE)
. Use ui_silence()
to silence
selected actions.
Value
The block styles, conditions, and questions are called for their side-effect. The inline styles return a string.
Examples
new_val <- "oxnard"
ui_done("{ui_field('name')} set to {ui_value(new_val)}")
ui_todo("Redocument with {ui_code('devtools::document()')}")
ui_code_block(c(
"Line 1",
"Line 2",
"Line 3"
))
User interface - Questions
Description
ui_yeah()
and ui_nope()
are technically superseded, but, unlike the rest
of the legacy ui_*()
functions, there's not yet a
drop-in replacement available in the cli package.
ui_yeah()
and ui_nope()
are no longer used internally in usethis.
Usage
ui_yeah(
x,
yes = c("Yes", "Definitely", "For sure", "Yup", "Yeah", "I agree", "Absolutely"),
no = c("No way", "Not now", "Negative", "No", "Nope", "Absolutely not"),
n_yes = 1,
n_no = 2,
shuffle = TRUE,
.envir = parent.frame()
)
ui_nope(
x,
yes = c("Yes", "Definitely", "For sure", "Yup", "Yeah", "I agree", "Absolutely"),
no = c("No way", "Not now", "Negative", "No", "Nope", "Absolutely not"),
n_yes = 1,
n_no = 2,
shuffle = TRUE,
.envir = parent.frame()
)
Arguments
x |
A character vector. For block styles, conditions, and questions, each element of the
vector becomes a line, and the result is processed by |
yes |
A character vector of "yes" strings, which are randomly sampled to populate the menu. |
no |
A character vector of "no" strings, which are randomly sampled to populate the menu. |
n_yes |
An integer. The number of "yes" strings to include. |
n_no |
An integer. The number of "no" strings to include. |
shuffle |
A logical. Should the order of the menu options be randomly shuffled? |
.envir |
Used to ensure that |
Value
A logical. ui_yeah()
returns TRUE
when the user selects a "yes"
option and FALSE
otherwise, i.e. when user selects a "no" option or
refuses to make a selection (cancels). ui_nope()
is the logical opposite
of ui_yeah()
.
Examples
## Not run:
ui_yeah("Do you like R?")
ui_nope("Have you tried turning it off and on again?", n_yes = 1, n_no = 1)
ui_yeah("Are you sure its plugged in?", yes = "Yes", no = "No", shuffle = FALSE)
## End(Not run)
Add minimal RStudio Addin binding
Description
This function helps you add a minimal
RStudio Addin binding to
inst/rstudio/addins.dcf
.
Usage
use_addin(addin = "new_addin", open = rlang::is_interactive())
Arguments
addin |
Name of the addin function, which should be defined in the
|
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
Add an author to the Authors@R
field in DESCRIPTION
Description
use_author()
adds a person to the Authors@R
field of the DESCRIPTION
file, creating that field if necessary. It will not modify, e.g., the role(s)
or email of an existing author (judged using their "Given Family" name). For
that we recommend editing DESCRIPTION directly. Or, for programmatic use,
consider calling the more specialized functions available in the desc
package directly.
use_author()
also surfaces two other situations you might want to address:
Explicit use of the fields
Author
orMaintainer
. We recommend switching to the more modernAuthors@R
field instead, because it offers richer metadata for various downstream uses. (Note thatAuthors@R
is eventually processed to createAuthor
andMaintainer
fields, but only when thetar.gz
is built from package source.)Presence of the fake author placed by
create_package()
anduse_description()
. This happens when usethis has to create a DESCRIPTION file and the user hasn't given any author information via thefields
argument or the global option"usethis.description"
. The placeholder looks something likeFirst Last <first.last@example.com> [aut, cre]
anduse_author()
offers to remove it in interactive sessions.
Usage
use_author(given = NULL, family = NULL, ..., role = "ctb")
Arguments
given |
a character vector with the given names, or a list thereof. |
family |
a character string with the family name, or a list thereof. |
... |
Arguments passed on to
|
role |
a character vector specifying the role(s) of the person (see Details), or a list thereof. |
Examples
## Not run:
use_author(
given = "Lucy",
family = "van Pelt",
role = c("aut", "cre"),
email = "lucy@example.com",
comment = c(ORCID = "LUCY-ORCID-ID")
)
use_author("Charlie", "Brown")
## End(Not run)
Don't save/load user workspace between sessions
Description
R can save and reload the user's workspace between sessions via an .RData
file in the current directory. However, long-term reproducibility is enhanced
when you turn this feature off and clear R's memory at every restart.
Starting with a blank slate provides timely feedback that encourages the
development of scripts that are complete and self-contained. More detail can
be found in the blog post Project-oriented workflow.
Usage
use_blank_slate(scope = c("user", "project"))
Arguments
scope |
Edit globally for the current user, or locally for the current project |
Add files to .Rbuildignore
Description
.Rbuildignore
has a regular expression on each line, but it's
usually easier to work with specific file names. By default,
use_build_ignore()
will (crudely) turn a filename into a regular
expression that will only match that path. Repeated entries will be
silently removed.
use_build_ignore()
is designed to ignore individual files. If you
want to ignore all files with a given extension, consider providing
an "as-is" regular expression, using escape = FALSE
; see examples.
Usage
use_build_ignore(files, escape = TRUE)
Arguments
files |
Character vector of path names. |
escape |
If |
Examples
## Not run:
# ignore all Excel files
use_build_ignore("[.]xlsx$", escape = FALSE)
## End(Not run)
Create a CITATION template
Description
Use this if you want to encourage users of your package to cite an article or book.
Usage
use_citation()
Add a code of conduct
Description
Adds a CODE_OF_CONDUCT.md
file to the active project and lists in
.Rbuildignore
, in the case of a package. The goal of a code of conduct is
to foster an environment of inclusiveness, and to explicitly discourage
inappropriate behaviour. The template comes from
https://www.contributor-covenant.org, version 2.1:
https://www.contributor-covenant.org/version/2/1/code_of_conduct/.
Usage
use_code_of_conduct(contact, path = NULL)
Arguments
contact |
Contact details for making a code of conduct report. Usually an email address. |
path |
Path of the directory to put |
Details
If your package is going to CRAN, the link to the CoC in your README must
be an absolute link to a rendered website as CODE_OF_CONDUCT.md
is not
included in the package sent to CRAN. use_code_of_conduct()
will
automatically generate this link if (1) you use pkgdown and (2) have set the
url
field in _pkgdown.yml
; otherwise it will link to a copy of the CoC
on https://www.contributor-covenant.org.
Helpers to download and unpack a ZIP file
Description
Details on the internal and helper functions that power use_course()
and
use_zip()
. Only create_download_url()
is exported.
Usage
tidy_download(url, destdir = getwd())
tidy_unzip(zipfile, cleanup = FALSE)
create_download_url(url)
Arguments
url |
A GitHub, DropBox, or Google Drive URL.
|
destdir |
Path to existing local directory where the ZIP file will be
stored. Defaults to current working directory, but note that |
zipfile |
Path to local ZIP file. |
cleanup |
Whether to delete the ZIP file after unpacking. In an
interactive session, |
tidy_download()
# how it's used inside use_course() tidy_download( # url has been processed with internal helper normalize_url() url, # conspicuous_place() = `getOption('usethis.destdir')` or desktop or home # directory or working directory destdir = destdir %||% conspicuous_place() )
Special-purpose function to download a ZIP file and automatically determine
the file name, which often determines the folder name after unpacking.
Developed with DropBox and GitHub as primary targets, possibly via
shortlinks. Both platforms offer a way to download an entire folder or repo
as a ZIP file, with information about the original folder or repo transmitted
in the Content-Disposition
header. In the absence of this header, a
filename is generated from the input URL. In either case, the filename is
sanitized. Returns the path to downloaded ZIP file, invisibly.
tidy_download()
is setup to retry after a download failure. In an
interactive session, it asks for user's consent. All retries use a longer
connect timeout.
DropBox
To make a folder available for ZIP download, create a shared link for it:
A shared link will have this form:
https://www.dropbox.com/sh/12345abcde/6789wxyz?dl=0
Replace the dl=0
at the end with dl=1
to create a download link:
https://www.dropbox.com/sh/12345abcde/6789wxyz?dl=1
You can use create_download_url()
to do this conversion.
This download link (or a shortlink that points to it) is suitable as input
for tidy_download()
. After one or more redirections, this link will
eventually lead to a download URL. For more details, see
https://help.dropbox.com/share/force-download and
https://help.dropbox.com/sync/download-entire-folders.
GitHub
Click on the repo's "Clone or download" button, to reveal a "Download ZIP" button. Capture this URL, which will have this form:
https://github.com/r-lib/usethis/archive/main.zip
This download link (or a shortlink that points to it) is suitable as input
for tidy_download()
. After one or more redirections, this link will
eventually lead to a download URL. Here are other links that also lead to
ZIP download, albeit with a different filenaming scheme (REF could be a
branch name, a tag, or a SHA):
https://github.com/github.com/r-lib/usethis/zipball/HEAD https://api.github.com/repos/r-lib/rematch2/zipball/REF https://api.github.com/repos/r-lib/rematch2/zipball/HEAD https://api.github.com/repos/r-lib/usethis/zipball/REF
You can use create_download_url()
to create the "Download ZIP" URL from
a typical GitHub browser URL.
Google Drive
To our knowledge, it is not possible to download a Google Drive folder as a ZIP archive. It is however possible to share a ZIP file stored on Google Drive. To get its URL, click on "Get the shareable link" (within the "Share" menu). This URL doesn't allow for direct download, as it's designed to be processed in a web browser first. Such a sharing link looks like:
https://drive.google.com/open?id=123456789xxyyyzzz
To be able to get the URL suitable for direct download, you need to extract the "id" element from the URL and include it in this URL format:
https://drive.google.com/uc?export=download&id=123456789xxyyyzzz
Use create_download_url()
to perform this transformation automatically.
tidy_unzip()
Special-purpose function to unpack a ZIP file and (attempt to) create the directory structure most people want. When unpacking an archive, it is easy to get one more or one less level of nesting than you expected.
It's especially important to finesse the directory structure here: we want the same local result when unzipping the same content from either GitHub or DropBox ZIP files, which pack things differently. Here is the intent:
If the ZIP archive
foo.zip
does not contain a single top-level directory, i.e. it is packed as "loose parts", unzip into a directory namedfoo
. Typical of DropBox ZIP files.If the ZIP archive
foo.zip
has a single top-level directory (which, by the way, is not necessarily called "foo"), unpack into said directory. Typical of GitHub ZIP files.
Returns path to the directory holding the unpacked files, invisibly.
DropBox:
The ZIP files produced by DropBox are special. The file list tends to contain
a spurious directory "/"
, which we ignore during unzip. Also, if the
directory is a Git repo and/or RStudio Project, we unzip-ignore various
hidden files, such as .RData
, .Rhistory
, and those below .git/
and
.Rproj.user
.
Examples
## Not run:
tidy_download("https://github.com/r-lib/rematch2/archive/main.zip")
tidy_unzip("rematch2-main.zip")
## End(Not run)
# GitHub
create_download_url("https://github.com/r-lib/usethis")
create_download_url("https://github.com/r-lib/usethis/issues")
# DropBox
create_download_url("https://www.dropbox.com/sh/12345abcde/6789wxyz?dl=0")
# Google Drive
create_download_url("https://drive.google.com/open?id=123456789xxyyyzzz")
create_download_url("https://drive.google.com/open?id=123456789xxyyyzzz/view")
Test coverage
Description
Adds test coverage reporting to a package, using either Codecov
(https://codecov.io
) or Coveralls (https://coveralls.io
).
Usage
use_coverage(type = c("codecov", "coveralls"), repo_spec = NULL)
use_covr_ignore(files)
Arguments
type |
Which web service to use. |
repo_spec |
Optional GitHub repo specification in this form: |
files |
Character vector of file globs. |
Use C++ via the cpp11 package
Description
Adds infrastructure needed to use the cpp11 package, a header-only R package that helps R package developers handle R objects with C++ code:
Creates
src/
Adds cpp11 to
DESCRIPTION
Creates
src/code.cpp
, an initial placeholder.cpp
file
Usage
use_cpp11()
CRAN submission comments
Description
Creates cran-comments.md
, a template for your communications with CRAN when
submitting a package. The goal is to clearly communicate the steps you have
taken to check your package on a wide range of operating systems. If you are
submitting an update to a package that is used by other packages, you also
need to summarize the results of your reverse dependency checks.
Usage
use_cran_comments(open = rlang::is_interactive())
Arguments
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
Create package data
Description
use_data()
makes it easy to save package data in the correct format. I
recommend you save scripts that generate package data in data-raw
: use
use_data_raw()
to set it up. You also need to document exported datasets.
Usage
use_data(
...,
internal = FALSE,
overwrite = FALSE,
compress = "bzip2",
version = 3,
ascii = FALSE
)
use_data_raw(name = "DATASET", open = rlang::is_interactive())
Arguments
... |
Unquoted names of existing objects to save. |
internal |
If If |
overwrite |
By default, |
compress |
Choose the type of compression used by |
version |
The serialization format version to use. The default, 3, can only be read by R versions 3.5.0 and higher. For R 1.4.0 to 3.5.3, use version 2. |
ascii |
if |
name |
Name of the dataset to be prepared for inclusion in the package. |
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
See Also
The data chapter of R Packages.
Examples
## Not run:
x <- 1:10
y <- 1:100
use_data(x, y) # For external use
use_data(x, y, internal = TRUE) # For internal use
## End(Not run)
## Not run:
use_data_raw("daisy")
## End(Not run)
Prepare for importing data.table
Description
use_data_table()
imports the data.table()
function from the data.table
package, as well as several important symbols: :=
, .SD
, .BY
, .N
,
.I
, .GRP
, .NGRP
, .EACHI
. This is a minimal setup and you can learn
much more in the "Importing data.table" vignette:
https://rdatatable.gitlab.io/data.table/articles/datatable-importing.html
.
In addition to importing these functions, use_data_table()
also blocks the
usage of data.table in the Depends
field of the DESCRIPTION
file;
data.table
should be used as an imported or suggested package only. See
this discussion.
Usage
use_data_table()
Create or modify a DESCRIPTION file
Description
use_description()
creates a DESCRIPTION
file. Although mostly associated
with R packages, a DESCRIPTION
file can also be used to declare
dependencies for a non-package project. Within such a project,
devtools::install_deps()
can then be used to install all the required
packages. Note that, by default, use_decription()
checks for a
CRAN-compliant package name. You can turn this off with check_name = FALSE
.
usethis consults the following sources, in this order, to set DESCRIPTION
fields:
-
fields
argument ofcreate_package()
oruse_description()
-
getOption("usethis.description")
Defaults built into usethis
The fields discovered via options or the usethis package can be viewed with
use_description_defaults()
.
If you create a lot of packages, consider storing personalized defaults as a
named list in an option named "usethis.description"
. Here's an example of
code to include in .Rprofile
, which can be opened via edit_r_profile()
:
options( usethis.description = list( "Authors@R" = utils::person( "Jane", "Doe", email = "jane@example.com", role = c("aut", "cre"), comment = c(ORCID = "YOUR-ORCID-ID") ), Language = "es", License = "MIT + file LICENSE" ) )
Prior to usethis v2.0.0, getOption("devtools.desc")
was consulted for
backwards compatibility, but now only the "usethis.description"
option is
supported.
Usage
use_description(fields = list(), check_name = TRUE, roxygen = TRUE)
use_description_defaults(package = NULL, roxygen = TRUE, fields = list())
Arguments
fields |
A named list of fields to add to |
check_name |
Whether to check if the name is valid for CRAN and throw an error if not. |
roxygen |
If |
package |
Package name |
See Also
The description chapter of R Packages
Examples
## Not run:
use_description()
use_description(fields = list(Language = "es"))
use_description_defaults()
## End(Not run)
Use a directory
Description
use_directory()
creates a directory (if it does not already exist) in the
project's top-level directory. This function powers many of the other use_
functions such as use_data()
and use_vignette()
.
Usage
use_directory(path, ignore = FALSE)
Arguments
path |
Path of the directory to create, relative to the project. |
ignore |
Should the newly created file be added to |
Examples
## Not run:
use_directory("inst")
## End(Not run)
Initialise a git repository
Description
use_git()
initialises a Git repository and adds important files to
.gitignore
. If user consents, it also makes an initial commit.
Usage
use_git(message = "Initial commit")
Arguments
message |
Message to use for first commit. |
See Also
Other git helpers:
use_git_config()
,
use_git_hook()
,
use_git_ignore()
Examples
## Not run:
use_git()
## End(Not run)
Configure Git
Description
Sets Git options, for either the user or the project ("global" or "local", in
Git terminology). Wraps gert::git_config_set()
and
gert::git_config_global_set()
. To inspect Git config, see
gert::git_config()
.
Usage
use_git_config(scope = c("user", "project"), ...)
Arguments
scope |
Edit globally for the current user, or locally for the current project |
... |
Name-value pairs, processed as
< |
Value
Invisibly, the previous values of the modified components, as a named list.
See Also
Other git helpers:
use_git()
,
use_git_hook()
,
use_git_ignore()
Examples
## Not run:
# set the user's global user.name and user.email
use_git_config(user.name = "Jane", user.email = "jane@example.org")
# set the user.name and user.email locally, i.e. for current repo/project
use_git_config(
scope = "project",
user.name = "Jane",
user.email = "jane@example.org"
)
## End(Not run)
Add a git hook
Description
Sets up a git hook using the specified script. Creates a hook directory if needed, and sets correct permissions on hook.
Usage
use_git_hook(hook, script)
Arguments
hook |
Hook name. One of "pre-commit", "prepare-commit-msg", "commit-msg", "post-commit", "applypatch-msg", "pre-applypatch", "post-applypatch", "pre-rebase", "post-rewrite", "post-checkout", "post-merge", "pre-push", "pre-auto-gc". |
script |
Text of script to run |
See Also
Other git helpers:
use_git()
,
use_git_config()
,
use_git_ignore()
Tell Git to ignore files
Description
Tell Git to ignore files
Usage
use_git_ignore(ignores, directory = ".")
Arguments
ignores |
Character vector of ignores, specified as file globs. |
directory |
Directory relative to active project to set ignores |
See Also
Other git helpers:
use_git()
,
use_git_config()
,
use_git_hook()
Configure and report Git remotes
Description
Two helpers are available:
-
use_git_remote()
sets the remote associated withname
tourl
. -
git_remotes()
reports the configured remotes, similar togit remote -v
.
Usage
use_git_remote(name = "origin", url, overwrite = FALSE)
git_remotes()
Arguments
name |
A string giving the short name of a remote. |
url |
A string giving the url of a remote. |
overwrite |
Logical. Controls whether an existing remote can be modified. |
Value
Named list of Git remotes.
Examples
## Not run:
# see current remotes
git_remotes()
# add new remote named 'foo', a la `git remote add <name> <url>`
use_git_remote(name = "foo", url = "https://github.com/<OWNER>/<REPO>.git")
# remove existing 'foo' remote, a la `git remote remove <name>`
use_git_remote(name = "foo", url = NULL, overwrite = TRUE)
# change URL of remote 'foo', a la `git remote set-url <name> <newurl>`
use_git_remote(
name = "foo",
url = "https://github.com/<OWNER>/<REPO>.git",
overwrite = TRUE
)
# Scenario: Fix remotes when you cloned someone's repo, but you should
# have fork-and-cloned (in order to make a pull request).
# Store origin = main repo's URL, e.g., "git@github.com:<OWNER>/<REPO>.git"
upstream_url <- git_remotes()[["origin"]]
# IN THE BROWSER: fork the main GitHub repo and get your fork's remote URL
my_url <- "git@github.com:<ME>/<REPO>.git"
# Rotate the remotes
use_git_remote(name = "origin", url = my_url)
use_git_remote(name = "upstream", url = upstream_url)
git_remotes()
# Scenario: Add upstream remote to a repo that you fork-and-cloned, so you
# can pull upstream changes.
# Note: If you fork-and-clone via `usethis::create_from_github()`, this is
# done automatically!
# Get URL of main GitHub repo, probably in the browser
upstream_url <- "git@github.com:<OWNER>/<REPO>.git"
use_git_remote(name = "upstream", url = upstream_url)
## End(Not run)
Connect a local repo with GitHub
Description
use_github()
takes a local project and:
Checks that the initial state is good to go:
Project is already a Git repo
Current branch is the default branch, e.g.
main
ormaster
No uncommitted changes
No pre-existing
origin
remote
Creates an associated repo on GitHub
Adds that GitHub repo to your local repo as the
origin
remoteMakes an initial push to GitHub
Calls
use_github_links()
, if the project is an R packageConfigures
origin/DEFAULT
to be the upstream branch of the localDEFAULT
branch, e.g.main
ormaster
See below for the authentication setup that is necessary for all of this to work.
Usage
use_github(
organisation = NULL,
private = FALSE,
visibility = c("public", "private", "internal"),
protocol = git_protocol(),
host = NULL
)
Arguments
organisation |
If supplied, the repo will be created under this
organisation, instead of the login associated with the GitHub token
discovered for this |
private |
If |
visibility |
Only relevant for organisation-owned repos associated with
certain GitHub Enterprise products. The special "internal" |
protocol |
One of "https" or "ssh" |
host |
GitHub host to target, passed to the For a hypothetical GitHub Enterprise instance, either "https://github.acme.com/api/v3" or "https://github.acme.com" is acceptable. |
Git/GitHub Authentication
Many usethis functions, including those documented here, potentially interact with GitHub in two different ways:
Via the GitHub REST API. Examples: create a repo, a fork, or a pull request.
As a conventional Git remote. Examples: clone, fetch, or push.
Therefore two types of auth can happen and your credentials must be discoverable. Which credentials do we mean?
A GitHub personal access token (PAT) must be discoverable by the gh package, which is used for GitHub operations via the REST API. See
gh_token_help()
for more about getting and configuring a PAT.If you use the HTTPS protocol for Git remotes, your PAT is also used for Git operations, such as
git push
. Usethis uses the gert package for this, so the PAT must be discoverable by gert. Generally gert and gh will discover and use the same PAT. This ability to "kill two birds with one stone" is why HTTPS + PAT is our recommended auth strategy for those new to Git and GitHub and PRs.If you use SSH remotes, your SSH keys must also be discoverable, in addition to your PAT. The public key must be added to your GitHub account.
Git/GitHub credential management is covered in a dedicated article: Managing Git(Hub) Credentials
Examples
## Not run:
pkgpath <- file.path(tempdir(), "testpkg")
create_package(pkgpath)
## now, working inside "testpkg", initialize git repository
use_git()
## create github repository and configure as git remote
use_github()
## End(Not run)
Set up a GitHub Actions workflow
Description
Sets up continuous integration (CI) for an R package that is developed on
GitHub using GitHub Actions. CI can be
used to trigger various operations for each push or pull request, e.g.
running R CMD check
or building and deploying a pkgdown site.
Workflows
There are four particularly important workflows that are used by many packages:
-
check-standard
: RunR CMD check
using R-latest on Linux, Mac, and Windows, and using R-devel and R-oldrel on Linux. This is a good baseline if you plan on submitting your package to CRAN. -
test-coverage
: Compute test coverage and report to https://about.codecov.io by callingcovr::codecov()
. -
pkgdown
: Automatically build and publish a pkgdown website. But we recommend instead callinguse_pkgdown_github_pages()
which performs other important set up. -
pr-commands
: Enables the use of two R-specific commands in pull request issue comments:/document
to runroxygen2::roxygenise()
and/style
to runstyler::style_pkg()
. Both will update the PR with any changes once they're done.
If you call use_github_action()
without arguments, you'll be prompted to
pick from one of these. Otherwise you can see a complete list of
possibilities provided by r-lib at
https://github.com/r-lib/actions/tree/v2/examples, or you can supply
your own url
to use any other workflow.
Usage
use_github_action(
name = NULL,
ref = NULL,
url = NULL,
save_as = NULL,
readme = NULL,
ignore = TRUE,
open = FALSE,
badge = NULL
)
Arguments
name |
For If the |
ref |
Desired Git reference, usually the name of a tag ( |
url |
The full URL to a |
save_as |
Name of the local workflow file. Defaults to |
readme |
The full URL to a |
ignore |
Should the newly created file be added to |
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
badge |
Should we add a badge to the |
Examples
## Not run:
use_github_action()
use_github_action_check_standard()
use_github_action("pkgdown")
## End(Not run)
Deprecated GitHub Actions functions
Description
-
use_github_actions()
is deprecated because it was just an alias foruse_github_action_check_release()
. -
use_github_action_check_full()
is overkill for most packages and is not recommended. -
use_github_action_check_release()
,use_github_action_check_standard()
, anduse_github_action_pr_commands()
are deprecated in favor ofuse_github_action()
, which can now suggest specific workflows to use.
Usage
use_github_actions()
use_github_action_check_release(
save_as = "R-CMD-check.yaml",
ref = NULL,
ignore = TRUE,
open = FALSE
)
use_github_action_check_standard(
save_as = "R-CMD-check.yaml",
ref = NULL,
ignore = TRUE,
open = FALSE
)
use_github_action_pr_commands(
save_as = "pr-commands.yaml",
ref = NULL,
ignore = TRUE,
open = FALSE
)
use_github_action_check_full(
save_as = "R-CMD-check.yaml",
ignore = TRUE,
open = FALSE,
repo_spec = NULL
)
Generates a GitHub Actions badge
Description
Generates a GitHub Actions badge and that's all. This exists primarily for internal use.
Usage
use_github_actions_badge(name = "R-CMD-check.yaml", repo_spec = NULL)
Arguments
name |
Name of the workflow's YAML configuration file (with or without
extension), e.g. |
Copy a file from any GitHub repo into the current project
Description
Gets the content of a file from GitHub, from any repo the user can read, and writes it into the active project. This function wraps an endpoint of the GitHub API which supports specifying a target reference (i.e. branch, tag, or commit) and which follows symlinks.
Usage
use_github_file(
repo_spec,
path = NULL,
save_as = NULL,
ref = NULL,
ignore = FALSE,
open = FALSE,
overwrite = FALSE,
host = NULL
)
Arguments
repo_spec |
A string identifying the GitHub repo or, alternatively, a GitHub file URL. Acceptable forms:
In the case of a URL, the |
path |
Path of file to copy, relative to the GitHub repo it lives in.
This is extracted from |
save_as |
Path of file to create, relative to root of active project.
Defaults to the last part of |
ref |
The name of a branch, tag, or commit. By default, the file at
|
ignore |
Should the newly created file be added to |
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
overwrite |
Force overwrite of existing file? |
host |
GitHub host to target, passed to the For a hypothetical GitHub Enterprise instance, either "https://github.acme.com/api/v3" or "https://github.acme.com" is acceptable. |
Value
A logical indicator of whether a file was written, invisibly.
Examples
## Not run:
use_github_file(
"https://github.com/r-lib/actions/blob/v2/examples/check-standard.yaml"
)
use_github_file(
"r-lib/actions",
path = "examples/check-standard.yaml",
ref = "v2",
save_as = ".github/workflows/R-CMD-check.yaml"
)
## End(Not run)
Manage GitHub issue labels
Description
use_github_labels()
can create new labels, update colours and descriptions,
and optionally delete GitHub's default labels (if delete_default = TRUE
).
It will never delete labels that have associated issues.
use_tidy_github_labels()
calls use_github_labels()
with tidyverse
conventions powered by tidy_labels()
, tidy_labels_rename()
,
tidy_label_colours()
and tidy_label_descriptions()
.
tidyverse label usage
Labels are used as part of the issue-triage process, designed to minimise the time spent re-reading issues. The absence of a label indicates that an issue is new, and has yet to be triaged.
There are four mutually exclusive labels that indicate the overall "type" of issue:
-
bug
: an unexpected problem or unintended behavior. -
documentation
: requires changes to the docs. -
feature
: feature requests and enhancement. -
upkeep
: general package maintenance work that makes future development easier.
Then there are five labels that are needed in most repositories:
-
breaking change
: issue/PR will requires a breaking change so should be not be included in patch releases. -
reprex
indicates that an issue does not have a minimal reproducible example, and that a reply has been sent requesting one from the user. -
good first issue
indicates a good issue for first-time contributors. -
help wanted
indicates that a maintainer wants help on an issue. -
wip
indicates that someone is working on it or has promised to.
Finally most larger repos will accumulate their own labels for specific areas of functionality. For example, usethis has labels like "description", "paths", "readme", because time has shown these to be common sources of problems. These labels are helpful for grouping issues so that you can tackle related problems at the same time.
Repo-specific issues should have a grey background (#eeeeee
) and an emoji.
This keeps the issue page visually harmonious while still giving enough
variation to easily distinguish different types of label.
Usage
use_github_labels(
labels = character(),
rename = character(),
colours = character(),
descriptions = character(),
delete_default = FALSE
)
use_tidy_github_labels()
tidy_labels()
tidy_labels_rename()
tidy_label_colours()
tidy_label_descriptions()
Arguments
labels |
A character vector giving labels to add. |
rename |
A named vector with names giving old names and values giving new names. |
colours , descriptions |
Named character vectors giving hexadecimal
colours (like |
delete_default |
If |
Examples
## Not run:
# typical use in, e.g., a new tidyverse project
use_github_labels(delete_default = TRUE)
# create labels without changing colours/descriptions
use_github_labels(
labels = c("foofy", "foofier", "foofiest"),
colours = NULL,
descriptions = NULL
)
# change descriptions without changing names/colours
use_github_labels(
labels = NULL,
colours = NULL,
descriptions = c("foofiest" = "the foofiest issue you ever saw")
)
## End(Not run)
Use GitHub links in URL and BugReports
Description
Populates the URL
and BugReports
fields of a GitHub-using R package with
appropriate links. The GitHub repo to link to is determined from the current
project's GitHub remotes:
If we are not working with a fork, this function expects
origin
to be a GitHub remote and the links target that repo.If we are working in a fork, this function expects to find two GitHub remotes:
origin
(the fork) andupstream
(the fork's parent) remote. In an interactive session, the user can confirm which repo to use for the links. In a noninteractive session, links are formed usingupstream
.
Usage
use_github_links(overwrite = FALSE)
Arguments
overwrite |
By default, |
Examples
## Not run:
use_github_links()
## End(Not run)
Configure a GitHub Pages site
Description
Activates or reconfigures a GitHub Pages site for a project hosted on GitHub. This function anticipates two specific usage modes:
Publish from the root directory of a
gh-pages
branch, which is assumed to be only (or at least primarily) a remote branch. Typically thegh-pages
branch is managed by an automatic "build and deploy" job, such as the one configured byuse_github_action("pkgdown")
.Publish from the
"/docs"
directory of a "regular" branch, probably the repo's default branch. The user is assumed to have a plan for how they will manage the content below"/docs"
.
Usage
use_github_pages(branch = "gh-pages", path = "/", cname = NA)
Arguments
branch , path |
Branch and path for the site source. The default of
The most common alternative is to use the repo's default branch, coupled
with Note that GitHub does not support an arbitrary |
cname |
Optional, custom domain name. The Note that this can add or modify a CNAME file in your repository. If you are using Pages to host a pkgdown site, it is better to specify its URL in the pkgdown config file and let pkgdown manage CNAME. |
Value
Site metadata returned by the GitHub API, invisibly
See Also
-
use_pkgdown_github_pages()
combinesuse_github_pages()
with other functions to fully configure a pkgdown site
Examples
## Not run:
use_github_pages()
use_github_pages(branch = git_default_branch(), path = "/docs")
## End(Not run)
Publish a GitHub release
Description
Pushes the current branch (if safe) then publishes a GitHub release for the latest CRAN submission.
If you use devtools::submit_cran()
to submit to CRAN, information about the
submitted state is captured in a CRAN-SUBMISSION
file.
use_github_release()
uses this info to populate the GitHub release notes
and, after success, deletes the file. In the absence of such a file, we
assume that current state (SHA of HEAD
, package version, NEWS) is the
submitted state.
Usage
use_github_release(publish = TRUE)
Arguments
publish |
If |
Continuous integration setup and badges
Description
These functions are not actively used by the tidyverse team, and may not currently work. Use at your own risk.
Sets up third-party continuous integration (CI) services for an R package on GitLab or CircleCI. These functions:
Add service-specific configuration files and add them to
.Rbuildignore
.Activate a service or give the user a detailed prompt.
Provide the markdown to insert a badge into README.
Usage
use_gitlab_ci()
use_circleci(browse = rlang::is_interactive(), image = "rocker/verse:latest")
use_circleci_badge(repo_spec = NULL)
Arguments
browse |
Open a browser window to enable automatic builds for the package. |
image |
The Docker image to use for build. Must be available on
DockerHub. The
rocker/verse image includes
TeXLive, pandoc, and the tidyverse packages. For a minimal image, try
rocker/r-ver. To specify a version
of R, change the tag from |
repo_spec |
Optional GitHub repo specification in this form: |
use_gitlab_ci()
Adds a basic .gitlab-ci.yml
to the top-level directory of a package. This
is a configuration file for the GitLab CI/CD continuous integration service.
use_circleci()
Adds a basic .circleci/config.yml
to the top-level directory of a package.
This is a configuration file for the CircleCI
continuous integration service.
use_circleci_badge()
Only adds the Circle CI badge. Use for a project where Circle CI is already configured.
Import a function from another package
Description
use_import_from()
imports a function from another package by adding the
roxygen2 @importFrom
tag to the package-level documentation (which can be
created with use_package_doc()
). Importing a function from another
package allows you to refer to it without a namespace (e.g., fun()
instead
of package::fun()
).
use_import_from()
also re-documents the NAMESPACE, and re-load the current
package. This ensures that fun
is immediately available in your development
session.
Usage
use_import_from(package, fun, load = is_interactive())
Arguments
package |
Package name |
fun |
A vector of function names |
load |
Logical. Re-load with |
Value
Invisibly, TRUE
if the package document has changed, FALSE
if not.
Examples
## Not run:
use_import_from("glue", "glue")
## End(Not run)
Create Jenkinsfile for Jenkins CI Pipelines
Description
use_jenkins()
adds a basic Jenkinsfile for R packages to the project root
directory. The Jenkinsfile stages take advantage of calls to make
, and so
calling this function will also run use_make()
if a Makefile does not
already exist at the project root.
Usage
use_jenkins()
See Also
The documentation on Jenkins Pipelines.
Use "latest" versions of all dependencies
Description
Pins minimum versions of all Imports
and Depends
dependencies to latest
ones (as determined by source
). Useful for the tidyverse package, but
should otherwise be used with extreme care.
Usage
use_latest_dependencies(overwrite = TRUE, source = c("CRAN", "local"))
Arguments
overwrite |
By default ( |
source |
Use "CRAN" or "local" package versions. |
Use lifecycle badges
Description
This helper:
Adds lifecycle as a dependency.
Imports
lifecycle::deprecated()
for use in function arguments.Copies the lifecycle badges into
man/figures
.Reminds you how to use the badge syntax.
Learn more at https://lifecycle.r-lib.org/articles/communicate.html
Usage
use_lifecycle()
See Also
use_lifecycle_badge()
to signal the
lifecycle stage of
your package as whole
Use a package logo
Description
This function helps you use a logo in your package:
Enforces a specific size
Stores logo image file at
man/figures/logo.png
Produces the markdown text you need in README to include the logo
Usage
use_logo(img, geometry = "240x278", retina = TRUE)
Arguments
img |
The path to an existing image file |
geometry |
a magick::geometry string specifying size. The default assumes that you have a hex logo using spec from http://hexb.in/sticker.html. |
retina |
|
Examples
## Not run:
use_logo("usethis.png")
## End(Not run)
Create Makefile
Description
use_make()
adds a basic Makefile to the project root directory.
Usage
use_make()
See Also
The documentation for GNU Make.
Use a basic NAMESPACE
Description
If roxygen
is TRUE
generates an empty NAMESPACE
that exports nothing;
you'll need to explicitly export functions with @export
. If roxygen
is FALSE
, generates a default NAMESPACE
that exports all functions
except those that start with .
.
Usage
use_namespace(roxygen = TRUE)
Arguments
roxygen |
Do you plan to manage |
See Also
The namespace chapter of R Packages.
Create a simple NEWS.md
Description
This creates a basic NEWS.md
in the root directory.
Usage
use_news_md(open = rlang::is_interactive())
Arguments
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
See Also
The other markdown files section of R Packages.
Depend on another package
Description
use_package()
adds a CRAN package dependency to DESCRIPTION
and offers a
little advice about how to best use it. use_dev_package()
adds a dependency
on an in-development package, adding the dev repo to Remotes
so it will be
automatically installed from the correct location. There is no helper to
remove a dependency: to do that, simply remove that package from your
DESCRIPTION
file.
use_package()
exists to support a couple of common maneuvers:
Add a dependency to
Imports
orSuggests
orLinkingTo
.Add a minimum version to a dependency.
Specify the minimum supported version for R.
use_package()
probably works for slightly more exotic modifications, but at
some point, you should edit DESCRIPTION
yourself by hand. There is no
intention to account for all possible edge cases.
Usage
use_package(package, type = "Imports", min_version = NULL)
use_dev_package(package, type = "Imports", remote = NULL)
Arguments
package |
Name of package to depend on. |
type |
Type of dependency: must be one of "Imports", "Depends", "Suggests", "Enhances", or "LinkingTo" (or unique abbreviation). Matching is case insensitive. |
min_version |
Optionally, supply a minimum version for the package. Set
to |
remote |
By default, an |
See Also
The dependencies section of R Packages.
Examples
## Not run:
use_package("ggplot2")
use_package("dplyr", "suggests")
use_dev_package("glue")
# Depend on R version 4.1
use_package("R", type = "Depends", min_version = "4.1")
## End(Not run)
Package-level documentation
Description
Adds a dummy .R
file that will cause roxygen2 to generate basic
package-level documentation. If your package is named "foo", this will make
help available to the user via ?foo
or package?foo
. Once you call
devtools::document()
, roxygen2 will flesh out the .Rd
file using data
from the DESCRIPTION
. That ensures you don't need to repeat (and remember
to update!) the same information in multiple places. This .R
file is also a
good place for roxygen directives that apply to the whole package (vs. a
specific function), such as global namespace tags like @importFrom
.
Usage
use_package_doc(open = rlang::is_interactive())
Arguments
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
See Also
The documentation chapter of R Packages
Use magrittr's pipe in your package
Description
Does setup necessary to use magrittr's pipe operator, %>%
in your package.
This function requires the use of roxygen2.
Adds magrittr to "Imports" in
DESCRIPTION
.Imports the pipe operator specifically, which is necessary for internal use.
Exports the pipe operator, if
export = TRUE
, which is necessary to make%>%
available to the users of your package.
Usage
use_pipe(export = TRUE)
Arguments
export |
If |
Examples
## Not run:
use_pipe()
## End(Not run)
Use pkgdown
Description
pkgdown makes it easy to turn your package into a beautiful website. usethis provides two functions to help you use pkgdown:
-
use_pkgdown()
: creates a pkgdown config file and adds relevant files or directories to.Rbuildignore
and.gitignore
. -
use_pkgdown_github_pages()
: implements the GitHub setup needed to automatically publish your pkgdown site to GitHub pages:(first, it calls
use_pkgdown()
)-
use_github_pages()
prepares to publish the pkgdown site from thegh-pages
branch -
use_github_action("pkgdown")
configures a GitHub Action to automatically build the pkgdown site and deploy it via GitHub Pages The pkgdown site's URL is added to the pkgdown configuration file, to the URL field of DESCRIPTION, and to the GitHub repo.
Packages owned by certain GitHub organizations (tidyverse, r-lib, and tidymodels) get some special treatment, in terms of anticipating the (eventual) site URL and the use of a pkgdown template.
Usage
use_pkgdown(config_file = "_pkgdown.yml", destdir = "docs")
use_pkgdown_github_pages()
Arguments
config_file |
Path to the pkgdown yaml config file, relative to the project. |
destdir |
Target directory for pkgdown docs. |
See Also
https://pkgdown.r-lib.org/articles/pkgdown.html#configuration
Create or edit R or test files
Description
This pair of functions makes it easy to create paired R and test files,
using the convention that the tests for R/foofy.R
should live
in tests/testthat/test-foofy.R
. You can use them to create new files
from scratch by supplying name
, or if you use RStudio, you can call
to create (or navigate to) the companion file based on the currently open
file. This also works when a test snapshot file is active, i.e. if you're
looking at tests/testthat/_snaps/foofy.md
, use_r()
or use_test()
take
you to R/foofy.R
or tests/testthat/test-foofy.R
, respectively.
Usage
use_r(name = NULL, open = rlang::is_interactive())
use_test(name = NULL, open = rlang::is_interactive())
Arguments
name |
Either a string giving a file name (without directory) or
|
open |
Whether to open the file for interactive editing. |
Renaming files in an existing package
Here are some tips on aligning file names across R/
and tests/testthat/
in an existing package that did not necessarily follow this convention
before.
This script generates a data frame of R/
and test files that can help you
identify missed opportunities for pairing:
library(fs) library(tidyverse) bind_rows( tibble( type = "R", path = dir_ls("R/", regexp = "\\.[Rr]$"), name = as.character(path_ext_remove(path_file(path))), ), tibble( type = "test", path = dir_ls("tests/testthat/", regexp = "/test[^/]+\\.[Rr]$"), name = as.character(path_ext_remove(str_remove(path_file(path), "^test[-_]"))), ) ) %>% pivot_wider(names_from = type, values_from = path) %>% print(n = Inf)
The rename_files()
function can also be helpful.
See Also
The testing and R code chapters of R Packages.
-
use_test_helper()
to create a testthat helper file.
Examples
## Not run:
# create a new .R file below R/
use_r("coolstuff")
# if `R/coolstuff.R` is active in a supported IDE, you can now do:
use_test()
# if `tests/testthat/test-coolstuff.R` is active in a supported IDE, you can
# return to `R/coolstuff.R` with:
use_r()
## End(Not run)
Use C, C++, RcppArmadillo, or RcppEigen
Description
Adds infrastructure commonly needed when using compiled code:
Creates
src/
Adds required packages to
DESCRIPTION
May create an initial placeholder
.c
or.cpp
fileCreates
Makevars
andMakevars.win
files (use_rcpp_armadillo()
only)
Usage
use_rcpp(name = NULL)
use_rcpp_armadillo(name = NULL)
use_rcpp_eigen(name = NULL)
use_c(name = NULL)
Arguments
name |
Either a string giving a file name (without directory) or
|
Create README files
Description
Creates skeleton README files with possible stubs for
a high-level description of the project/package and its goals
R code to install from GitHub, if GitHub usage detected
a basic example
Use Rmd
if you want a rich intermingling of code and output. Use md
for a
basic README. README.Rmd
will be automatically added to .Rbuildignore
.
The resulting README is populated with default YAML frontmatter and R fenced
code blocks (md
) or chunks (Rmd
).
If you use Rmd
, you'll still need to render it regularly, to keep
README.md
up-to-date. devtools::build_readme()
is handy for this. You
could also use GitHub Actions to re-render README.Rmd
every time you push.
An example workflow can be found in the examples/
directory here:
https://github.com/r-lib/actions/.
If the current project is a Git repo, then use_readme_rmd()
automatically
configures a pre-commit hook that helps keep README.Rmd
and README.md
,
synchronized. The hook creates friction if you try to commit when
README.Rmd
has been edited more recently than README.md
. If this hook
causes more problems than it solves for you, it is implemented in
.git/hooks/pre-commit
, which you can modify or even delete.
Usage
use_readme_rmd(open = rlang::is_interactive())
use_readme_md(open = rlang::is_interactive())
Arguments
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
See Also
The other markdown files section of R Packages.
Examples
## Not run:
use_readme_rmd()
use_readme_md()
## End(Not run)
Create a release checklist in a GitHub issue
Description
When preparing to release a package to CRAN there are quite a few steps that need to be performed, and some of the steps can take multiple hours. This function creates a checklist in a GitHub issue to:
Help you keep track of where you are in the process
Feel a sense of satisfaction as you progress towards final submission
Help watchers of your package stay informed.
The checklist contains a generic set of steps that we've found to be helpful, based on the type of release ("patch", "minor", or "major"). You're encouraged to edit the issue to customize this list to meet your needs.
Customization
If you want to consistently add extra bullets for every release, you can include your own custom bullets by providing an (unexported)
release_bullets()
function that returns a character vector. (For historical reasons,release_questions()
is also supported).If you want to check additional packages in the revdep check process, provide an (unexported)
release_extra_revdeps()
function that returns a character vector. This is currently only supported for Posit internal check tooling.
Usage
use_release_issue(version = NULL)
Arguments
version |
Optional version number for release. If unspecified, you can make an interactive choice. |
Examples
## Not run:
use_release_issue("2.0.0")
## End(Not run)
Reverse dependency checks
Description
Performs set up for checking the reverse dependencies of an R package, as implemented by the revdepcheck package:
Creates
revdep/
directory and adds it to.Rbuildignore
Populates
revdep/.gitignore
to prevent tracking of various revdep artefactsPrompts user to run the checks with
revdepcheck::revdep_check()
Usage
use_revdep()
Add an RMarkdown Template
Description
Adds files and directories necessary to add a custom rmarkdown template to RStudio. It creates:
-
inst/rmarkdown/templates/{{template_dir}}
. Main directory. -
skeleton/skeleton.Rmd
. Your template Rmd file. -
template.yml
with basic information filled in.
Usage
use_rmarkdown_template(
template_name = "Template Name",
template_dir = NULL,
template_description = "A description of the template",
template_create_dir = FALSE
)
Arguments
template_name |
The name as printed in the template menu. |
template_dir |
Name of the directory the template will live in within
|
template_description |
Sets the value of |
template_create_dir |
Sets the value of |
Examples
## Not run:
use_rmarkdown_template()
## End(Not run)
Use roxygen2 with markdown
Description
If you are already using roxygen2, but not with markdown, you'll need to use roxygen2md to convert existing Rd expressions to markdown. The conversion is not perfect, so make sure to check the results.
Usage
use_roxygen_md(overwrite = FALSE)
Arguments
overwrite |
Whether to overwrite an existing |
Deprecated badge function
Description
use_rscloud_badge()
has been replaced by use_posit_cloud_badge()
.
Usage
use_rscloud_badge(url)
Add RStudio Project infrastructure
Description
It is likely that you want to use create_project()
or create_package()
instead of use_rstudio()
! Both create_*()
functions can add RStudio
Project infrastructure to a pre-existing project or package. use_rstudio()
is mostly for internal use or for those creating a usethis-like package for
their organization. It does the following in the current project, often after
executing proj_set(..., force = TRUE)
:
Creates an
.Rproj
fileAdds RStudio files to
.gitignore
Adds RStudio files to
.Rbuildignore
, if project is a package
Usage
use_rstudio(line_ending = c("posix", "windows"), reformat = TRUE)
Arguments
line_ending |
Line ending |
reformat |
If If |
Set global RStudio preferences
Description
This function allows you to set global RStudio preferences, achieving the same effect programmatically as clicking buttons in RStudio's Global Options. You can find a list of configurable properties at https://docs.posit.co/ide/server-pro/reference/session_user_settings.html.
Usage
use_rstudio_preferences(...)
Arguments
... |
< |
Value
A named list of the previous values, invisibly.
Use spell check
Description
Adds a unit test to automatically run a spell check on documentation and,
optionally, vignettes during R CMD check
, using the
spelling package. Also adds a WORDLIST
file to the package, which is a dictionary of whitelisted words. See
spelling::wordlist for details.
Usage
use_spell_check(vignettes = TRUE, lang = "en-US", error = FALSE)
Arguments
vignettes |
Logical, |
lang |
Preferred spelling language. Usually either |
error |
Logical, indicating whether the unit test should fail if
spelling errors are found. Defaults to |
Use a standalone file from another repo
Description
A "standalone" file implements a minimum set of functionality in such a way
that it can be copied into another package. use_standalone()
makes it easy
to get such a file into your own repo.
It always overwrites an existing standalone file of the same name, making it easy to update previously imported code.
Usage
use_standalone(repo_spec, file = NULL, ref = NULL, host = NULL)
Arguments
repo_spec |
A string identifying the GitHub repo in one of these forms:
|
file |
Name of standalone file. The |
ref |
The name of a branch, tag, or commit. By default, the file at
|
host |
GitHub host to target, passed to the If unspecified, gh defaults to "https://api.github.com", although gh's default can be customised by setting the GITHUB_API_URL environment variable. For a hypothetical GitHub Enterprise instance, either "https://github.acme.com/api/v3" or "https://github.acme.com" is acceptable. |
Supported fields
A standalone file has YAML frontmatter that provides additional information, such as where the file originates from and when it was last updated. Here is an example:
--- repo: r-lib/rlang file: standalone-types-check.R last-updated: 2023-03-07 license: https://unlicense.org dependencies: standalone-obj-type.R imports: rlang (>= 1.1.0) ---
Two of these fields are consulted by use_standalone()
:
-
dependencies
: A file or a list of files in the same repo that the standalone file depends on. These files are retrieved automatically byuse_standalone()
. -
imports
: A package or list of packages that the standalone file depends on. A minimal version may be specified in parentheses, e.g.rlang (>= 1.0.0)
. These dependencies are passed touse_package()
to ensure they are included in theImports:
field of theDESCRIPTION
file.
Note that lists are specified with standard YAML syntax, using
square brackets, for example: imports: [rlang (>= 1.0.0), purrr]
.
Examples
## Not run:
use_standalone("r-lib/rlang", file = "types-check")
use_standalone("r-lib/rlang", file = "types-check", ref = "standalone-dep")
## End(Not run)
Use a usethis-style template
Description
Creates a file from data and a template found in a package. Provides control
over file name, the addition to .Rbuildignore
, and opening the file for
inspection.
Usage
use_template(
template,
save_as = template,
data = list(),
ignore = FALSE,
open = FALSE,
package = "usethis"
)
Arguments
template |
Path to template file relative to |
save_as |
Path of file to create, relative to root of active project.
Defaults to |
data |
A list of data passed to the template. |
ignore |
Should the newly created file be added to |
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
package |
Name of the package where the template is found. |
Details
This function can be used as the engine for a templating function in other
packages. The template
argument is used along with the package
argument
to derive the path to your template file; it will be expected at
fs::path_package(package = package, "templates", template)
. We use
fs::path_package()
instead of base::system.file()
so that path
construction works even in a development workflow, e.g., works with
devtools::load_all()
or pkgload::load_all()
. Note this describes the
behaviour of fs::path_package()
in fs v1.2.7.9001 and higher.
To interpolate your data into the template, supply a list using
the data
argument. Internally, this function uses
whisker::whisker.render()
to combine your template file with your data.
Value
A logical vector indicating if file was modified.
Examples
## Not run:
# Note: running this will write `NEWS.md` to your working directory
use_template(
template = "NEWS.md",
data = list(Package = "acme", Version = "1.2.3"),
package = "usethis"
)
## End(Not run)
Create or edit a test helper file
Description
This function creates (or opens) a test helper file, typically
tests/testthat/helper.R
. Test helper files are executed at the
beginning of every automated test run and are also executed by
load_all()
. A helper file is a great place to
define test helper functions for use throughout your test suite, such as
a custom expectation.
Usage
use_test_helper(name = NULL, open = rlang::is_interactive())
Arguments
name |
Can be used to specify the optional "SLUG" in
|
open |
Whether to open the file for interactive editing. |
See Also
-
use_test()
to create a test file. The testthat vignette on special files
vignette("special-files", package = "testthat")
.
Examples
## Not run:
use_test_helper()
use_test_helper("mocks")
## End(Not run)
Sets up overall testing infrastructure
Description
Creates tests/testthat/
, tests/testthat.R
, and adds the testthat package
to the Suggests field. Learn more in https://r-pkgs.org/testing-basics.html
Usage
use_testthat(edition = NULL, parallel = FALSE)
Arguments
edition |
testthat edition to use. Defaults to the latest edition, i.e. the major version number of the currently installed testthat. |
parallel |
Should tests be run in parallel? This feature appeared in testthat 3.0.0; see https://testthat.r-lib.org/articles/parallel.html for details and caveats. |
See Also
use_test()
to create individual test files
Examples
## Not run:
use_testthat()
use_test()
use_test("something-management")
## End(Not run)
Prepare to return a tibble
Description
Does minimum setup such that a tibble returned by your package
is handled using the tibble method for generics like print()
or [
.
Presumably you care about this if you've chosen to store and expose an
object with class tbl_df
. Specifically:
Check that the active package uses roxygen2
Add the tibble package to "Imports" in
DESCRIPTION
Prepare the roxygen directive necessary to import at least one function from tibble:
If possible, the directive is inserted into existing package-level documentation, i.e. the roxygen snippet created by
use_package_doc()
Otherwise, we issue advice on where the user should add the directive
This is necessary when your package returns a stored data object that has
class tbl_df
, but the package code does not make direct use of functions
from the tibble package. If you do nothing, the tibble namespace is not
necessarily loaded and your tibble may therefore be printed and subsetted
like a base data.frame
.
Usage
use_tibble()
Examples
## Not run:
use_tibble()
## End(Not run)
Deprecated tidyverse functions
Description
-
use_tidy_eval()
is deprecated because there's no longer a need to systematically import and re-export a large number of functions in order to use tidy evaluation. Instead, useuse_import_from()
to tactically import functions as you need them.
Usage
use_tidy_eval()
Helpers for tidyverse development
Description
These helpers follow tidyverse conventions which are generally a little stricter than the defaults, reflecting the need for greater rigor in commonly used packages.
Usage
use_tidy_github_actions(ref = NULL)
create_tidy_package(path, copyright_holder = NULL)
use_tidy_description()
use_tidy_dependencies()
use_tidy_contributing()
use_tidy_support()
use_tidy_issue_template()
use_tidy_coc()
use_tidy_github()
use_tidy_style(strict = TRUE)
use_tidy_logo(geometry = "240x278", retina = TRUE)
use_tidy_upkeep_issue(last_upkeep = last_upkeep_year())
Arguments
ref |
Desired Git reference, usually the name of a tag ( |
path |
A path. If it exists, it is used. If it does not exist, it is created, provided that the parent path exists. |
copyright_holder |
Name of the copyright holder or holders. This
defaults to |
strict |
Boolean indicating whether or not a strict version of styling
should be applied. See |
geometry |
a magick::geometry string specifying size. The default assumes that you have a hex logo using spec from http://hexb.in/sticker.html. |
retina |
|
last_upkeep |
Year of last upkeep. By default, the
|
Details
-
use_tidy_github_actions()
: Sets up the following workflows using GitHub Actions:Run
R CMD check
on the current release, devel, and four previous versions of R. The build matrix also ensuresR CMD check
is run at least once on each of the three major operating systems (Linux, macOS, and Windows).Report test coverage.
Build and deploy a pkgdown site.
Provide two commands to be used in pull requests:
/document
to runroxygen2::roxygenise()
and update the PR, and/style
to runstyler::style_pkg()
and update the PR.This is how the tidyverse team checks its packages, but it is overkill for less widely used packages. Consider using the more streamlined workflows set up by
use_github_actions()
oruse_github_action_check_standard()
.
-
create_tidy_package()
: creates a new package, immediately applies as many of the tidyverse conventions as possible, issues a few reminders, and activates the new package. -
use_tidy_dependencies()
: sets up standard dependencies used by all tidyverse packages (except packages that are designed to be dependency free). -
use_tidy_description()
: puts fields in standard order and alphabetises dependencies. -
use_tidy_eval()
: imports a standard set of helpers to facilitate programming with the tidy eval toolkit. -
use_tidy_style()
: styles source code according to the tidyverse style guide. This function will overwrite files! See below for usage advice. -
use_tidy_contributing()
: adds standard tidyverse contributing guidelines. -
use_tidy_issue_template()
: adds a standard tidyverse issue template. -
use_tidy_release_test_env()
: updates the test environment section incran-comments.md
. -
use_tidy_support()
: adds a standard description of support resources for the tidyverse. -
use_tidy_coc()
: equivalent touse_code_of_conduct()
, but puts the document in a.github/
subdirectory. -
use_tidy_github()
: convenience wrapper that callsuse_tidy_contributing()
,use_tidy_issue_template()
,use_tidy_support()
,use_tidy_coc()
. -
use_tidy_github_labels()
callsuse_github_labels()
to implement tidyverse conventions around GitHub issue label names and colours. -
use_tidy_upkeep_issue()
creates an issue containing a checklist of actions to bring your package up to current tidyverse standards. Also records the current date in theConfig/usethis/last-upkeep
field inDESCRIPTION
. -
use_tidy_logo()
callsuse_logo()
on the appropriate hex sticker PNG file at https://github.com/rstudio/hex-stickers.
use_tidy_style()
Uses the styler package package to style all code in a package, project, or directory, according to the tidyverse style guide.
Warning: This function will overwrite files! It is strongly suggested to only style files that are under version control or to first create a backup copy.
Invisibly returns a data frame with one row per file, that indicates whether styling caused a change.
Identify contributors via GitHub activity
Description
Derives a list of GitHub usernames, based on who has opened issues or pull
requests. Used to populate the acknowledgment section of package release blog
posts at https://www.tidyverse.org/blog/. If no arguments are given, we
retrieve all contributors to the active project since its last (GitHub)
release. Unexported helper functions, releases()
and ref_df()
can be
useful interactively to get a quick look at release tag names and a data
frame about refs (defaulting to releases), respectively.
Usage
use_tidy_thanks(repo_spec = NULL, from = NULL, to = NULL)
Arguments
repo_spec |
Optional GitHub repo specification in any form accepted for
the |
from , to |
GitHub ref (i.e., a SHA, tag, or release) or a timestamp in
ISO 8601 format, specifying the start or end of the interval of interest,
in the sense of |
Value
A character vector of GitHub usernames, invisibly.
Examples
## Not run:
# active project, interval = since the last release
use_tidy_thanks()
# active project, interval = since a specific datetime
use_tidy_thanks(from = "2020-07-24T00:13:45Z")
# r-lib/usethis, interval = since a certain date
use_tidy_thanks("r-lib/usethis", from = "2020-08-01")
# r-lib/usethis, up to a specific release
use_tidy_thanks("r-lib/usethis", from = NULL, to = "v1.1.0")
# r-lib/usethis, since a specific commit, up to a specific date
use_tidy_thanks("r-lib/usethis", from = "08a560d", to = "2018-05-14")
# r-lib/usethis, but with copy/paste of a browser URL
use_tidy_thanks("https://github.com/r-lib/usethis")
## End(Not run)
Create a learnr tutorial
Description
Creates a new tutorial below inst/tutorials/
. Tutorials are interactive R
Markdown documents built with the learnr
package. use_tutorial()
does
this setup:
Adds learnr to Suggests in
DESCRIPTION
.Gitignores
inst/tutorials/*.html
so you don't accidentally track rendered tutorials.Creates a new
.Rmd
tutorial from a template and, optionally, opens it for editing.Adds new
.Rmd
to.Rbuildignore
.
Usage
use_tutorial(name, title, open = rlang::is_interactive())
Arguments
name |
Base for file name to use for new |
title |
The human-facing title of the tutorial. |
open |
Open the newly created file for editing? Happens in RStudio, if
applicable, or via |
See Also
The learnr package documentation.
Examples
## Not run:
use_tutorial("learn-to-do-stuff", "Learn to do stuff")
## End(Not run)
Create an upkeep checklist in a GitHub issue
Description
This opens an issue in your package repository with a checklist of tasks for
regular maintenance of your package. This is a fairly opinionated list of
tasks but we believe taking care of them will generally make your package
better, easier to maintain, and more enjoyable for your users. Some of the
tasks are meant to be performed only once (and once completed shouldn't show
up in subsequent lists), and some should be reviewed periodically. The
tidyverse team uses a similar function use_tidy_upkeep_issue()
for our
annual package Spring Cleaning.
Usage
use_upkeep_issue(year = NULL)
Arguments
year |
Year you are performing the upkeep, used in the issue title. Defaults to current year |
Examples
## Not run:
use_upkeep_issue()
## End(Not run)
Increment package version
Description
usethis supports semantic versioning, which is described in more detail in the version section of R Packages. A version number breaks down like so:
<major>.<minor>.<patch> (released version) <major>.<minor>.<patch>.<dev> (dev version)
use_version()
increments the "Version" field in DESCRIPTION
, adds a new
heading to NEWS.md
(if it exists), commits those changes (if package uses
Git), and optionally pushes (if safe to do so). It makes the same update to a
line like PKG_version = "x.y.z";
in src/version.c
(if it exists).
use_dev_version()
increments to a development version, e.g. from 1.0.0 to
1.0.0.9000. If the existing version is already a development version with
four components, it does nothing. Thin wrapper around use_version()
.
Usage
use_version(which = NULL, push = FALSE)
use_dev_version(push = FALSE)
Arguments
which |
A string specifying which level to increment, one of: "major",
"minor", "patch", "dev". If |
push |
If |
See Also
The version section of R Packages.
Examples
## Not run:
## for interactive selection, do this:
use_version()
## request a specific type of increment
use_version("minor")
use_dev_version()
## End(Not run)
Create a vignette or article
Description
Creates a new vignette or article in vignettes/
. Articles are a special
type of vignette that appear on pkgdown websites, but are not included
in the package itself (because they are added to .Rbuildignore
automatically).
Usage
use_vignette(name, title = NULL)
use_article(name, title = NULL)
Arguments
name |
File name to use for new vignette. Should consist only of
numbers, letters, |
title |
The title of the vignette. If not provided, a title is generated
from |
General setup
Adds needed packages to
DESCRIPTION
.Adds
inst/doc
to.gitignore
so built vignettes aren't tracked.Adds
vignettes/*.html
andvignettes/*.R
to.gitignore
so you never accidentally track rendered vignettes.For
*.qmd
, adds Quarto-related patterns to.gitignore
and.Rbuildignore
.
See Also
The vignettes chapter of R Packages
The pkgdown vignette on Quarto:
vignette("quarto", package = "pkgdown")
The quarto (as in the R package) vignette on HTML vignettes:
vignette("hello", package = "quarto")
Examples
## Not run:
use_vignette("how-to-do-stuff", "How to do stuff")
use_vignette("r-markdown-is-classic.Rmd", "R Markdown is classic")
use_vignette("quarto-is-cool.qmd", "Quarto is cool")
## End(Not run)
Options consulted by usethis
Description
User-configurable options consulted by usethis, which provide a mechanism for setting default behaviors for various functions.
If the built-in defaults don't suit you, set one or more of these options.
Typically, this is done in the .Rprofile
startup file, which you can open
for editing with edit_r_profile()
- this will set the specified options for
all future R sessions. Your code will look something like:
options( usethis.description = list( "Authors@R" = utils::person( "Jane", "Doe", email = "jane@example.com", role = c("aut", "cre"), comment = c(ORCID = "YOUR-ORCID-ID") ), License = "MIT + file LICENSE" ), usethis.destdir = "/path/to/folder/", # for use_course(), create_from_github() usethis.protocol = "ssh", # Use ssh git protocol usethis.overwrite = TRUE # overwrite files in Git repos without confirmation )
Options for the usethis package
-
usethis.description
: customize the default content of newDESCRIPTION
files by setting this option to a named list. If you are a frequent package developer, it is worthwhile to pre-configure your preferred name, email, license, etc. See the example above and the article on usethis setup for more details. -
usethis.destdir
: Default directory in which to place new projects downloaded byuse_course()
andcreate_from_github()
. If this option is unset, the user's Desktop or similarly conspicuous place will be used. -
usethis.protocol
: specifies your preferred transport protocol for Git. Either "https" (default) or "ssh":-
usethis.protocol = "https"
implieshttps://github.com/<OWNER>/<REPO>.git
-
usethis.protocol = "ssh"
impliesgit@github.com:<OWNER>/<REPO>.git
You can also change this for the duration of your R session with
use_git_protocol()
. -
-
usethis.overwrite
: IfTRUE
, usethis overwrites an existing file without asking for user confirmation if the file is inside a Git repo. The rationale is that the normal Git workflow makes it easy to see and selectively accept/discard any proposed changes. -
usethis.quiet
: Set toTRUE
to suppress user-facing messages. DefaultFALSE
. -
usethis.allow_nested_project
: Whether or not to allow you to create a project inside another project. This is rarely a good idea, so this option defaults toFALSE
.
Write into or over a file
Description
Helpers to write into or over a new or pre-existing file. Designed mostly for for internal use. File is written with UTF-8 encoding.
Usage
write_union(path, lines, quiet = FALSE)
write_over(path, lines, quiet = FALSE, overwrite = FALSE)
Arguments
path |
Path to target file. It is created if it does not exist, but the parent directory must exist. |
lines |
Character vector of lines. For |
quiet |
Logical. Whether to message about what is happening. |
overwrite |
Force overwrite of existing file? |
Value
Logical indicating whether a write occurred, invisibly.
Functions
-
write_union()
: writes lines to a file, taking the union of what's already there, if anything, and some new lines. Note, there is no explicit promise about the line order. Designed to modify simple config files like.Rbuildignore
and.gitignore
. -
write_over()
: writes a file with specific lines, creating it if necessary or overwriting existing, if proposed contents are not identical and user is available to give permission.
Examples
write_union("a_file", letters[1:3])
readLines("a_file")
write_union("a_file", letters[1:5])
readLines("a_file")
write_over("another_file", letters[1:3])
readLines("another_file")
write_over("another_file", letters[1:3])
## Not run:
## will error if user isn't present to approve the overwrite
write_over("another_file", letters[3:1])
## End(Not run)
## clean up
file.remove("a_file", "another_file")
Download and unpack a ZIP file
Description
Functions to download and unpack a ZIP file into a local folder of files, with very intentional default behaviour. Useful in pedagogical settings or anytime you need a large audience to download a set of files quickly and actually be able to find them. The underlying helpers are documented in use_course_details.
Usage
use_course(url, destdir = getOption("usethis.destdir"))
use_zip(
url,
destdir = getwd(),
cleanup = if (rlang::is_interactive()) NA else FALSE
)
Arguments
url |
Link to a ZIP file containing the materials. To reduce the chance of typos in live settings, these shorter forms are accepted:
|
destdir |
Destination for the new folder. Defaults to the location
stored in the global option |
cleanup |
Whether to delete the original ZIP file after unpacking its
contents. In an interactive setting, |
Value
Path to the new directory holding the unpacked ZIP file, invisibly.
Functions
-
use_course()
: Designed with live workshops in mind. Includes intentional friction to highlight the download destination. Workflow:User executes, e.g.,
use_course("bit.ly/xxx-yyy-zzz")
.User is asked to notice and confirm the location of the new folder. Specify
destdir
or configure the"usethis.destdir"
option to prevent this.User is asked if they'd like to delete the ZIP file.
If new folder contains an
.Rproj
file, a new instance of RStudio is launched. Otherwise, the folder is opened in the file manager, e.g. Finder or File Explorer.
-
use_zip()
: More useful in day-to-day work. Downloads in current working directory, by default, and allowscleanup
behaviour to be specified.
Examples
## Not run:
# download the source of usethis from GitHub, behind a bit.ly shortlink
use_course("bit.ly/usethis-shortlink-example")
use_course("http://bit.ly/usethis-shortlink-example")
# download the source of rematch2 package from CRAN
use_course("https://cran.r-project.org/bin/windows/contrib/3.4/rematch2_2.0.1.zip")
# download the source of rematch2 package from GitHub, 4 ways
use_course("r-lib/rematch2")
use_course("https://api.github.com/repos/r-lib/rematch2/zipball/HEAD")
use_course("https://api.github.com/repos/r-lib/rematch2/zipball/main")
use_course("https://github.com/r-lib/rematch2/archive/main.zip")
## End(Not run)