Debian Codegraph @

R/autoload.R

raw
1
2 #' Auto-load the active project
3 #'
4 #' Automatically load the renv project associated with a particular directory.
5 #' renv will search parent directories for the renv project root; if found,
6 #' that project will be loaded via [renv::load()].
7 #'
8 #' To enable the renv auto-loader, you can place:
9 #'
10 #' ```
11 #' renv::autoload()
12 #' ````
13 #'
14 #' into your site-wide or user `.Rprofile` to ensure that renv projects are
15 #' automatically loaded for any newly-launched \R sessions, even if those \R
16 #' sessions are launched within the sub-directory of an renv project.
17 #'
18 #' If you'd like to launch \R within the sub-directory of an renv project
19 #' without auto-loading renv, you can set the environment variable:
20 #'
21 #' ```
22 #' RENV_AUTOLOAD_ENABLED = FALSE
23 #' ```
24 #'
25 #' before starting \R.
26 #'
27 #' Note that `renv::autoload()` is only compatible with projects using
28 #' `renv 0.15.3` or newer, as it relies on features within the `renv/activate.R`
29 #' script that are only generated with newer versions of renv.
30 #'
31 #' @export
32 autoload <- function() {
33 invisible(renv_autoload_impl())
34 }
35
36 renv_autoload_impl <- function() {
37
38 # check if we're disabled
39 enabled <- Sys.getenv("RENV_AUTOLOAD_ENABLED", unset = "TRUE")
40 if (!truthy(enabled))
41 return(FALSE)
42
43 # bail if load is already being called
44 if (the$load_running)
45 return(FALSE)
46
47 # avoid recursion
48 running <- getOption("renv.autoload.running")
49 if (identical(running, TRUE))
50 return(FALSE)
51
52 # set our flag
53 renv_scope_options(renv.autoload.running = TRUE)
54
55 # try to find a project
56 project <- catch(renv_project_find())
57 if (inherits(project, "error"))
58 return(FALSE)
59
60 # move to project directory
61 renv_scope_wd(project)
62
63 # if we have a project profile, source it
64 profile <- file.path(project, ".Rprofile")
65 if (file.exists(profile)) {
66 sys.source(profile, envir = globalenv())
67 return(TRUE)
68 }
69
70 # if we have an activate script, run it
71 activate <- renv_paths_renv("activate.R", profile = FALSE, project = project)
72 if (file.exists(activate)) {
73 sys.source(activate, envir = globalenv())
74 return(TRUE)
75 }
76
77 # otherwise, just try to load the project
78 load(project)
79 TRUE
80
81 }