Debian Codegraph @

R/sass_cache.R

raw
1 # A registry of caches for different directories
2 .caches <- new.env(parent = emptyenv())
3
4
5 #' Get and set the cache object registered for a specific directory
6 #'
7 #' @details
8 #'
9 #' If `sass_cache_get_dir()` is called for a given directory, before
10 #' `sass_cache_set_dir()` has been called for that directory, then it will
11 #' return `NULL`.
12 #'
13 #' After `sass_cache_set_dir()` is called for a directory, any future calls to
14 #' `sass_cache_get_dir()` with that directory will return that specific cache
15 #' object. This can be useful if you customize parameters for the cache object,
16 #' like maximum size or age.
17 #'
18 #'
19 #' @param dir A directory. An error will be thrown if the directory does not
20 #' exist.
21 #' @param cache A [sass_file_cache()] object, or `NULL` if you don't want to
22 #' unset the cache for a directory.
23 #' @param create If `TRUE`, then if the cache directory doesn't exist, or if
24 #' there is not a registered cache object for the directory, create them as
25 #' needed.
26 #'
27 #' @seealso [sass_cache_get()], [sass_file_cache()], [sass()]
28 #'
29 #' @keywords internal
30 #' @export
31 sass_cache_get_dir <- function(dir, create = FALSE) {
32 if (create) {
33 # Create dir if needed
34 if (!dir.exists(dir)) {
35 dir.create2(dir)
36 }
37 dir <- normalizePath(dir, mustWork = TRUE)
38
39 # Create cache object if needed
40 if (is.null(.caches[[dir]])) {
41 sass_cache_set_dir(dir, sass_file_cache(dir))
42 }
43
44 } else {
45 if (!dir.exists(dir)) {
46 stop("`dir` does not exist.")
47 }
48 }
49
50 dir <- normalizePath(dir, mustWork = TRUE)
51 .caches[[dir]]
52 }
53
54 #' @rdname sass_cache_get_dir
55 #' @export
56 sass_cache_set_dir <- function(dir, cache) {
57 if (!is.null(cache) && !inherits(cache, "FileCache")) {
58 stop("`cache` must be a FileCache object or NULL.")
59 }
60 if (!dir.exists(dir)) {
61 stop("`dir` does not exist.")
62 }
63
64 dir <- normalizePath(dir, mustWork = TRUE)
65
66 if (is.null(cache)) {
67 # Unset the cache registered for a directory
68 if (exists(dir, envir = .caches, inherits = FALSE)) {
69 rm(list = dir, envir = .caches)
70 }
71 return(invisible(NULL))
72 }
73
74 if (!identical(dir, normalizePath(cache$dir()))) {
75 stop("`dir` and the cache object's directory do not match.")
76 }
77
78 .caches[[dir]] <- cache
79 invisible(cache)
80 }
81
82 #' Retrieve the default file cache
83 #'
84 #' @description
85 #'
86 #' When caching is enabled, this function returns a [sass_file_cache()] object
87 #' that [sass()]'s `cache` argument uses (by default) for caching Sass
88 #' compilation. When caching is disabled (either by setting the `sass.cache`
89 #' option to `FALSE`, `NULL`, or via [shiny::devmode()]), this function returns
90 #' `NULL` (effectively telling [sass()] to not `cache` by default).
91 #'
92 #' @details
93 #'
94 #' When caching is enabled, then this function returns a `sass_file_cache()`
95 #' object that (by default) uses [sass_cache_context_dir()] for its directory.
96 #' The directory can also be customized by providing the `sass.cache` option
97 #' with either a filepath (as a string) or a full-blown `sass_file_cache()`
98 #' object.
99 #'
100 #' @seealso [sass_cache_get_dir()], [sass()]
101 #'
102 #' @export
103 sass_cache_get <- function() {
104 cache_option <-
105 get_shiny_devmode_option(
106 "sass.cache",
107 default = TRUE,
108 devmode_default = FALSE,
109 devmode_message = "Turning off caching of Sass -> CSS compilation. To turn caching on, call `options(sass.cache = TRUE)`"
110 )
111
112 if (is.null(cache_option) || identical(cache_option, FALSE)) {
113 return(NULL)
114 }
115 if (inherits(cache_option, "FileCache")) {
116 return(cache_option)
117 }
118
119 cache_dir <- NULL
120 if (is.character(cache_option)) {
121 cache_dir <- cache_option
122 }
123
124 # Default case
125 if (is.null(cache_dir)) {
126 cache_dir <- sass_cache_context_dir()
127 }
128
129 sass_cache_get_dir(cache_dir, create = TRUE)
130 }
131
132 #' Return the cache directory for the current context.
133 #'
134 #' @details
135 #'
136 #' In most cases, this function returns the user's cache directory, by calling
137 #' `tools::R_user_dir("sass", which = "cache")` (for R 4.0 and above) or
138 #' `rappdirs::user_cache_dir("R-sass")` (for older versions of R).
139 #'
140 #' If this function is called from a Shiny application, it will also look for a
141 #' subdirectory named `app_cache/`. If it exists, it will use a directory named
142 #' `app_cache/sass/` to store the cache.
143 #'
144 #' When running a Shiny application in a typical R session, it will not create
145 #' the `app_cache/` subdirectory, but it will use it if present. This scopes the
146 #' cache to the application.
147 #'
148 #' With Shiny applications hosted on Shiny Server and Connect, it _will_ create
149 #' a `app_cache/sass/` subdirectory, so that the cache is scoped to the
150 #' application and will not interfere with another application's cache.
151 #'
152 #' @keywords internal
153 #' @export
154 sass_cache_context_dir <- function() {
155 tryCatch(
156 {
157 # The usual place we'll look. This may be superseded below.
158 cache_dir <- find_cache_dir("sass")
159
160 if (is_shiny_app()) {
161 # We might use ./cache/sass, if it's a hosted app, or if the directory
162 # already exists. (We won't automatically create the directory on
163 # locally-running apps.)
164 app_dir <- shiny::getShinyOption("appDir")
165 app_cache_dir <- file.path(app_dir, "app_cache", "sass")
166 if (is_hosted_app()) {
167 # On hosted platforms, always create a ./cache/sass subdir for caching
168 # sass stuff.
169 cache_dir <- app_cache_dir
170
171 } else {
172 # When running an app in a normal R session...
173 if (dir.exists(app_cache_dir) || dir.exists(dirname(app_cache_dir))) {
174 # If ./cache/sass or ./cache already exists, use it.
175 cache_dir <- app_cache_dir
176 }
177 }
178 }
179
180 if (!dir.exists(cache_dir)) {
181 res <- dir.create(cache_dir, recursive = TRUE)
182 if (!res) {
183 stop("Error creating cache directory")
184 }
185 }
186 },
187 error = function(e) {
188 # If all of the attempts to find/create a dir failed, just use a temp dir.
189 warning("Error using cache directory at '", cache_dir,
190 "'. Using temp dir instead.")
191
192 cache_dir <<- tempfile("sass-")
193 dir.create(cache_dir)
194 }
195 )
196 normalizePath(cache_dir)
197 }
198
199
200 #' Returns a hash of the object, including sass_file mtimes
201 #'
202 #' This function returns a hash of the object `x`, intended for use in caching.
203 #' It recurses into lists, and any [sass_file()] objects will have the file's
204 #' mtime attached as an attribute. This is useful for detecting if the file has
205 #' been modified.
206 #'
207 #' @param x A list with sass objects.
208 #' @noRd
209 sass_hash <- function(x) {
210 rlang::hash(
211 add_sass_file_mtime(list(x, get_package_version("sass")))
212 )
213 }
214
215 # Given an object, return an object that can be \code{rlang::hash}-ed into a
216 # hash key. This traverses the object and adds file mtimes for files imported
217 # via `sass_file` directives (but not files that are imported by those files).
218 add_sass_file_mtime <- function(x) {
219 if (inherits(x, "sass_file")) {
220 # Add the file's mtime to the cache key. This will cause mtime changes to
221 # bust the cache.
222 input_path <- attr(x, "sass_file_path", exact = TRUE)
223 attr(x, "sass_timestamp") <- file.mtime(input_path)
224 x
225 } else if (inherits(x, "list")) {
226 lapply(x, add_sass_file_mtime)
227 } else {
228 x
229 }
230 }
231
232
233 find_cache_dir <- function(pkg) {
234 # In R 4.0 and above, CRAN wants us to use the new tools::R_user_dir().
235 # If not present, fall back to rappdirs::user_cache_dir().
236 R_user_dir <- getNamespace('tools')$R_user_dir
237 if (!is.null(R_user_dir)) {
238 R_user_dir(pkg, which = "cache")
239 } else {
240 rappdirs::user_cache_dir(paste0("R-", pkg))
241 }
242 }
243
244
245 #' Caching Options for Sass (defunct)
246 #'
247 #' This function is no longer used. Please see [sass_cache_get()].
248 #' @param cache No longer used.
249 #' @param cache_dir No longer used.
250 #' @export
251 #' @keywords internal
252 sass_cache_options <- function(cache, cache_dir) {
253 message(
254 "The function `sass_cache_options` is no longer used. ",
255 "Please see ?sass_cache_set and ?sass_file_cache"
256 )
257 }