1#' Unload and reload package.
2#'
3#' This attempts to unload and reload an _installed_ package. If the package is
4#' not loaded already, it does nothing. It's not always possible to cleanly
5#' unload a package: see the caveats in [unload()] for some of the potential
6#' failure points. If in doubt, restart R and reload the package with
7#' [library()].
8#'
9#' @template devtools
10#' @param quiet if `TRUE` suppresses output from this function.
11#' @seealso [load_all()] to load a package for interactive development.
12#' @examples
13#' \dontrun{
14#' # Reload package that is in current directory
15#' reload(".")
16#'
17#' # Reload package that is in ./ggplot2/
18#' reload("ggplot2/")
19#'
20#' # Can use inst() to find the package path
21#' # This will reload the installed ggplot2 package
22#' reload(pkgload::inst("ggplot2"))
23#' }
24#' @export
25reload <- function(pkg = ".", quiet = FALSE) {
26  pkg <- as.package(pkg)
27
28  if (is_attached(pkg)) {
29    if (!quiet) cli::cli_alert_info("Reloading attached {.pkg {pkg$package}}")
30    pkgload::unload(pkg$package)
31    require(pkg$package, character.only = TRUE, quietly = TRUE)
32  } else if (is_loaded(pkg)) {
33    if (!quiet) cli::cli_alert_info("Reloading loaded {.pkg {pkg$package}}")
34    pkgload::unload(pkg$package)
35    requireNamespace(pkg$package, quietly = TRUE)
36  }
37}
38