Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

customizable cache (closes #2176) #2340

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions R/cache.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ new_cache = function() {
}

cache_purge = function(hash) {
for (h in hash) unlink(paste(cache_path(h), c('rdb', 'rdx', 'RData'), sep = '.'))
for (h in hash) unlink(paste(cache_path(h), c('rds', 'rdb', 'rdx', 'RData'), sep = '.'))
}
Copy link
Collaborator Author

@atusy atusy Apr 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cache_purge() and clean_cache() take into account of limited file types/names.
There may be some cases where knitr should remove more files.

The example in the description saved an extra file as a part of cache, which will not be removed by knitr.

registerS3method("knit_cache_preprocess", "data.frame", function(x) {
  write.csv(x, "cache.csv") # NOTE: this file is not removed by `cache$purge()` or `clean_cache()`
  structure("cache.csv", class = "knit_cache_csv")
}, envir = asNamespace("knitr"))


cache_save = function(keys, outname, hash, lazy = TRUE) {
Expand All @@ -31,7 +31,9 @@ new_cache = function() {
if (!lazy) return() # everything has been saved; no need to make lazy db
# random seed is always load()ed
keys = as.character(setdiff(keys, '.Random.seed'))
getFromNamespace('makeLazyLoadDB', 'tools')(knit_global(), path, variables = keys)
envir = knit_global()
saveRDS(setNames(lapply(keys, function(k) knit_cache_preprocess(envir[[k]])), keys), paste(path, 'rds', sep = '.'))
unlink(paste(path, c('rdb', 'rdx'), sep = '.')) # migrate from former implementation
}

save_objects = function(objs, label, path) {
Expand All @@ -56,7 +58,17 @@ new_cache = function() {
cache_load = function(hash, lazy = TRUE) {
path = cache_path(hash)
if (!is_abs_path(path)) path = file.path(getwd(), path)
if (lazy) lazyLoad(path, envir = knit_global())
if (lazy) {
if (file.exists(paste(path, 'rdb', sep = '.'))) {
lazyLoad(path, envir = knit_global()) # backward compatibility
} else {
envir = knit_global()
obj = readRDS(paste(path, 'rds', sep = '.'))
for (nm in names(obj)) {
assign(nm, knit_cache_postprocess(obj[[nm]]), envir = envir)
}
}
}
# load output from last run if exists
if (file.exists(path2 <- paste(path, 'RData', sep = '.'))) {
load(path2, envir = knit_global())
Expand Down Expand Up @@ -87,10 +99,12 @@ new_cache = function() {
}

cache_exists = function(hash, lazy = TRUE) {
is.character(hash) &&
all(file.exists(paste(
cache_path(hash), if (lazy) c('rdb', 'rdx') else 'RData', sep = '.'
)))
if (!is.character(hash)) return(FALSE)
path = cache_path(hash)
if (!lazy) return(file.exists(paste(path, 'RData', sep = '.')))

# for backward compatibility, allow rdb/rdx
file.exists(paste(path, 'rds', sep = '.')) || all(file.exists(paste(path, c('rdb', 'rdx'), sep = '.')))
}

# when cache=3, code output is stored in .[hash], so cache=TRUE won't lose
Expand Down Expand Up @@ -128,10 +142,16 @@ cache_meta_name = function(hash) sprintf('.%s_meta', hash)
# a variable name to store the text output of code chunks
cache_output_name = function(hash) sprintf('.%s', hash)

# process cached objects before save and after read
knit_cache_preprocess = function(x, ...) UseMethod('knit_cache_preprocess')
knit_cache_preprocess.default = function(x, ...) x
knit_cache_postprocess = function(x, ...) UseMethod('knit_cache_postprocess')
knit_cache_postprocess.default = function(x, ...) x
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postprocess is skipped if a package is not loaded.


cache = new_cache()

# a regex for cache files
cache_rx = '_[abcdef0123456789]{32}[.](rdb|rdx|RData)$'
cache_rx = '_[abcdef0123456789]{32}[.](rds|rdb|rdx|RData)$'

#' Build automatic dependencies among chunks
#'
Expand Down Expand Up @@ -246,7 +266,7 @@ load_cache = function(
'Wrong cache databases for the chunk ', label,
'. You need to remove redundant cache files. Found ', paste(p2, collapse = ', ')
)
p2 = unique(gsub('[.](rdb|rdx|RData)$', '', p2))
p2 = unique(gsub('[.](rds|rdb|rdx|RData)$', '', p2))
if (length(p2) != 1) stop('Cannot identify the cache database for chunk ', label)
cache$load(file.path(p0, p2), lazy)
if (missing(object)) return(invisible(NULL))
Expand Down
Loading