Debian Codegraph @

R/path_package.R

raw
1 #' Construct a path to a location within an installed or development package
2 #'
3 #' `path_package` differs from [system.file()] in that it always returns an
4 #' error if the package does not exist. It also returns a different error if
5 #' the file within the package does not exist.
6 #'
7 #'`path_package()` also automatically works with packages loaded with devtools
8 #'even if the `path_package()` call comes from a different package.
9 #'
10 #' @param package Name of the package to in which to search
11 #' @param ... Additional paths appended to the package path by [path()].
12 #' @examples
13 #' path_package("base")
14 #' path_package("stats")
15 #' path_package("base", "INDEX")
16 #' path_package("splines", "help", "AnIndex")
17 #' @export
18 path_package <- function(package, ...) {
19 if (!is.character(package) || length(package) != 1L) {
20 stop(fs_error(sprintf("`package` must be a character vector of length 1")))
21 }
22
23 pkg_path <-
24 tryCatch(
25 find.package(package, quiet = FALSE),
26
27 error = function(error) {
28 is_not_found_error <- grepl(
29 gettextf("there is no package called %s", sQuote(package)),
30 conditionMessage(error),
31 fixed = TRUE
32 )
33 if (!is_not_found_error) {
34 stop(error)
35 }
36
37 msg <- sprintf(
38 "Can't find package `%s` in library locations:
39 %s",
40 package,
41 paste0(" - '", path_tidy(.libPaths()), "'", collapse = "\n")
42 )
43
44 stop(fs_error(msg, class = "EEXIST"))
45 }
46 )
47
48 files_inst <- path(pkg_path, "inst", ...)
49 present_inst <- file_exists(files_inst)
50 files_top <- path(pkg_path, ...)
51 present_top <- file_exists(files_top)
52 files <- files_top
53 files[present_inst] <- files_inst[present_inst]
54 files <- files[present_inst | present_top]
55
56 if (length(files) == 0) {
57 msg <- sprintf(
58 "File(s) %s do not exist",
59 paste0("'", files_top, "'", collapse = ", ")
60 )
61 stop(fs_error(msg, class = "EEXIST"))
62 }
63 files
64 }