| 1 |
## ideas borrowed from cacheSweave but not as sophisticated |
| 2 |
|
| 3 |
## closure adapted from Hadley's decumar: https://github.com/hadley/decumar |
| 4 |
## but it is using .rdb and .rdx as 'hard cache' (instead of cache in memory) |
| 5 |
new_cache = function() { |
| 6 |
|
| 7 |
cache_path = function(hash) { |
| 8 |
d = dirname(hash) |
| 9 |
if (!file.exists(d)) dir.create(d, showWarnings = FALSE, recursive = TRUE) |
| 10 |
file.path(d, basename(hash)) |
| 11 |
} |
| 12 |
|
| 13 |
cache_purge = function(hash) { |
| 14 |
for (h in hash) unlink(paste(cache_path(h), c('rdb', 'rdx', 'RData'), sep = '.')) |
| 15 |
} |
| 16 |
|
| 17 |
cache_save = function(keys, outname, hash, lazy = TRUE) { |
| 18 |
meta_name = cache_meta_name(hash) |
| 19 |
if (exists(meta_name, envir = knit_global())) outname = c(outname, meta_name) |
| 20 |
out0 = outname |
| 21 |
on.exit(rm(list = out0, envir = knit_global()), add = TRUE) |
| 22 |
# keys are new variables created; outname is the text output of a chunk |
| 23 |
path = cache_path(hash) |
| 24 |
# add random seed to cache if exists |
| 25 |
if (exists('.Random.seed', envir = globalenv(), inherits = FALSE)) { |
| 26 |
copy_env(globalenv(), knit_global(), '.Random.seed') |
| 27 |
outname = c('.Random.seed', outname) |
| 28 |
} |
| 29 |
if (!lazy) outname = c(keys, outname) |
| 30 |
save(list = outname, file = paste(path, 'RData', sep = '.'), envir = knit_global()) |
| 31 |
if (!lazy) return() # everything has been saved; no need to make lazy db |
| 32 |
# random seed is always load()ed |
| 33 |
keys = as.character(setdiff(keys, '.Random.seed')) |
| 34 |
getFromNamespace('makeLazyLoadDB', 'tools')(knit_global(), path, variables = keys) |
| 35 |
} |
| 36 |
|
| 37 |
save_objects = function(objs, label, path) { |
| 38 |
if (length(objs) == 0L) objs = '' |
| 39 |
# save object names |
| 40 |
x = paste(c(label, objs), collapse = '\t') |
| 41 |
if (file.exists(path)) { |
| 42 |
lines = read_utf8(path) |
| 43 |
lines = lines[lines != label] # knitr < 1.5 may have lines == label |
| 44 |
idx = substr(lines, 1L, nchar(label) + 1L) == paste0(label, '\t') |
| 45 |
if (any(idx)) { |
| 46 |
lines[idx] = x # update old objects |
| 47 |
} else lines = c(lines, x) |
| 48 |
} else lines = x |
| 49 |
write_utf8(lines, path) |
| 50 |
} |
| 51 |
cache_objects = function(keys, globals, label, path) { |
| 52 |
save_objects(keys, label, valid_path(path, '__objects')) |
| 53 |
save_objects(globals, label, valid_path(path, '__globals')) |
| 54 |
} |
| 55 |
|
| 56 |
cache_load = function(hash, lazy = TRUE) { |
| 57 |
path = cache_path(hash) |
| 58 |
if (!is_abs_path(path)) path = file.path(getwd(), path) |
| 59 |
if (lazy) lazyLoad(path, envir = knit_global()) |
| 60 |
# load output from last run if exists |
| 61 |
if (file.exists(path2 <- paste(path, 'RData', sep = '.'))) { |
| 62 |
load(path2, envir = knit_global()) |
| 63 |
if (exists('.Random.seed', envir = knit_global(), inherits = FALSE)) |
| 64 |
copy_env(knit_global(), globalenv(), '.Random.seed') |
| 65 |
name = cache_meta_name(hash) |
| 66 |
if (exists(name, envir = knit_global())) { |
| 67 |
.knitEnv$meta = c( |
| 68 |
.knitEnv$meta, get(name, envir = knit_global(), inherits = FALSE) |
| 69 |
) |
| 70 |
rm(list = name, envir = knit_global()) |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
cache_library = function(path, save = TRUE) { |
| 76 |
# save or load R packages |
| 77 |
path = valid_path(path, '__packages') |
| 78 |
if (save) { |
| 79 |
x = rev(.packages()) |
| 80 |
if (file.exists(path)) x = setdiff(c(read_utf8(path), x), xfun::base_pkgs()) |
| 81 |
write_utf8(x, path) |
| 82 |
} else { |
| 83 |
if (!file.exists(path)) return() |
| 84 |
for (p in read_utf8(path)) |
| 85 |
suppressPackageStartupMessages(library(p, character.only = TRUE)) |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
cache_exists = function(hash, lazy = TRUE) { |
| 90 |
is.character(hash) && |
| 91 |
all(file.exists(paste( |
| 92 |
cache_path(hash), if (lazy) c('rdb', 'rdx') else 'RData', sep = '.' |
| 93 |
))) |
| 94 |
} |
| 95 |
|
| 96 |
# when cache=3, code output is stored in .[hash], so cache=TRUE won't lose |
| 97 |
# output as cacheSweave does; for cache=1,2, output is the evaluate() list |
| 98 |
cache_output = function(hash, mode = 'character') { |
| 99 |
name = cache_output_name(hash) |
| 100 |
res = get(name, envir = knit_global(), mode = mode, inherits = FALSE) |
| 101 |
# clean up this hidden variable after we obtain its value |
| 102 |
if (mode == mode(res)) rm(list = name, envir = knit_global()) |
| 103 |
res |
| 104 |
} |
| 105 |
|
| 106 |
list(purge = cache_purge, save = cache_save, load = cache_load, objects = cache_objects, |
| 107 |
exists = cache_exists, output = cache_output, library = cache_library) |
| 108 |
} |
| 109 |
|
| 110 |
# analyze code and find out all possible variables (not necessarily global variables) |
| 111 |
find_symbols = function(code) { |
| 112 |
if (is.null(code) || length(p <- parse(text = code, keep.source = TRUE)) == 0) return() |
| 113 |
p = getParseData(p) |
| 114 |
p = p[p$terminal & p$token %in% c('SYMBOL', 'SYMBOL_FUNCTION_CALL', 'SPECIAL'), ] |
| 115 |
unique(p$text) |
| 116 |
} |
| 117 |
|
| 118 |
# a variable name to store the metadata object from code chunks |
| 119 |
cache_meta_name = function(hash) sprintf('.%s_meta', hash) |
| 120 |
# a variable name to store the text output of code chunks |
| 121 |
cache_output_name = function(hash) sprintf('.%s', hash) |
| 122 |
|
| 123 |
cache = new_cache() |
| 124 |
|
| 125 |
# a regex for cache files |
| 126 |
cache_rx = '_[abcdef0123456789]{32}[.](rdb|rdx|RData)$' |
| 127 |
|
| 128 |
#' Build automatic dependencies among chunks |
| 129 |
#' |
| 130 |
#' When the chunk option \code{autodep = TRUE}, all names of objects created in |
| 131 |
#' a chunk will be saved in a file named \file{__objects} and all global objects |
| 132 |
#' used in a chunk will be saved to \file{__globals}. This function can analyze |
| 133 |
#' object names in these files to automatically build cache dependencies, which |
| 134 |
#' is similar to the effect of the \code{dependson} option. It is supposed to be |
| 135 |
#' used in the first chunk of a document and this chunk must not be cached. |
| 136 |
#' @param path Path to the dependency file. |
| 137 |
#' @param labels A vector of labels of chunks for which the dependencies will be |
| 138 |
#' built. By default, dependencies for all chunks will be built. |
| 139 |
#' @return \code{NULL}. The dependencies are built as a side effect. |
| 140 |
#' @note Be cautious about \code{path}: because this function is used in a |
| 141 |
#' chunk, the working directory when the chunk is evaluated is the directory |
| 142 |
#' of the input document in \code{\link{knit}}, and if that directory differs |
| 143 |
#' from the working directory before calling \code{knit()}, you need to adjust |
| 144 |
#' the \code{path} argument here to make sure this function can find the cache |
| 145 |
#' files \file{__objects} and \file{__globals}. |
| 146 |
#' @export |
| 147 |
#' @seealso \code{\link{dep_prev}} |
| 148 |
#' @references \url{https://yihui.org/knitr/demo/cache/} |
| 149 |
dep_auto = function(path = opts_chunk$get('cache.path'), labels = all_labels()) { |
| 150 |
# this function should be evaluated in the original working directory |
| 151 |
owd = setwd(opts_knit$get('output.dir')); on.exit(setwd(owd)) |
| 152 |
paths = valid_path(path, c('__objects', '__globals')) |
| 153 |
locals = parse_objects(paths[1L]); globals = parse_objects(paths[2L]) |
| 154 |
if (is.null(locals) || is.null(globals)) return(invisible(NULL)) |
| 155 |
if (!identical(names(locals), names(globals))) { |
| 156 |
warning('corrupt dependency files? \ntry remove ', paste(paths, collapse = '; ')) |
| 157 |
return(invisible(NULL)) |
| 158 |
} |
| 159 |
nms = intersect(all_labels(), names(locals)) # guarantee correct order |
| 160 |
for (i in match(labels, nms)) { |
| 161 |
# ignore first chunk (i < 2); locals may contain old chunk names (i will be NA) |
| 162 |
if (is.na(i) || i < 2 || length(g <- globals[[nms[i]]]) == 0) next |
| 163 |
for (j in 1:(i - 1L)) { |
| 164 |
# check if current globals are in old locals |
| 165 |
if (any(g %in% locals[[nms[j]]])) |
| 166 |
dep_list$set(setNames(list(unique(c(dep_list$get(nms[j]), nms[i]))), nms[j])) |
| 167 |
} |
| 168 |
} |
| 169 |
} |
| 170 |
# parse objects in dependency files |
| 171 |
parse_objects = function(path) { |
| 172 |
if (!file.exists(path)) return() |
| 173 |
lines = strsplit(read_utf8(path), '\t') |
| 174 |
if (length(lines) < 2L) return() # impossible for dependson |
| 175 |
objs = lapply(lines, `[`, -1L) |
| 176 |
names(objs) = lapply(lines, `[`, 1L) |
| 177 |
objs |
| 178 |
} |
| 179 |
|
| 180 |
#' Load the cache database of a code chunk |
| 181 |
#' |
| 182 |
#' If a code chunk has turned on the chunk option \code{cache = TRUE}, a cache |
| 183 |
#' database will be established after the document is compiled. You can use this |
| 184 |
#' function to manually load the database anywhere in the document (even before |
| 185 |
#' the code chunk). This makes it possible to use objects created later in the |
| 186 |
#' document earlier, e.g. in an inline R expression before the cached code |
| 187 |
#' chunk, which is normally not possible because \pkg{knitr} compiles the |
| 188 |
#' document in a linear fashion, and objects created later cannot be used before |
| 189 |
#' they are created. |
| 190 |
#' @param label The chunk label of the code chunk that has a cache database. |
| 191 |
#' @param object The name of the object to be fetched from the database. If it |
| 192 |
#' is missing, \code{NULL} is returned). |
| 193 |
#' @param notfound A value to use when the \code{object} cannot be found. |
| 194 |
#' @param path Path of the cache database (normally set in the global chunk |
| 195 |
#' option \code{cache.path}). |
| 196 |
#' @param dir Path to use as the working directory. Defaults to the output |
| 197 |
#' directory if run inside a \pkg{knitr} context and to the current working |
| 198 |
#' directory otherwise. Any relative \code{path} is defined from \code{dir}. |
| 199 |
#' @param envir Environment to use for cache loading, into which all objects in |
| 200 |
#' the cache for the specified chunk (not just that in \code{object}) will be |
| 201 |
#' loaded. Defaults to the value in \code{\link{knit_global}}. |
| 202 |
#' @param lazy Whether to \code{\link{lazyLoad}} the cache database (depending |
| 203 |
#' on the chunk option \code{cache.lazy = TRUE} or \code{FALSE} of that code |
| 204 |
#' chunk). |
| 205 |
#' @note Apparently this function loads the value of the object from the |
| 206 |
#' \emph{previous} run of the document, which may be problematic when the |
| 207 |
#' value of the object becomes different the next time the document is |
| 208 |
#' compiled. Normally you must compile the document twice to make sure the |
| 209 |
#' cache database is created, and the object can be read from it. Please use |
| 210 |
#' this function with caution. |
| 211 |
#' @references See the example #114 at |
| 212 |
#' \url{https://github.com/yihui/knitr-examples}. |
| 213 |
#' @return Invisible \code{NULL} when \code{object} is not specified (the cache |
| 214 |
#' database will be loaded as a side effect), otherwise the value of the |
| 215 |
#' object if found. |
| 216 |
#' @export |
| 217 |
load_cache = function( |
| 218 |
label, object, notfound = 'NOT AVAILABLE', path = opts_chunk$get('cache.path'), |
| 219 |
dir = opts_knit$get('output.dir'), envir = NULL, lazy = TRUE |
| 220 |
) { |
| 221 |
if (is.null(dir)) dir = "." |
| 222 |
owd = setwd(dir); on.exit(setwd(owd), add = TRUE) |
| 223 |
if (!is.null(envir)) { |
| 224 |
oldenv = .knitEnv$knit_global |
| 225 |
on.exit(.knitEnv$knit_global <- oldenv, add = TRUE) |
| 226 |
.knitEnv$knit_global = envir |
| 227 |
} |
| 228 |
|
| 229 |
path = valid_path(path, label) |
| 230 |
p0 = dirname(path); p1 = basename(path) |
| 231 |
p2 = list.files(p0, cache_rx) |
| 232 |
if (length(p2) == 0) return(notfound) |
| 233 |
p2 = p2[substr(p2, 1, nchar(p1)) == p1] |
| 234 |
if (length(p2) == 0) return(notfound) |
| 235 |
if (length(p2) > 3) stop( |
| 236 |
'Wrong cache databases for the chunk ', label, |
| 237 |
'. You need to remove redundant cache files. Found ', paste(p2, collapse = ', ') |
| 238 |
) |
| 239 |
p2 = unique(gsub('[.](rdb|rdx|RData)$', '', p2)) |
| 240 |
if (length(p2) != 1) stop('Cannot identify the cache database for chunk ', label) |
| 241 |
cache$load(file.path(p0, p2), lazy) |
| 242 |
if (missing(object)) return(invisible(NULL)) |
| 243 |
if (exists(object, envir = knit_global(), inherits = FALSE)) { |
| 244 |
get(object, envir = knit_global(), inherits = FALSE) |
| 245 |
} else notfound |
| 246 |
} |
| 247 |
|
| 248 |
#' Make later chunks depend on previous chunks |
| 249 |
#' |
| 250 |
#' This function can be used to build dependencies among chunks so that all |
| 251 |
#' later chunks depend on previous chunks, i.e. whenever the cache of a previous |
| 252 |
#' chunk is updated, the cache of all its later chunks will be updated. |
| 253 |
#' @return \code{NULL}; the internal dependency structure is updated as a side |
| 254 |
#' effect. |
| 255 |
#' @export |
| 256 |
#' @seealso \code{\link{dep_auto}} |
| 257 |
#' @references \url{https://yihui.org/knitr/demo/cache/} |
| 258 |
dep_prev = function() { |
| 259 |
labs = names(knit_code$get()) |
| 260 |
if ((n <- length(labs)) < 2L) return() # one chunk or less; no sense of deps |
| 261 |
opts_knit$set(warn.uncached.dep = FALSE) |
| 262 |
for (i in 1L:(n - 1L)) { |
| 263 |
dep_list$set(setNames(list(labs[(i + 1L):n]), labs[i])) |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
#' An unevaluated expression to return .Random.seed if exists |
| 268 |
#' |
| 269 |
#' This expression returns \code{.Random.seed} when \code{eval(rand_seed)} and |
| 270 |
#' \code{NULL} otherwise. |
| 271 |
#' |
| 272 |
#' It is designed to work with \code{opts_chunk$set(cache.extra = rand_seed)} |
| 273 |
#' for reproducibility of chunks that involve with random number generation. See |
| 274 |
#' references. |
| 275 |
#' @export |
| 276 |
#' @format NULL |
| 277 |
#' @references \url{https://yihui.org/knitr/demo/cache/} |
| 278 |
#' @examples eval(rand_seed) |
| 279 |
#' rnorm(1) # .Random.seed is created (or modified) |
| 280 |
#' eval(rand_seed) |
| 281 |
rand_seed = quote({ |
| 282 |
.GlobalEnv$.Random.seed |
| 283 |
}) |
| 284 |
|
| 285 |
#' Clean cache files that are probably no longer needed |
| 286 |
#' |
| 287 |
#' If you remove or rename some cached code chunks, their original cache files |
| 288 |
#' will not be automatically cleaned. You can use this function to identify |
| 289 |
#' these possible files, and clean them if you are sure they are no longer |
| 290 |
#' needed. |
| 291 |
#' @param clean Boolean; whether to remove the files. |
| 292 |
#' @param path Path to the cache. |
| 293 |
#' @note The identification is not guaranteed to be correct, especially when |
| 294 |
#' multiple documents share the same cache directory. You are recommended to |
| 295 |
#' call \code{clean_cache(FALSE)} and carefully check the list of files (if |
| 296 |
#' any) before you really delete them (\code{clean_cache(TRUE)}). |
| 297 |
#' |
| 298 |
#' This function must be called within a code chunk in a source document, |
| 299 |
#' since it needs to know all chunk labels of the current document to |
| 300 |
#' determine which labels are no longer present, and delete cache |
| 301 |
#' corresponding to these labels. |
| 302 |
#' @export |
| 303 |
clean_cache = function(clean = FALSE, path = opts_chunk$get('cache.path')) { |
| 304 |
odir = opts_knit$get('output.dir') |
| 305 |
if (is.null(odir)) { |
| 306 |
warning('This function must be called inside a source document') |
| 307 |
return() |
| 308 |
} |
| 309 |
owd = setwd(odir); on.exit(setwd(owd)) |
| 310 |
if (file_test('-d', path)) { |
| 311 |
p0 = path; p1 = '' |
| 312 |
} else { |
| 313 |
p0 = dirname(path); p1 = basename(path) |
| 314 |
} |
| 315 |
files = list.files(p0, cache_rx, full.names = TRUE) |
| 316 |
if (length(files) == 0) return() |
| 317 |
base = basename(files) |
| 318 |
labs = .knitEnv$labels |
| 319 |
if (length(labs) == 0) return() |
| 320 |
i = !(sub(cache_rx, '', base) %in% paste0(p1, labs)) |
| 321 |
if (p1 != '') i = i & (substr(base, 1, nchar(p1)) == p1) |
| 322 |
if (!any(i)) return() |
| 323 |
if (clean) unlink(files[i]) else message( |
| 324 |
'Clean these cache files?\n\n', one_string(files[i]), '\n' |
| 325 |
) |
| 326 |
} |