| 1 |
#' Cache the execution of an expression in memory or on disk |
| 2 |
#' |
| 3 |
#' Caching is based on the assumption that if the input does not change, the |
| 4 |
#' output will not change. After an expression is executed for the first time, |
| 5 |
#' its result will be saved (either in memory or on disk). The next run will be |
| 6 |
#' skipped and the previously saved result will be loaded directly if all |
| 7 |
#' external inputs of the expression remain the same, otherwise the cache will |
| 8 |
#' be invalidated and the expression will be re-executed. |
| 9 |
#' |
| 10 |
#' Arguments supported in `...` include: |
| 11 |
#' |
| 12 |
#' - `vars`: Names of local variables (which are created inside the expression). |
| 13 |
#' By default, local variables are automatically detected from the expression |
| 14 |
#' via [find_locals()]. Locally created variables are cached along with the |
| 15 |
#' value of the expression. |
| 16 |
#' |
| 17 |
#' - `hash` and `extra`: R objects to be used to determine if cache should be |
| 18 |
#' loaded or invalidated. If (the MD5 hash of) the objects is not changed, the |
| 19 |
#' cache is loaded, otherwise the cache is invalidated and rebuilt. By default, |
| 20 |
#' `hash` is a list of values of global variables in the expression (i.e., |
| 21 |
#' variables created outside the expression). Global variables are automatically |
| 22 |
#' detected by [find_globals()]. You can provide a vector of names to override |
| 23 |
#' the automatic detection if you want some specific global variables to affect |
| 24 |
#' caching, or the automatic detection is not reliable. You can also provide |
| 25 |
#' additional information via the `extra` argument. For example, if the |
| 26 |
#' expression reads an external file `foo.csv`, and you want the cache to be |
| 27 |
#' invalidated after the file is modified, you may use `extra = |
| 28 |
#' file.mtime("foo.csv")`. |
| 29 |
#' |
| 30 |
#' - `keep`: By default, only one copy of the cache corresponding to an `id` |
| 31 |
#' under `path` is kept, and all other copies for this `id` is automatically |
| 32 |
#' purged. If `TRUE`, all copies of the cache are kept. If `FALSE`, all copies |
| 33 |
#' are removed, which means the cache is *always* invalidated, and can be useful |
| 34 |
#' to force re-executing the expression. |
| 35 |
#' |
| 36 |
#' - `rw`: A list of functions to read/write the cache files. The list is of the |
| 37 |
#' form `list(name = 'xxx', load = function(file) {}, save = function(x, file) |
| 38 |
#' {})`. By default, [readRDS()] and [saveRDS()] are used. This argument can |
| 39 |
#' also take a character string to use some built-in read/write methods. |
| 40 |
#' Currently available methods include `rds` (the default), `raw` (using |
| 41 |
#' [serialize()] and [unserialize()]), `qs2` (using [qs2::qs_read()] and |
| 42 |
#' [qs2::qs_save()]), and `qdata` (using [qs2::qd_read()] and [qs2::qd_save()]). |
| 43 |
#' The `rds` and `raw` methods only use base R functions (the `rds` method |
| 44 |
#' generates smaller files because it uses compression, but is often slower than |
| 45 |
#' the `raw` method, which does not use compression). The `qs2` and `qdata` |
| 46 |
#' methods require the \pkg{qs2} package, which can be much faster than base R |
| 47 |
#' methods and also supports compression. |
| 48 |
#' @param expr An R expression to be cached. |
| 49 |
#' @param path The path to save the cache. The special value `":memory:"` means |
| 50 |
#' in-memory caching. If it is intended to be a directory path, please make |
| 51 |
#' sure to add a trailing slash. |
| 52 |
#' @param id A stable and unique string identifier for the expression to be used |
| 53 |
#' to identify a unique copy of cache for the current expression from all |
| 54 |
#' cache files (or in-memory elements). If not provided, an MD5 digest of the |
| 55 |
#' [deparse]d expression will be used, which means if the expression does not |
| 56 |
#' change (changes in comments or white spaces do not matter), the `id` will |
| 57 |
#' remain the same. This may not be a good default is two identical |
| 58 |
#' expressions are cached under the same `path`, because they could overwrite |
| 59 |
#' each other's cache when one expression's cache is invalidated, which may or |
| 60 |
#' may not be what you want. If you do not want that to happen, you need to |
| 61 |
#' manually provide an `id`. |
| 62 |
#' @param ... More arguments to control the behavior of caching (see |
| 63 |
#' \sQuote{Details}). |
| 64 |
#' @return If the cache is found, the cached value of the expression will be |
| 65 |
#' loaded and returned (other local variables will also be lazy-loaded into |
| 66 |
#' the current environment as a side-effect). If cache does not exist, the |
| 67 |
#' expression is executed and its value is returned. |
| 68 |
#' @references See <https://pkg.yihui.org/litedown/book/#sec:option-cache> for |
| 69 |
#' how it works and an application in \pkg{litedown}. |
| 70 |
#' @export |
| 71 |
#' @examples |
| 72 |
#' # the first run takes about 1 second |
| 73 |
#' y1 = xfun::cache_exec({ |
| 74 |
#' x = rnorm(1e5) |
| 75 |
#' Sys.sleep(1) |
| 76 |
#' x |
| 77 |
#' }, path = ':memory:', id = 'sim-norm') |
| 78 |
#' |
| 79 |
#' # the second run takes almost no time |
| 80 |
#' y2 = xfun::cache_exec({ |
| 81 |
#' # comments won't affect caching |
| 82 |
#' x = rnorm(1e5) |
| 83 |
#' Sys.sleep(1) |
| 84 |
#' x |
| 85 |
#' }, path = ':memory:', id = 'sim-norm') |
| 86 |
#' |
| 87 |
#' # y1, y2, and x should be identical |
| 88 |
#' stopifnot(identical(y1, y2), identical(y1, x)) |
| 89 |
cache_exec = function(expr, path = 'cache/', id = NULL, ...) { |
| 90 |
use_cache = FALSE |
| 91 |
ret = cache_code( |
| 92 |
substitute(expr), parent.frame(), use_cache <- TRUE, |
| 93 |
list(path = path, id = id, ...) |
| 94 |
) |
| 95 |
if (use_cache) ret else expr |
| 96 |
} |
| 97 |
|
| 98 |
# a dictionary containing names and hashes of global variables |
| 99 |
.cache_dict = new.env(parent = emptyenv()) |
| 100 |
|
| 101 |
# an in-memory database containing results from previous run, values of local |
| 102 |
# variables, and their hashes, of the form environment(*__id__* = list(results, |
| 103 |
# values, hashes)) |
| 104 |
.cache_db = new.env(parent = emptyenv()) |
| 105 |
|
| 106 |
cache_code = function( |
| 107 |
code, envir = parent.frame(), found = NULL, config = list( |
| 108 |
path = NULL, vars = NULL, hash = NULL, extra = NULL, keep = NULL, id = NULL, |
| 109 |
rw = NULL |
| 110 |
) |
| 111 |
) { |
| 112 |
dict = .cache_dict |
| 113 |
if (!is.character(path <- config$path)) { |
| 114 |
# when caching is not enabled, we should clean up hashes for local variables |
| 115 |
# to make sure the next cached chunk will get the up-to-date hash |
| 116 |
vars = intersect(config$vars %||% if (loadable('codetools')) find_locals(code), ls_all(dict)) |
| 117 |
rm_vars(vars, dict) |
| 118 |
return() |
| 119 |
} |
| 120 |
|
| 121 |
# functions to read/write cache files |
| 122 |
if (is.null(rw <- config$rw)) rw = 'rds' |
| 123 |
if (is.character(rw)) rw = io_methods[[rw]] |
| 124 |
if (!is.character(rw$name) || length(rw$name) != 1) stop( |
| 125 |
'The cache method must have a name (as a character string).' |
| 126 |
) |
| 127 |
|
| 128 |
hash = config$hash %||% find_globals(code, envir) |
| 129 |
# get the values of hash variables (unless hash is I(character())) |
| 130 |
if (is.character(hash) && !inherits(hash, 'AsIs')) { |
| 131 |
# if a variable exists in the hash dictionary, use its hash (32 chars) in |
| 132 |
# the dict instead of its actual value, because the value may be large and |
| 133 |
# slow to serialize or compute md5 checksum |
| 134 |
hash = lapply(hash, function(x) dict[[x]] %||% get(x, envir)) |
| 135 |
} |
| 136 |
# "normalized" code that doesn't rely on comments or white spaces |
| 137 |
code2 = deparse(if (is.character(code)) parse_only(code) else code) |
| 138 |
hash = md5_one(c(hash, config$extra, list(code2))) |
| 139 |
|
| 140 |
mem_cache = path == ':memory:' # in-memory or disk cache |
| 141 |
|
| 142 |
# by default, the ID is a checksum of the code, which may not be a good idea |
| 143 |
# (e.g., two identical code fragments could be executed one after another |
| 144 |
# but they should not share the same cache); for litedown, id is chunk label |
| 145 |
if (is.null(id <- config$id)) id = md5_one(code2) |
| 146 |
id = paste0(path, if (mem_cache) '__', id, if (mem_cache) '__') |
| 147 |
|
| 148 |
file_pattern = function(x) sprintf('^[0-9a-z]{32}[.]%s([.][0-9]+)?$', x) |
| 149 |
# try to retrieve cache from memory (the dictionary) or disk |
| 150 |
cached = if (mem_cache) { |
| 151 |
db = .cache_db |
| 152 |
id_names = function(x) { |
| 153 |
x = ls_all(db) |
| 154 |
x[startsWith(x, id) & nchar(x) == nchar(id) + 32] |
| 155 |
} |
| 156 |
hits = id_names(db) |
| 157 |
# clean up all cache for this id, i.e., remove :memory:__id__hash |
| 158 |
if (isFALSE(config$keep)) rm_vars(hits, db) |
| 159 |
id = paste0(id, hash) |
| 160 |
id %in% ls_all(db) |
| 161 |
} else { |
| 162 |
db = list.files(id, full.names = TRUE) |
| 163 |
hits = grepl(file_pattern('[[:alnum:]]+'), basename(db)) |
| 164 |
if (isFALSE(config$keep)) file.remove(db[hits]) |
| 165 |
id = file.path(id, paste0(hash, '.', rw$name)) |
| 166 |
file_exists(id) |
| 167 |
} |
| 168 |
# return now if cache is found |
| 169 |
if (cached) { |
| 170 |
# I could implement lazy-loading here but I'm not sure if it's worth it |
| 171 |
ret = if (mem_cache) db[[id]] else rw$load(id) |
| 172 |
list2env(ret$hashes, dict) # update the hash dictionary |
| 173 |
# lazy-load cached objects into envir |
| 174 |
.mapply(function(name, file) { |
| 175 |
delayedAssign(name, if (mem_cache) ret$values[[name]] else rw$load(file), assign.env = envir) |
| 176 |
}, list(names(ret$hashes), sprintf('%s.%d', id, seq_along(ret$hashes))), NULL) |
| 177 |
found |
| 178 |
return(ret$result) |
| 179 |
} |
| 180 |
|
| 181 |
# clean up other versions of cache before saving a new version |
| 182 |
if (!isTRUE(config$keep)) { |
| 183 |
if (mem_cache) rm_vars(hits, db) else { |
| 184 |
# clean cache for the current method only; don't touch other methods' cache |
| 185 |
hits = grepl(file_pattern(rw$name), basename(db)) |
| 186 |
file.remove(db[hits]) |
| 187 |
} |
| 188 |
} |
| 189 |
vars = config$vars %||% find_locals(code) |
| 190 |
# inject an on.exit() call to the parent function to save its returned value; |
| 191 |
# note that returnValue() requires R >= 3.2.0 released on 2015-04-16, which I |
| 192 |
# hope is a reasonable requirement (anyone using R from a decade ago?) |
| 193 |
exit_call(function() { |
| 194 |
# we can't tell if returnValue() is from a successful call of a function or |
| 195 |
# not, so we pass a default that is very unlikely to be the returned value |
| 196 |
# on success; if we get this value, it's very likely that errors occurred |
| 197 |
void_return = new.env() # should be unlikely for two new.env() to be identical |
| 198 |
res = returnValue(void_return) |
| 199 |
if (identical(res, void_return)) return() |
| 200 |
# save the checksums of objects to be used for a future run |
| 201 |
v1 = ls_all(envir) |
| 202 |
v2 = setdiff(vars, v1) |
| 203 |
if (length(v2)) warning( |
| 204 |
'Variable(s) not found in the environment: ', paste(v2, collapse = ', ') |
| 205 |
) |
| 206 |
hashes = as.list(do.call(md5, vals <- mget(vars, envir))) |
| 207 |
ret = list(result = res, hashes = hashes) |
| 208 |
if (mem_cache) { |
| 209 |
ret$values = vals |
| 210 |
db[[id]] = ret |
| 211 |
} else { |
| 212 |
dir_create(dirname(id)) |
| 213 |
rw$save(ret, id) # result and variable hashes are saved to the main file |
| 214 |
# variable values are saved in separate files of the form HASH.i; the i-th |
| 215 |
# file is for the i-th variable |
| 216 |
.mapply(rw$save, list(vals, sprintf('%s.%d', id, seq_along(vals))), NULL) |
| 217 |
} |
| 218 |
list2env(hashes, dict) |
| 219 |
}) |
| 220 |
} |
| 221 |
|
| 222 |
# functions to load/save cache files |
| 223 |
io_methods = list( |
| 224 |
raw = list( |
| 225 |
name = 'raw', |
| 226 |
load = function(...) unserialize(read_bin(...)), |
| 227 |
save = function(x, file, ...) { |
| 228 |
s = serialize(x, NULL, xdr = FALSE, ...) |
| 229 |
writeBin(s, file) |
| 230 |
} |
| 231 |
), |
| 232 |
rds = list( |
| 233 |
name = 'rds', |
| 234 |
load = function(...) readRDS(...), |
| 235 |
save = function(x, file, ...) saveRDS(x, file, ...) |
| 236 |
), |
| 237 |
qs2 = list( |
| 238 |
name = 'qs2', |
| 239 |
load = function(...) qs2::qs_read(...), |
| 240 |
save = function(x, file, ...) qs2::qs_save(x, file, ...) |
| 241 |
), |
| 242 |
qdata = list( |
| 243 |
name = 'qdata', |
| 244 |
load = function(...) qs2::qd_read(...), |
| 245 |
save = function(x, file, ...) qs2::qd_save(x, file, ...) |
| 246 |
) |
| 247 |
) |
| 248 |
|
| 249 |
#' Cache the value of an R expression to an RDS file |
| 250 |
#' |
| 251 |
#' Save the value of an expression to a cache file. Next time the value is |
| 252 |
#' loaded from the file if it exists. Please consider using [cache_exec()] |
| 253 |
#' instead, which is more flexible and intelligent. |
| 254 |
#' |
| 255 |
#' Note that the `file` argument does not provide the full cache filename. The |
| 256 |
#' actual name of the cache file is of the form \file{BASENAME_HASH.rds}, where |
| 257 |
#' \file{BASENAME} is the base name provided via the \file{file} argument (e.g., |
| 258 |
#' if `file = 'foo.rds'`, `BASENAME` would be \file{foo}), and \file{HASH} is |
| 259 |
#' the MD5 hash (also called the \sQuote{checksum}) calculated from the R code |
| 260 |
#' provided to the `expr` argument and the value of the `hash` argument, which |
| 261 |
#' means when the code or the `hash` argument changes, the \file{HASH} string |
| 262 |
#' may also change, and the old cache will be invalidated (if it exists). If you |
| 263 |
#' want to find the cache file, look for \file{.rds} files that contain 32 |
| 264 |
#' hexadecimal digits (consisting of 0-9 and a-z) at the end of the filename. |
| 265 |
#' |
| 266 |
#' The file can be other formats such as `.qs2`. See the `rw` argument of |
| 267 |
#' [cache_exec()]. |
| 268 |
#' |
| 269 |
#' The possible ways to invalidate the cache are: 1) change the code in `expr` |
| 270 |
#' argument; 2) delete the cache file manually or automatically through the |
| 271 |
#' argument `rerun = TRUE`; and 3) change the value of the `hash` argument. The |
| 272 |
#' first two ways should be obvious. For the third way, it makes it possible to |
| 273 |
#' automatically invalidate the cache based on changes in certain R objects. For |
| 274 |
#' example, when you run `cache_rds({ x + y })`, you may want to invalidate the |
| 275 |
#' cache to rerun `{ x + y }` when the value of `x` or `y` has been changed, and |
| 276 |
#' you can tell `cache_rds()` to do so by `cache_rds({ x + y }, hash = list(x, |
| 277 |
#' y))`. The value of the argument `hash` is expected to be a list, but it can |
| 278 |
#' also take a special value, `"auto"`, which means `cache_rds(expr)` will try |
| 279 |
#' to automatically figure out the global variables in `expr`, return a list of |
| 280 |
#' their values, and use this list as the actual value of `hash`. This behavior |
| 281 |
#' is most likely to be what you really want: if the code in `expr` uses an |
| 282 |
#' external global variable, you may want to invalidate the cache if the value |
| 283 |
#' of the global variable has changed. Here a \dQuote{global variable} means a |
| 284 |
#' variable not created locally in `expr`, e.g., for `cache_rds({ x <- 1; x + y |
| 285 |
#' })`, `x` is a local variable, and `y` is (most likely to be) a global |
| 286 |
#' variable, so changes in `y` should invalidate the cache. However, you know |
| 287 |
#' your own code the best. If you want to be completely sure when to invalidate |
| 288 |
#' the cache, you can always provide a list of objects explicitly rather than |
| 289 |
#' relying on `hash = "auto"`. |
| 290 |
#' |
| 291 |
#' By default (the argument `clean = TRUE`), old cache files will be |
| 292 |
#' automatically cleaned up. Sometimes you may want to use `clean = FALSE` (set |
| 293 |
#' the R global option `options(xfun.cache_rds.clean = FALSE)` if you want |
| 294 |
#' `FALSE` to be the default). For example, you may not have decided which |
| 295 |
#' version of code to use, and you can keep the cache of both versions with |
| 296 |
#' `clean = FALSE`, so when you switch between the two versions of code, it will |
| 297 |
#' still be fast to run the code. |
| 298 |
#' @param expr An R expression. |
| 299 |
#' @param rerun Whether to delete the RDS file, rerun the expression, and save |
| 300 |
#' the result again (i.e., invalidate the cache if it exists). |
| 301 |
#' @param file The *base* (see Details) cache filename under the directory |
| 302 |
#' specified by the `dir` argument. If not specified and this function is |
| 303 |
#' called inside a code chunk of a \pkg{knitr} document (e.g., an R Markdown |
| 304 |
#' document), the default is the current chunk label plus the extension |
| 305 |
#' \file{.rds}. The file can also be other formats (see Details). |
| 306 |
#' @param dir The path of the RDS file is partially determined by `paste0(dir, |
| 307 |
#' file)`. If not specified and the \pkg{knitr} package is available, the |
| 308 |
#' default value of `dir` is the \pkg{knitr} chunk option `cache.path` (so if |
| 309 |
#' you are compiling a \pkg{knitr} document, you do not need to provide this |
| 310 |
#' `dir` argument explicitly), otherwise the default is \file{cache/}. If you |
| 311 |
#' do not want to provide a `dir` but simply a valid path to the `file` |
| 312 |
#' argument, you may use `dir = ""`. |
| 313 |
#' @param hash A `list` object that contributes to the MD5 hash of the cache |
| 314 |
#' filename (see Details). It can also take a special character value |
| 315 |
#' `"auto"`. Other types of objects are ignored. |
| 316 |
#' @param clean Whether to clean up the old cache files automatically when |
| 317 |
#' `expr` has changed. |
| 318 |
#' @param ... Other arguments to be passed to the saving method such as |
| 319 |
#' [saveRDS()]. |
| 320 |
#' @note Changes in the code in the `expr` argument do not necessarily always |
| 321 |
#' invalidate the cache, if the changed code is [`parse`]`d` to the same |
| 322 |
#' expression as the previous version of the code. For example, if you have |
| 323 |
#' run `cache_rds({Sys.sleep(5);1+1})` before, running `cache_rds({ Sys.sleep( |
| 324 |
#' 5 ) ; 1 + 1 })` will use the cache, because the two expressions are |
| 325 |
#' essentially the same (they only differ in white spaces). Usually you can |
| 326 |
#' add/delete white spaces or comments to your code in `expr` without |
| 327 |
#' invalidating the cache. See the package vignette `vignette('xfun', package |
| 328 |
#' = 'xfun')` for more examples. |
| 329 |
#' |
| 330 |
#' When this function is called in a code chunk of a \pkg{knitr} document, you |
| 331 |
#' may not want to provide the filename or directory of the cache file, |
| 332 |
#' because they have reasonable defaults. |
| 333 |
#' |
| 334 |
#' Side-effects (such as plots or printed output) will not be cached. The |
| 335 |
#' cache only stores the last value of the expression in `expr`. |
| 336 |
#' |
| 337 |
#' The hash is calculated by saving the hash object to a temporary file via |
| 338 |
#' `saveRDS()` and getting the MD5 digest of the file. Since the file |
| 339 |
#' generated by `saveRDS()` may be platform-dependent, the cache may not be |
| 340 |
#' platform-agnostic. In other words, the cache saved on one platform may be |
| 341 |
#' invalidated on another platform even if nothing in the hash object has |
| 342 |
#' changed. By comparison, [cache_exec()] doesn't have this problem. |
| 343 |
#' @return If the cache file does not exist, run the expression and save the |
| 344 |
#' result to the file, otherwise read the cache file and return the value. |
| 345 |
#' @seealso [cache_exec()], which is more flexible (e.g., it supports in-memory |
| 346 |
#' caching and different read/write methods for cache files). |
| 347 |
#' @export |
| 348 |
#' @keywords internal |
| 349 |
#' @examples |
| 350 |
#' f = tempfile() # the cache file |
| 351 |
#' compute = function(...) { |
| 352 |
#' res = xfun::cache_rds({ |
| 353 |
#' Sys.sleep(1) |
| 354 |
#' 1:10 |
| 355 |
#' }, file = f, dir = '', ...) |
| 356 |
#' res |
| 357 |
#' } |
| 358 |
#' compute() # takes one second |
| 359 |
#' compute() # returns 1:10 immediately |
| 360 |
#' compute() # fast again |
| 361 |
#' compute(rerun = TRUE) # one second to rerun |
| 362 |
#' compute() |
| 363 |
#' unlink(paste0(f, '_*.rds')) |
| 364 |
cache_rds = function( |
| 365 |
expr = {}, rerun = FALSE, file = 'cache.rds', dir = 'cache/', |
| 366 |
hash = NULL, clean = getOption('xfun.cache_rds.clean', TRUE), ... |
| 367 |
) { |
| 368 |
if (loadable('knitr')) { |
| 369 |
if (!is.null(lab <- knitr::opts_current$get('label'))) { |
| 370 |
if (missing(file)) file = '.rds' |
| 371 |
if (startsWith(file, '.')) file = paste0(lab, file) |
| 372 |
} |
| 373 |
if (missing(dir) && !is.null(d <- knitr::opts_current$get('cache.path'))) |
| 374 |
dir = d |
| 375 |
} |
| 376 |
path = paste0(dir, file) |
| 377 |
if (file_ext(path) == '') path = paste0(path, '.rds') |
| 378 |
code = deparse(substitute(expr)) |
| 379 |
md5 = md5_obj(code) |
| 380 |
if (identical(hash, 'auto')) hash = global_vars(code, parent.frame(2)) |
| 381 |
if (is.list(hash)) md5 = md5_obj(c(md5, md5_obj(hash))) |
| 382 |
ext = file_ext(path) |
| 383 |
if (!ext %in% names(io_methods)) |
| 384 |
stop('The file extension ', ext, ' is not supported.') |
| 385 |
path = paste0(sans_ext(path), '_', md5, '.', ext) |
| 386 |
if (rerun) unlink(path) |
| 387 |
if (clean) clean_cache(path, ext) |
| 388 |
m = io_methods[[ext]] |
| 389 |
if (file_exists(path)) m$load(path) else { |
| 390 |
obj = expr # lazy evaluation |
| 391 |
dir_create(dirname(path)) |
| 392 |
m$save(obj, path, ...) |
| 393 |
obj |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
# an old hash function for cache_rds() only |
| 398 |
md5_obj = function(x) { |
| 399 |
f = tempfile(); on.exit(unlink(f), add = TRUE) |
| 400 |
if (is.character(x)) writeLines(x, f) else saveRDS(x, f) |
| 401 |
unname(tools::md5sum(f)) |
| 402 |
} |
| 403 |
|
| 404 |
#' Calculate the MD5 checksums of R objects |
| 405 |
#' |
| 406 |
#' [Serialize][serialize()] an object and calculate the checksum via |
| 407 |
#' [tools::md5sum()]. If `tools::md5sum()` does not have the argument `bytes`, |
| 408 |
#' the object will be first serialized to a temporary file, which will be |
| 409 |
#' deleted after the checksum is calculated, otherwise the raw bytes of the |
| 410 |
#' object will be passed to the `bytes` argument directly (which will be |
| 411 |
#' faster than writing to a temporary file). |
| 412 |
#' @param ... Any number of R objects. |
| 413 |
#' @return A character vector of the checksums of objects passed to `md5()`. If |
| 414 |
#' the arguments are named, the results will also be named. |
| 415 |
#' @export |
| 416 |
#' @examples |
| 417 |
#' x1 = 1; x2 = 1:10; x3 = seq(1, 10); x4 = iris; x5 = paste |
| 418 |
#' (m = xfun::md5(x1, x2, x3, x4, x5)) |
| 419 |
#' stopifnot(m[2] == m[3]) # x2 and x3 should be identical |
| 420 |
#' |
| 421 |
#' xfun::md5(x1 = x1, x2 = x2) # named arguments |
| 422 |
md5 = function(...) { |
| 423 |
obj = list(...) |
| 424 |
res = unlist(lapply(obj, md5_one)) |
| 425 |
names(res) = names(obj) |
| 426 |
res |
| 427 |
} |
| 428 |
|
| 429 |
md5_one = function(x) { |
| 430 |
# no need to write to a file if md5sum() has the 'bytes' arg (R > 4.4.1) |
| 431 |
m = tools::md5sum |
| 432 |
if ('bytes' %in% names(formals(m))) f = NULL else { |
| 433 |
f = tempfile(); on.exit(unlink(f), add = TRUE) |
| 434 |
} |
| 435 |
s = serialize(x, NULL, xdr = FALSE) |
| 436 |
s = tail(s, -14) # the first 14 bytes contain version info, etc |
| 437 |
if (is.null(f)) m(bytes = s) else { |
| 438 |
writeBin(s, f); unname(m(f)) |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
# clean up old cache files (those with the same base names as the new cache |
| 443 |
# file, e.g., if the new file is FOO_0123abc...z.rds, then FOO_9876def...x.rds |
| 444 |
# should be deleted) |
| 445 |
clean_cache = function(path, ext) { |
| 446 |
olds = list.files(dirname(path), sprintf('_[0-9a-f]{32}[.]%s$', ext), full.names = TRUE) |
| 447 |
olds = c(olds, path) # `path` may not exist; make sure it is in target paths |
| 448 |
base = basename(olds) |
| 449 |
keep = basename(path) == base # keep this file (will cache to this file) |
| 450 |
base = substr(base, 1, nchar(base) - 34 - nchar(ext)) # 33 = 1 (_) + 32 (md5 sum) + 1 (.) |
| 451 |
unlink(olds[(base == base[keep][1]) & !keep]) |
| 452 |
} |
| 453 |
|
| 454 |
#' Find global/local variables in R code |
| 455 |
#' |
| 456 |
#' Use [codetools::findGlobals()] and [codetools::findLocalsList()] to find |
| 457 |
#' global and local variables in a piece of code. Global variables are defined |
| 458 |
#' outside the code, and local variables are created inside the code. |
| 459 |
#' @param code Either a character vector of R source code, or an R expression. |
| 460 |
#' @param envir The global environment in which global variables are to be |
| 461 |
#' found. |
| 462 |
#' @return A character vector of the variable names. If the source code contains |
| 463 |
#' syntax errors, an empty character vector will be returned. |
| 464 |
#' @note Due to the flexibility of creating and getting variables in R, these |
| 465 |
#' functions are not guaranteed to find all possible variables in the code |
| 466 |
#' (e.g., when the code is hidden behind `eval()`). |
| 467 |
#' @export |
| 468 |
#' @examples |
| 469 |
#' x = 2 |
| 470 |
#' xfun::find_globals('y = x + 1') |
| 471 |
#' xfun::find_globals("y = get('x') + 1") # x is not recognized |
| 472 |
#' xfun::find_globals('y = zzz + 1') # zzz doesn't exist |
| 473 |
#' |
| 474 |
#' xfun::find_locals('y = x + 1') |
| 475 |
#' xfun::find_locals("assign('y', x + 1)") # it works |
| 476 |
#' xfun::find_locals("assign('y', x + 1, new.env())") # still smart |
| 477 |
#' xfun::find_locals("eval(parse(text = 'y = x + 1'))") # no way |
| 478 |
find_globals = function(code, envir = parent.frame()) { |
| 479 |
fun = function() {} |
| 480 |
if (is.language(code)) { |
| 481 |
body(fun) = code |
| 482 |
} else { |
| 483 |
fun = eval(parse2(c('function(){', code, '}'), fun), baseenv()) |
| 484 |
} |
| 485 |
obj = codetools::findGlobals(fun) |
| 486 |
intersect(obj, ls_all(envir, TRUE)) |
| 487 |
} |
| 488 |
|
| 489 |
# ls() all objects in the envir and if recursive, all parent environments until |
| 490 |
# globalenv() or emptyenv() |
| 491 |
ls_all = function(envir, recursive = FALSE) { |
| 492 |
x = ls(envir, all.names = TRUE) |
| 493 |
if (!recursive) return(x) |
| 494 |
while (TRUE) { |
| 495 |
# in theory, we shouldn't stop at global env but should keep recursion, but |
| 496 |
# in practice, objects in the parent environments of globalenv() (often |
| 497 |
# package namespaces) are unlikely to change and won't affect cache |
| 498 |
if (identical(envir, emptyenv()) || identical(envir, .GlobalEnv)) break |
| 499 |
envir = parent.env(envir) |
| 500 |
x = c(x, ls(envir, all.names = TRUE)) |
| 501 |
} |
| 502 |
unique(x) |
| 503 |
} |
| 504 |
|
| 505 |
#' @rdname find_globals |
| 506 |
#' @export |
| 507 |
find_locals = function(code) { |
| 508 |
code = if (is.language(code)) as.expression(code) else parse2(code) |
| 509 |
codetools::findLocalsList(code) |
| 510 |
} |
| 511 |
|
| 512 |
# if code cannot be parsed, return an empty expression |
| 513 |
parse2 = function(code, fallback = expression()) { |
| 514 |
tryCatch(parse_only(code), error = function(e) fallback) |
| 515 |
} |
| 516 |
|
| 517 |
# return a list of values of global variables in code |
| 518 |
global_vars = function(code, envir) { |
| 519 |
if (length(vars <- find_globals(code, envir)) > 0) |
| 520 |
mget(vars, envir, inherits = TRUE) |
| 521 |
} |
| 522 |
|
| 523 |
#' Download a file from a URL and cache it on disk |
| 524 |
#' |
| 525 |
#' This object provides methods to download files and cache them on disk. |
| 526 |
#' @format A list of methods: |
| 527 |
#' |
| 528 |
#' - `$get(url, type, handler)` downloads a URL, caches it, and returns the file |
| 529 |
#' content according to the value of `type` (possible values: `"text"` means |
| 530 |
#' the text content; `"base64"` means the base64 encoded data; `"raw"` means |
| 531 |
#' the raw binary content; `"auto"` is the default and means the type is |
| 532 |
#' determined by the content type in the URL headers). Optionally a `handler` |
| 533 |
#' function can be applied to the content. |
| 534 |
#' - `$list()` gives the list of cache files. |
| 535 |
#' - `$summary()` gives a summary of existing cache files. |
| 536 |
#' - `$remove(url, type)` removes a single cache file. |
| 537 |
#' - `$purge()` deletes all cache files. |
| 538 |
#' @export |
| 539 |
#' @examplesIf interactive() |
| 540 |
#' # the first time it may take a few seconds |
| 541 |
#' x1 = xfun::download_cache$get('https://www.r-project.org/') |
| 542 |
#' head(x1) |
| 543 |
#' |
| 544 |
#' # now you can get the cached content |
| 545 |
#' x2 = xfun::download_cache$get('https://www.r-project.org/') |
| 546 |
#' identical(x1, x2) # TRUE |
| 547 |
#' |
| 548 |
#' # a binary file |
| 549 |
#' x3 = xfun::download_cache$get('https://yihui.org/images/logo.png', 'raw') |
| 550 |
#' length(x3) |
| 551 |
#' |
| 552 |
#' # show a summary |
| 553 |
#' xfun::download_cache$summary() |
| 554 |
#' # remove a specific cache file |
| 555 |
#' xfun::download_cache$remove('https://yihui.org/images/logo.png', 'raw') |
| 556 |
#' # remove all cache files |
| 557 |
#' xfun::download_cache$purge() |
| 558 |
download_cache = local({ |
| 559 |
pre = 'url' # file prefix |
| 560 |
c_file = function(url, type) { |
| 561 |
file.path(cache_dir(), sprintf('%s_%s_%s.rds', pre, type, md5_one(url))) |
| 562 |
} |
| 563 |
read = function(url, type) { |
| 564 |
if (length(f <- c_file(url, type)) && file.exists(f)) readRDS(f) |
| 565 |
} |
| 566 |
write = function(url, type, data) { |
| 567 |
if (length(f <- c_file(url, type))) { |
| 568 |
dir_create(dirname(f)) |
| 569 |
saveRDS(data, f) |
| 570 |
} |
| 571 |
} |
| 572 |
list_cache = function() { |
| 573 |
d = cache_dir() |
| 574 |
list.files(d, sprintf('^%s_.+[.]rds$', pre), full.names = TRUE) |
| 575 |
} |
| 576 |
list( |
| 577 |
get = function(url, type = c('auto', 'text', 'base64', 'raw'), handler = NULL) { |
| 578 |
type = type[1] |
| 579 |
if (!is.null(x <- read(url, type))) return(x[[url]]) |
| 580 |
if ((auto <- type == 'auto')) type = if (length(grep( |
| 581 |
'^content-type:\\s+(text/.+|[^;]+;\\s+charset=utf-8)\\s*$', |
| 582 |
curlGetHeaders(url), ignore.case = TRUE |
| 583 |
))) 'text' else 'raw' |
| 584 |
dir_create(d <- tempfile()) |
| 585 |
on.exit(unlink(d, recursive = TRUE), add = TRUE) |
| 586 |
x = in_dir(d, { |
| 587 |
o = url_filename(url) |
| 588 |
download_file(url, o) |
| 589 |
switch( |
| 590 |
type, text = read_utf8(o), base64 = base64_uri(o), raw = read_bin(o) |
| 591 |
) |
| 592 |
}) |
| 593 |
if (is.function(handler)) x = handler(x) |
| 594 |
write(url, if (auto) 'auto' else type, setNames(list(x), url)) |
| 595 |
x |
| 596 |
}, |
| 597 |
summary = function() { |
| 598 |
f = list_cache() |
| 599 |
if (length(f) == 0) return(invisible()) |
| 600 |
t = gsub('^url_([^_]+)_.+$', '\\1', basename(f)) |
| 601 |
u = vapply(f, function(x) names(readRDS(x)), character(1)) |
| 602 |
s = file.size(f) |
| 603 |
if (length(f) > 1) message('Total size: ', format_bytes(sum(s))) |
| 604 |
d = data.frame(url = u, type = t, size = s, size_h = format_bytes(s)) |
| 605 |
rownames(d) = NULL |
| 606 |
unname(split(d, seq_len(nrow(d)))) |
| 607 |
}, |
| 608 |
list = list_cache, |
| 609 |
remove = function(url, type = 'auto') file.remove(c_file(url, type)), |
| 610 |
purge = function() { |
| 611 |
f = list_cache() |
| 612 |
s = file.size(f) |
| 613 |
i = file.remove(f) |
| 614 |
message(sprintf( |
| 615 |
"Purged %d cache file(s) from '%s' (%s)", |
| 616 |
sum(i), cache_dir(), format_bytes(sum(s[i])) |
| 617 |
)) |
| 618 |
} |
| 619 |
) |
| 620 |
}) |
| 621 |
|
| 622 |
cache_dir = if (getRversion() >= '4.0.0') function() { |
| 623 |
getOption('xfun.cache.dir', tools::R_user_dir('xfun', 'cache')) |
| 624 |
} else function() { |
| 625 |
getOption('xfun.cache.dir', file.path(tempdir(), 'xfun', 'cache')) |
| 626 |
} |