diff --git a/.Rbuildignore b/.Rbuildignore deleted file mode 100644 index cde952b..0000000 --- a/.Rbuildignore +++ /dev/null @@ -1 +0,0 @@ -TODO.md \ No newline at end of file diff --git a/.github/workflows/pr_check.yml b/.github/workflows/pr_check.yml new file mode 100644 index 0000000..255e5dc --- /dev/null +++ b/.github/workflows/pr_check.yml @@ -0,0 +1,91 @@ +name: PR CMD check & build site + +on: + push: + paths: + - 'DESCRIPTION' + - '**.yml' + branches: + - RELEASE_3_21 + - pkgdown + +env: + R_REMOTES_NO_ERRORS_FROM_WARNINGS: true + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + CRAN: https://p3m.dev/cran/__linux__/noble/latest + BIOC_RELEASE: RELEASE_3_21 + +jobs: + check: + runs-on: ubuntu-latest + container: bioconductor/bioconductor_docker:RELEASE_3_21 + + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + with: + ref: ${{ env.BIOC_RELEASE }} + + - name: Copy .github and _pkgdown.yml + run: | + git config --global --add safe.directory /__w/${{ github.event.repository.name }}/${{ github.event.repository.name }} + git fetch origin pkgdown + git checkout origin/pkgdown -- .github + git checkout origin/pkgdown -- _pkgdown.yml + + - name: Query dependencies + run: | + BiocManager::install(c("covr", "BiocCheck")) + saveRDS(remotes::dev_package_deps(dependencies = TRUE), ".github/depends.Rds", version = 2) + shell: Rscript {0} + + - name: Cache R packages + uses: actions/cache@v4 + with: + path: /usr/local/lib/R/site-library + key: ${{ runner.os }}-r-${{ env.BIOC_RELEASE }}-${{ hashFiles('.github/depends.Rds') }} + restore-keys: ${{ runner.os }}-r-${{ env.BIOC_RELEASE }}- + + - name: Install Dependencies + run: | + remotes::install_deps(dependencies = TRUE, repos = BiocManager::repositories()) + BiocManager::install(c("rcmdcheck", "BiocCheck"), ask = FALSE, update = TRUE) + shell: Rscript {0} + + - name: Check Package + env: + _R_CHECK_CRAN_INCOMING_REMOTE_: false + run: rcmdcheck::rcmdcheck(args = "--no-manual", error_on = "error", check_dir = "check") + shell: Rscript {0} + + - name: Run BiocCheck + id: bioccheck + run: | + BiocCheck::BiocCheck( + dir('check', 'tar.gz$', full.names = TRUE), + `quit-with-status` = TRUE, `no-check-bioc-help` = TRUE + ) + shell: Rscript {0} + + - name: Build pkgdown + run: | + PATH=$PATH:$HOME/bin/ Rscript -e 'pkgdown::build_site()' + + - name: Upload pkgdown artifact + uses: actions/upload-pages-artifact@v3 + with: + path: docs + + deploy: + needs: check + permissions: + contents: write + pages: write + id-token: write + runs-on: ubuntu-24.04 + + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 + diff --git a/DESCRIPTION b/DESCRIPTION deleted file mode 100644 index 27d38ca..0000000 --- a/DESCRIPTION +++ /dev/null @@ -1,40 +0,0 @@ -Package: BiocFileCache -Title: Manage Files Across Sessions -Version: 3.5.0 -Authors@R: c(person("Lori", "Shepherd", - email = "lori.shepherd@roswellpark.org", - role = c("aut", "cre")), - person("Martin", "Morgan", - email = "martin.morgan@roswellpark.org", - role = "aut")) -Description: This package creates a persistent on-disk cache of files - that the user can add, update, and retrieve. It is useful for - managing resources (such as custom Txdb objects) that are costly - or difficult to create, web resources, and data files used across - sessions. -Depends: - R (>= 3.4.0), - dbplyr (>= 1.0.0) -Imports: - methods, - stats, - utils, - dplyr, - RSQLite, - DBI, - filelock, - curl, - httr2 -BugReports: https://github.com/Bioconductor/BiocFileCache/issues -DevelopmentURL: https://github.com/Bioconductor/BiocFileCache -License: Artistic-2.0 -Encoding: UTF-8 -RoxygenNote: 7.3.2 -biocViews: DataImport -VignetteBuilder: knitr -Suggests: - testthat, - knitr, - BiocStyle, - rmarkdown, - rtracklayer diff --git a/NAMESPACE b/NAMESPACE deleted file mode 100644 index f46e15f..0000000 --- a/NAMESPACE +++ /dev/null @@ -1,85 +0,0 @@ -# Generated by roxygen2: do not edit by hand - -export("bfcmeta<-") -export(BiocFileCache) -export(bfcadd) -export(bfccache) -export(bfccount) -export(bfcdownload) -export(bfcinfo) -export(bfcmeta) -export(bfcmetalist) -export(bfcmetaremove) -export(bfcneedsupdate) -export(bfcnew) -export(bfcpath) -export(bfcquery) -export(bfcquerycols) -export(bfcremove) -export(bfcrid) -export(bfcrpath) -export(bfcsync) -export(bfcupdate) -export(cleanbfc) -export(exportbfc) -export(getBFCOption) -export(importbfc) -export(makeBiocFileCacheFromDataFrame) -export(makeCachedActiveBinding) -export(removebfc) -export(setBFCOption) -exportMethods("[") -exportMethods("[[") -exportMethods("[[<-") -exportMethods("bfcmeta<-") -exportMethods(bfcadd) -exportMethods(bfccache) -exportMethods(bfccount) -exportMethods(bfcdownload) -exportMethods(bfcinfo) -exportMethods(bfcmeta) -exportMethods(bfcmetalist) -exportMethods(bfcmetaremove) -exportMethods(bfcneedsupdate) -exportMethods(bfcnew) -exportMethods(bfcpath) -exportMethods(bfcquery) -exportMethods(bfcquerycols) -exportMethods(bfcremove) -exportMethods(bfcrid) -exportMethods(bfcrpath) -exportMethods(bfcsync) -exportMethods(bfcupdate) -exportMethods(cleanbfc) -exportMethods(exportbfc) -exportMethods(importbfc) -exportMethods(length) -exportMethods(makeBiocFileCacheFromDataFrame) -exportMethods(removebfc) -exportMethods(show) -import(RSQLite) -import(dbplyr) -import(httr2) -import(methods) -importFrom(DBI,dbExecute) -importFrom(DBI,dbSendStatement) -importFrom(curl,curl_escape) -importFrom(dplyr,"%>%") -importFrom(dplyr,collect) -importFrom(dplyr,filter) -importFrom(dplyr,left_join) -importFrom(dplyr,mutate) -importFrom(dplyr,n) -importFrom(dplyr,select) -importFrom(dplyr,summarize) -importFrom(dplyr,tbl) -importFrom(filelock,lock) -importFrom(filelock,unlock) -importFrom(stats,setNames) -importFrom(tools,R_user_dir) -importFrom(utils,capture.output) -importFrom(utils,packageVersion) -importFrom(utils,tar) -importFrom(utils,untar) -importFrom(utils,unzip) -importFrom(utils,zip) diff --git a/NEWS b/NEWS deleted file mode 100644 index 98aaa0b..0000000 --- a/NEWS +++ /dev/null @@ -1,268 +0,0 @@ -CHANGES IN VERSION 2.99.0 ----------------------- - -MAJOR UPDATES - - o Update downloading method from httr to httr2 - -BUG FIX - - o (2.99.1) Soft failure for if HEAD does not work. Will still download and - add to cache without caching information. Additionally fix bug so config can - be passed down to HEAD call from bfcneedsupdate, bfcadd, and bfcrpath. - - o (2.99.4) Fix bug to pass proxy down to HEAD call - -NEW FEATURE - - o (2.99.2) Add progress argument to bfcadd/bfcdownload to control if a - progress bar is displayed during an interactive session - -CHANGES IN VERSION 2.15 ----------------------- - -BUG FIX - - o (2.15.1) Fix issue trying to create multiple caches in single R session - -CHANGES IN VERSION 2.11 ----------------------- - -BUG FIX - - o (2.11.1) Merge PR to fix dbplyr compatibility issue - -CHANGES IN VERSION 2.9 ----------------------- - -USER VISIBLE CHANGE - - o (2.9.1) Add documentation for operating behind a proxy - -CHANGES IN VERSION 2.7 ----------------------- - -USER VISIBLE CHANGE - - o (2.7.1) Remove rappdirs officially from package after deprecating - functionality and moving to using default R tools caching location. - -BUG FIX - - o (2.7.2) Fix mismatch of arguments from function to generic for bfcupdate - -CHANGES IN VERSION 2.5 ----------------------- - -ENHANCEMENT - - o (2.5.2) Add option to override unique identifer when adding files to the - cache. This will allow exact match of original file name. - -BUG FIX - - o (2.5.1) ERROR if interactively decide not to removebfc - -CHANGES IN VERSION 2.3 ----------------------- - -ENHANCEMENT - - o (2.3.4) Add instructions for a shared cache across multiple users of a system - o (2.3.2) Add direct SQL calls for certain retrieval functions to speed up - access time. This will speed up the bfcquery function as well as any - function tha utilized the underlying .sql_get_field, .get_all_rids or - .get_all_web_rids. - o (2.3.1) Add @LTLA solution for making bfcrpath thread safe - -CHANGES IN VERSION 2.1 ----------------------- - -MAJOR UPDATES - - o (2.1.1) Change caching location warning/deprecation to an ERROR in - preparation for removal of dependency next release. - -CHANGES IN VERSION 1.99 ----------------------- - -MAJOR UPDATES - - o (1.99.0) The default caching location has changed. Instead of - rappdirs::user_cache_dir using tools::R_user_dir. To avoid conflicting - caches, a user will have to manage an old cache location before - proceeding. Information for handling an old cache location is provided in - the vignette. - o (1.99.0) Another major change, a default caching location is automatically - created in a non interactive session instead of using a temporary - location. In an interactive session, a user is still prompted for - permission. - o (1.99.0) An enviornment variable may be set system wide or user wide to - control the default caching location: BFC_CACHE. Note: do not use R - variables or command line export to set this variable. It must be set system - wide or user wide for reproducibility in future R sessions or else it must - be specified upon ever usage. It must be set before calling - library(BiocFileCache) to take effect. - o (1.99.0) Fixes partial argument matching error in SQL function SQLExecute - o (1.15.1) Added file locking for thread-safe SQL operations. Thanks for the PR @LTLA - -BUG FIX - - o (1.99.6) cleanbfc() incorrect format string; see - https://github.com/Bioconductor/BiocFileCache/issues/31 - -CHANGES IN VERSION 1.11 ----------------------- - -BUG FIX - - o (1.11.5) Update dplyr functions for dplyr_1.0.0 release - o (1.11.2) Fixes run of examples. Different result manual vs interactive so - have conditional that will allow complete example if run by user rather than - run automatically through the checks. - -NEW FEATURES - - o (1.11.1) Add makeCachedActiveBinding(). Allows data to be cached during - ActiveBinding call. Avoids callback function executing data retrieval - everytime. - - o (1.11.3) Only asks for / reports use of temporary cache once per - session. https://github.com/Bioconductor/TENxBrainData/issues/7 - -CHANGES IN VERSION 1.7 ----------------------- - -BUG FIX - - o (1.7.10) Fix date comparison to use as.POSIXlt instead of as.Date. This - catches the rare edge case if a remote resource is updated twice in a day - and a download happened in between the two. - o (1.7.9) Make creation of database atomic commits - o (1.7.8) Make adding resource to database atomic commits - o (1.7.4) Limit where possible opening database in RW mode. Use read-only - mode whereever possible to avoid database locking - o (1.7.2) Fix bug in multi path addition through bfcadd/bfcrpaths. The - function was assuming all files had same rtype and action. Now can - vectorize - o (1.7.1) Fix man documentation example. Interactive vs non interactive - session - -CHANGES IN VERSION 1.5 ----------------------- - -NEW FEATURES - - o (v. 1.5.1) Add 'exact = ' for exact matching in bfcquery(), - bfcrpath(). (v. 1.5.2) defaults to TRUE for bfcrpath() - -BUG FIX - - o (v. 1.5.2) bfcrpath() more robust when adding regular expression - rnames. - -USER-VISIBLE CHANGES - - o (v. 1.5.4) bfcpath() implementation change. Only displays rpath and can - work with multiple rids. bfcpath only for rpath access while bfcrpath is the - option to get or add. - -CHANGES IN VERSION 1.3 ----------------------- - -NEW FEATURES - - o (v. 1.3.35) Save a post download processed file to cache. - o (v. 1.3.28) Add ask = TRUE argument to BiocFileCache(). - o (v. 1.3.24) Add function makeBiocFileCacheFromDataFrame to - convert data.frame to BiocFileCache - o (v. 1.3.19) etag now checked in addition to last modified time to - determine if local version of file is current - o (v. 1.3.16) importbfc to load output of exportbfc - o (v. 1.3.15) exportbfc allows users to create exportable archive of bfc - related files - o (v. 1.3.11) bfcisrelative checks for rtype='local' in addition to relative - o (v. 1.3.11) Helper function to check rtype for local but - relative, and web and update if necessary - o (v. 1.3.10) Add function to check portability of BiocFileCache: - bfcisrelative - o (v. 1.3.10) Add function to convert rpaths for portability: bfcrelative - o (v. 1.3.9) Optionally download web resource when adding to cache - bfcadd(download=TRUE) - -SCHEMA CHANGE - - o (v. 1.3.36) expires added - o (v. 1.3.19) etag added - o (v. 1.3.9) Last modified time default is NA - -USER-VISIBLE CHANGES - - o (v. 1.3.38) ... argument exposed and pased to GET, this includes bfcadd - which original ... was pasesed to file.copy. This use of ... is used in bfc - functions bfcadd(), bfcupdate() and bfcdownload() which could potential - download the file. - o (v. 1.3.30) bfcnew(), bfcadd(), accept vector arguments; - performance improvements and - o (v. 1.3.25) bfcinfo and bfcquery will show full rpaths even if - stored as relative - o (v. 1.3.22) prompt user only once when using default cache - o (v. 1.3.17) prompt user when overwriting exisiting file - o (v. 1.3.16) add importbfc to extract output of exportbfc and - load bfc object - o (v. 1.3.16) added exportbfc to export bfc or subset of bfc - o (v. 1.3.16) bfcisportblae and bfcportbale removed for exportbfc - o (v. 1.3.14) upon bfc creation, option to update to most current schema - o (v. 1.3.13) bfcportable operates over all offending ids instead - of asking individually - o (v. 1.3.12) bfcisrelative/bfcrelative changed to - bfcisportbale/bfcportable - o (v. 1.3.11) web resource rpaths are stored as relative links - o (v. 1.3.9) If web resource was not downloaded, bfcneedsupdate is TRUE - o (v. 1.3.9) Local and non downloaded web will have last modified - time as NA - o (v. 1.3.6) Update how default cache location is determined - o (v. 1.3.1) Expose GET::config argument to web resource functions - -BUG CORRECTION - - o (v. 1.3.40) correct trycatch with cache_info. cache_info bug workaround - orginally output NA even if present, now manually grab values if present - o (v. 1.3.37) correct which functions update access_time - o (v. 1.3.26) patch for cache_info after returning etag and last_modified - o (v. 1.3.4) patch for cache_info bug - - - -CHANGES IN VERSION 1.1 ----------------------- - -NEW FEATURES - - o (v. 1.1.7) bfcmeta() and friends allows arbitrary metadata on - records and ability to query bfcmeta data. - -USER-VISIBLE CHANGES - - o (v. 1.1.16) if httr::HEAD fails don't try httr::GET, just report not - available - - o (v. 1.1.7) bfcquery() syntax changed to grep(), rather than SQL - 'LIKE'. - - o (v. 1.1.7) bfcquery() supports user-specified 'fields='. - - o (v. 1.1.5) queryCount renamed to bfccount - - o (v. 1.1.2) Add user specified extension to file in cache - - o (v. 1.1.2) Use dbExecute/dbSendStatement rather than pasting query - - o Files in cache retain basename and extension of original file - -CHANGES IN VERSION 0.99.0 -------------------------- - -SIGNIFICANT NEW FEATURES - - o First Bioconductor release. diff --git a/R/BFCOption.R b/R/BFCOption.R deleted file mode 100644 index 9d1c7d2..0000000 --- a/R/BFCOption.R +++ /dev/null @@ -1,43 +0,0 @@ -.bfc_options <- new.env(parent=emptyenv()) - - -.bfc_option_key <- function(key0=c("CACHE")) - match.arg(key0) - -#' BFCOption -#' These functions help get and set an R variable CACHE that controls the -#' default caching location. -#' @details -#' Currently the only supported option is CACHE. This controls the default -#' location of the BiocFileCache caching directory. By default the value is -#' established by \code{tools::R_user_dir("BiocFileCache",which="cache")}. This -#' value can also be defaultly set by using system and global environment -#' variables visible \emph{before} the package is loaded. The variable that -#' should be set if utilized is \dQuote{BFC_CACHE} -#' @param arg character(1) option to get or set -#' @param value The value to be assigned to the designated option -#' @return Value of request option or invisible successfully set option -#' @examples -#' origPath = getBFCOption('CACHE') -#' \donttest{setBFCOption('CACHE', "~/.myBFC") } -#' @name BFCOption -#' @author Lori Shepherd -#' @aliases setBFCOption -#' @aliases getBFCOption -#' @export getBFCOption -#' @export setBFCOption -setBFCOption <- function(arg, value) -{ - key <- .bfc_option_key(toupper(trimws(arg))) - - .bfc_options[[key]] <- switch(key, CACHE={ - value <- as.character(value) - stopifnot(length(value)==1) - value - }) -} - -getBFCOption <- function(arg) { - arg <- .bfc_option_key(toupper(arg)) - .bfc_options[[arg]] -} diff --git a/R/BiocFileCache-class.R b/R/BiocFileCache-class.R deleted file mode 100644 index c38f08d..0000000 --- a/R/BiocFileCache-class.R +++ /dev/null @@ -1,1511 +0,0 @@ -#' @import methods -#' @import httr2 -#' @importFrom utils tar zip untar unzip -#' @importFrom dplyr mutate -#' @importFrom tools R_user_dir - -.BiocFileCacheBase = setClass( - "BiocFileCacheBase", - slots=c(cache="character") -) - -.BiocFileCacheReadOnly = setClass( - "BiocFileCacheReadOnly", - contains="BiocFileCacheBase", - slots=c(rid="character") -) - -.BiocFileCache = setClass( - "BiocFileCache", - contains="BiocFileCacheBase" -) - -#' BiocFileCache class -#' -#' This class represents the location of files stored on disk. Use the -#' return value to add and retrieve files that persist across -#' sessions. -#' -#' @details The package defines 'BiocFileCache', 'BiocFileCacheBase' and -#' 'BiocFileCacheReadOnly' classes. -#' -#' Slots unique to 'BiocFileCache' and related classes: -#' \describe{ -#' \item{'cache': }{character(1) on-disk location (directory path) of the -#' cache} -#' \item{'rid': }{character() of unique rids in the cache. } -#' } -#' -#' The cache creates an RSQLite database to keep track of local and remote -#' resources. Each item located in the database will have the following -#' information: -#' \describe{ -#' \item{'rid': }{resource id. Autogenerated. This is a unique identifier -#' automatically generated when a resource is added to the cache} -#' \item{'rname': }{resource name. This is given by the user when a -#' resource is added to the cache. It does not have to be unique -#' and can be updated at anytime. We recommend descriptive key -#' words and identifers.} -#' \item{'create_time': }{The date and time a resource is added to the cache.} -#' \item{'access_time': }{The date and time a resource is utilized -#' within the cache. The access time is updated when the resource -#' is updated or accessed} -#' \item{'rpath': }{resource path. This is the path to the local -#' (on-disk) file} -#' \item{'rtype': }{resource type. Either "relative", "local", or -#' "web", indicating if the resource has a remote origin} -#' \item{'fpath': }{If rtype is "web", this is the link to the -#' remote resource. It will be utilized to download or update the -#' remote data} -#' \item{'last_modified_time': }{For a remote resource, the -#' last_modified (if available) information for the local copy of -#' the data. This information is checked against the remote -#' resource to determine if the local copy is stale and needs to -#' be updated} -#' } -#' -#' All functions have a quick implementation where if the BiocFileCache object -#' is not passed as an argument, the function uses default 'BiocFileCache()' for -#' implementation. e.g 'bfcinfo()' can be used instead of -#' 'bfcinfo(BiocFileCache())'. The only function this is not available for is -#' 'bfcmeta()<-'; The BiocFileCache object must be defined as a varaible and -#' passed as an argument. See vignette("BiocFileCache") for more details. -#' -#' @param cache character(1) On-disk location (directory path) of -#' cache. For default location see -#' \code{\link[tools]{R_user_dir}}. -#' @param ask logical(1) Ask before creating, updating, overwriting, -#' or removing cache or local file locations. -#' @return For 'BiocFileCache': a \code{BiocFileCache} instance. -#' @examples -#' # bfc <- BiocFileCache() # global cache -#' # bfc -#' bfc0 <- BiocFileCache(tempfile()) # temporary catch for examples -#' @name BiocFileCache-class -#' @aliases BiocFileCache -#' @export BiocFileCache -BiocFileCache <- - function(cache=getBFCOption("CACHE"), ask = interactive()) -{ - - stopifnot( - is.character(cache), length(cache) == 1L, !is.na(cache), - is.logical(ask), length(ask) == 1L, !is.na(ask) - ) - - if (!file.exists(cache)) { - ans <- !ask - if (ask && !.biocfilecache_flags$get_create_asked()) { - ans <- .util_ask(cache, "\n does not exist, create directory?") - } - if (ask && .biocfilecache_flags$get_create_asked()) { - ans <- .biocfilecache_flags$get_ask_response() - } - if (ans) { - dir.create(cache, recursive=TRUE) - } else { - cache <- file.path(tempdir(), "BiocFileCache") - if (!file.exists(cache)) { - message("using temporary cache ", cache) - dir.create(cache, recursive=TRUE) - } - } - } - bfc <- .BiocFileCache(cache=cache) - .sql_create_db(bfc) - bfc -} - -#' @export -setGeneric("bfccache", - function(x) standardGeneric("bfccache") -) - -#' @describeIn BiocFileCache Get the location of the on-disk cache. -#' @param x A \code{BiocFileCache} instance or, if missing, the result -#' of \code{BiocFileCache()}. -#' @return For 'bfccache': character(1) location of the directory -#' containing the cache. -#' @examples -#' bfccache(bfc0) -#' @aliases bfccache -#' @exportMethod bfccache -setMethod("bfccache", "BiocFileCacheBase", function(x) x@cache) - -#' @rdname BiocFileCache-class -#' @aliases bfccache,missing-method -#' @exportMethod bfccache -setMethod("bfccache", "missing", function(x) bfccache(BiocFileCache())) - -#' @describeIn BiocFileCache Get the number of objects in the file -#' cache. -#' @return For 'length': integer(1) Number of objects in the file -#' cache. -#' @examples -#' length(bfc0) -#' @importFrom stats setNames -#' @exportMethod length -setMethod("length", "BiocFileCacheBase", function(x) length(bfcrid(x))) - -#' @rdname BiocFileCache-class -#' @aliases bfcrid -#' @export -setGeneric("bfcrid", function(x) standardGeneric("bfcrid")) - -#' @rdname BiocFileCache-class -#' @aliases bfcrid,missing-method -#' @exportMethod bfcrid -setMethod("bfcrid", "missing", function(x) bfcrid(BiocFileCache())) - -#' @describeIn BiocFileCache Get the rids of the object. -#' @aliases bfcrid,BiocFileCacheReadOnly-method -#' @exportMethod bfcrid -setMethod("bfcrid", "BiocFileCacheReadOnly", function(x) x@rid) - -#' @rdname BiocFileCache-class -#' @aliases bfcrid,BiocFileCache-method -#' @exportMethod bfcrid -setMethod("bfcrid", "BiocFileCache", function(x) .get_all_rids(x)) - -#' @describeIn BiocFileCache Subset a BiocFileCache object. -#' @param drop Ignored. -#' @return For '[': A subset of the BiocFileCache object. -#' @exportMethod [ -setMethod("[", c("BiocFileCache", "character", "missing"), - function(x, i, j, ..., drop=TRUE) -{ - stopifnot(all(i %in% bfcrid(x))) - stopifnot(identical(unname(drop), TRUE)) - - .BiocFileCacheReadOnly(x, rid=as.character(i)) -}) - -#' @rdname BiocFileCache-class -#' @aliases [,BiocFileCacheReadOnly,character,missing-method -#' @exportMethod [ -setMethod("[", c("BiocFileCacheReadOnly", "character", "missing"), - function(x, i, j, ..., drop=TRUE) -{ - stopifnot(all(i %in% bfcrid(x))) - stopifnot(identical(unname(drop), TRUE)) - - initialize(x, rid=as.character(i)) -}) - -#' @rdname BiocFileCache-class -#' @aliases [,BiocFileCache,missing,missing-method -#' @exportMethod [ -setMethod("[", c("BiocFileCache", "missing", "missing"), - function(x, i, j, ..., drop=TRUE) -{ - stopifnot(identical(unname(drop), TRUE)) - - .BiocFileCacheReadOnly(x, rid=bfcrid(x)) -}) - -#' @rdname BiocFileCache-class -#' @aliases [,BiocFileCacheReadOnly,missing,missing-method -#' @exportMethod [ -setMethod("[", c("BiocFileCacheReadOnly", "missing", "missing"), - function(x, i, j, ..., drop=TRUE) -{ - x # no-op -}) - -#' @describeIn BiocFileCache Get a file path for select resources from -#' the cache. -#' @param i character() 'rid' identifiers. -#' @param j Ignored. -#' @return For '[[': named character(1) rpath for the given resource -#' in the cache. -#' @exportMethod [[ -setMethod("[[", c("BiocFileCacheBase", "character", "missing"), - function(x, i, j) -{ - stopifnot(length(i) == 1L, i %in% bfcrid(x)) - - .sql_get_rpath(x, i) -}) - -#' @describeIn BiocFileCache Set the file path of selected resources -#' from the cache. -#' @param value character(1) Replacement file path. -#' @return For '[[<-': Updated BiocFileCache, invisibly. -#' @exportMethod [[<- -setReplaceMethod("[[", c("BiocFileCache", "character", "missing", "character"), - function(x, i, j, ..., value) -{ - stopifnot(length(i) == 1L, length(value) == 1L) - stopifnot(file.exists(value)) - - .sql_set_time(x, i) - .sql_set_rpath(x, i, value) - rtype <- unname(.sql_get_rtype(x, i)) - if (identical(rtype, "relative") || identical(rtype, "web")) { - warning("updating rpath, changing rtype to 'local'") - .sql_set_rtype(x, i, "local") - } - x -}) - -#' @export -setGeneric("bfcnew", - function(x, rname, rtype=c("relative", "local"), ext=NA_character_, - fname=c("unique", "exact")) - standardGeneric("bfcnew"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcnew,missing-method -#' @exportMethod bfcnew -setMethod("bfcnew", "missing", - function(x, rname, rtype=c("relative", "local"), ext=NA_character_, - fname=c("unique", "exact")) -{ - bfcnew(x=BiocFileCache(), rname=rname, rtype=rtype, ext=ext, fname=fname) -}) - -#' @describeIn BiocFileCache Add a resource to the database -#' @param rname character(1) Name of object in file cache. For -#' 'bfcupdate' a character vector of replacement rnames. -#' @param ext character(1) A file extension to add to the local -#' copy of the file (e.g., \sQuote{sqlite}, \sQuote{txt}, -#' \sQuote{tar.gz}). -#' @param fname character(1). Options are \sQuote{unique} or -#' \sQuote{exact}. \sQuote{unique} provides each bfc resource with a unique -#' identifier when storing the file, allowing resources with the same name -#' to be stored in the cache. \sQuote{exact} uses the exact file name of the -#' resource; only one of foo/my.txt and bar/my.txt could be stored. Default -#' is \sQuote{unique}. -#' @return For 'bfcnew': named character(1), the path to save your -#' object / file. The name of the return value is the unique rid -#' for the resource. -#' @examples -#' path <- bfcnew(bfc0, "NewResource") -#' path -#' @aliases bfcnew -#' @exportMethod bfcnew -setMethod("bfcnew", "BiocFileCache", - function(x, rname, rtype=c("relative", "local"), ext=NA_character_, - fname=c("unique", "exact")) -{ - stopifnot( - is.character(rname), length(rname) > 0L, !any(is.na(rname)), - is.character(ext), length(ext) > 0L - ) - rtype <- match.arg(rtype) - fname <- match.arg(fname) - - .sql_add_resource(x, rname, rtype, NA_character_, ext, fname) -}) - -#' @export -setGeneric("bfcadd", - function( - x, rname, fpath = rname, rtype=c("auto", "relative", "local", "web"), - action=c("copy", "move", "asis"), proxy="", - download=TRUE, progress=TRUE, config=list(), ext=NA_character_, - fname=c("unique", "exact"),... - ) standardGeneric("bfcadd"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcadd,missing-method -#' @exportMethod bfcadd -setMethod("bfcadd", "missing", - function( - x, rname, fpath = rname, rtype=c("auto", "relative", "local", "web"), - action=c("copy", "move", "asis"), proxy="", - download=TRUE, progress=TRUE, config=list(), ext=NA_character_, - fname=c("unique", "exact"), ... - ) -{ - bfcadd(x=BiocFileCache(), rname=rname, fpath=fpath, rtype=rtype, - action=action, proxy=proxy, download=download, progress=progress, config=config, - ext=ext, fname=fname,...) -}) - -#' @describeIn BiocFileCache Add an existing resource to the database -#' @param fpath For bfcadd(), character(1) path to current file -#' location or remote web resource. If none is given, the rname is -#' assumed to also be the path location. For bfcupdate() -#' character() vector of replacement web resources. -#' @param rtype character(1) 'local', 'relative', or 'web' indicating -#' if the resource is a local file, a relative path in the cache, -#' or a web resource. For \code{bfcnew}: local or relative are -#' only options. For \code{bfcadd}, the default 'auto' creates -#' relative or web paths, based on the path prefix. -#' @param action character(1) How to handle the file: create a -#' \code{copy} of \code{fpath} in the cache directory; \code{move} -#' the file to the cache directory; or \code{asis} leave the file -#' in current location but save the path in the cache. If 'rtype -#' == "relative"', action can not be "asis". -#' @param proxy character(1) (Optional) proxy server passed to -#' \code{httr2::req_proxy} -#' @param download logical(1) If \code{rtype=web}, should remote -#' resource be downloaded locally immediately. -#' @param progress TRUE/FALSE if progress bar for downloads in interactive -#' session should be shown -#' @param config list() passed as argument to \code{httr2::req_options}. The -#' names of items should be valid curl options as defined in -#' \code{curl::curl_options}. -#' @param ... For 'bfcadd', 'bfcupdate' and 'bfcdownload': Additional -#' arguments passed to internal download functions for use with -#' \code{httr2::req_perform}. For 'bfcrpaths': Additional arguments passed -#' to 'bfcadd', or \code{exact} passed to 'bfcquery'. For -#' 'bfcquery': Additional arguments passed to \code{grepl}. For -#' 'exportbfc': Additional arguments to the selected outputMethod -#' function. See \code{utils::tar} or \code{utils::zip} for more -#' information. For 'importbfc': Additional arguments to the -#' selected archiveMethod function. See \code{utils::untar} or -#' \code{utils::unzip} for more information. -#' @return For 'bfcadd': named character(1), the path to save your -#' object / file. The name of the character is the unique rid for -#' the resource. -#' @examples -#' fl1 <- tempfile(); file.create(fl1) -#' bfcadd(bfc0, "Test1", fl1) # copy -#' fl2 <- tempfile(); file.create(fl2) -#' bfcadd(bfc0, "Test2", fl2, action="move") # move -#' fl3 <- tempfile(); file.create(fl3) -#' add3 <- bfcadd(bfc0, "Test3", fl3, rtype="local", action="asis") # reference -#' rid3 <- names(add3) -#' -#' bfc0 -#' file.exists(fl1) # TRUE -#' file.exists(fl2) # FALSE -#' file.exists(fl3) # TRUE -#' -#' # add a remote resource -#' url <- "https://httpbin.org/get" -#' bfcadd(bfc0, "TestWeb", fpath=url) -#' @aliases bfcadd -#' @exportMethod bfcadd -setMethod("bfcadd", "BiocFileCache", - function( - x, rname, fpath = rname, - rtype = c("auto", "relative", "local", "web"), - action = c("copy", "move", "asis"), - proxy = "", download = TRUE, progress=TRUE, config = list(), ext=NA_character_, - fname=c("unique", "exact"),...) -{ - stopifnot( - is.character(rname), length(rname) > 0L, !any(is.na(rname)), - is.character(fpath), length(fpath) > 0L, !any(is.na(fpath)) - ) - stopifnot(all(action %in% c("copy", "move", "asis")), - all(rtype %in% c("auto", "relative", "local", "web"))) - if (missing(rtype)) rtype <- match.arg(rtype) - if (missing(action)) action <- match.arg(action) - stopifnot((length(action) == 1) || (length(action) == length(fpath))) - stopifnot((length(rtype) == 1) || (length(rtype) == length(fpath))) - if (length(action) == 1) action = rep(action, length(fpath)) - if (length(rtype) == 1) rtype = rep(rtype, length(fpath)) - - rtype <- .util_standardize_rtype(rtype, fpath, action) - stopifnot(all(rtype == "web" | file.exists(fpath))) - fname <- match.arg(fname) - - rpath <- .sql_add_resource(x, rname, rtype, fpath, ext, fname) - rid <- names(rpath) - - for(i in seq_along(rpath)){ - if (rtype[i] %in% c("local", "relative")) { - switch( - action[i], - copy = file.copy(fpath[i], rpath[i]), - move = file.rename(fpath[i], rpath[i]), - asis = { - .sql_set_rpath(x, rid[i], fpath[i]) - rpath[i] <- bfcrpath(x, rids = rid[i]) - } - ) - } else if (download) { # rtype == "web" - .util_download(x, rid[i], proxy, progress, config, "bfcadd()", ...) - } - } - - rpath -}) - -#' @export -setGeneric("bfcinfo", - function(x, rids) standardGeneric("bfcinfo"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcinfo,missing-method -#' @exportMethod bfcinfo -setMethod("bfcinfo", "missing", - function(x, rids) -{ - bfcinfo(x=BiocFileCache(), rids=rids) -}) - -#' @describeIn BiocFileCache list resources in database -#' @param rids character() Vector of rids. -#' @return For 'bfcinfo': A \code{bfc_tbl} of current resources in the -#' database. -#' @examples -#' bfcinfo(bfc0) -#' @aliases bfcinfo -#' @exportMethod bfcinfo -setMethod("bfcinfo", "BiocFileCacheBase", - function(x, rids) -{ - if (missing(rids)) - rids <- bfcrid(x) - stopifnot(all(rids %in% bfcrid(x))) - - tbl <- .sql_get_resource_table(x, rids) - tbl <- mutate(tbl, rpath = unname(bfcrpath(x, rids=rids))) - class(tbl) <- c("tbl_bfc", class(tbl)) - tbl -}) - -setOldClass("tbl_bfc") - -#' @describeIn BiocFileCache Get the rids of the object -#' @exportMethod bfcrid -setMethod("bfcrid", "tbl_bfc", function(x) .get_tbl_rid(x)) - -#' @export -setGeneric("bfcpath", - function(x, rids) standardGeneric("bfcpath"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcpath,missing-method -#' @exportMethod bfcpath -setMethod("bfcpath", "missing", - function(x, rids) -{ - bfcpath(x=BiocFileCache(), rids=rids) -}) - -#' @describeIn BiocFileCache display rpaths of resource. -#' @return For 'bfcpath': the file path location to load -#' @examples -#' bfcpath(bfc0, rid3) -#' @aliases bfcpath -#' @exportMethod bfcpath -setMethod("bfcpath", "BiocFileCacheBase", - function(x, rids) -{ - if (missing(rids)) - rids <- bfcrid(x) - - stopifnot(length(rids) > 0L, all(rids %in% bfcrid(x))) - - path <- .sql_get_rpath(x, rids) - path -}) - -#' @export -setGeneric("bfcrpath", - function(x, rnames, ..., rids, exact = TRUE) standardGeneric("bfcrpath"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcrpath,missing-method -#' @exportMethod bfcrpath -setMethod("bfcrpath", "missing", - function(x, rnames, ..., rids, exact = TRUE) -{ - bfcrpath(x=BiocFileCache(), rnames=rnames, ..., rids=rids, exact=exact) -}) - -#' @describeIn BiocFileCache display rpath of resource. If 'rnames' is -#' in the cache the path is returned, if it is not it will try to -#' add it to the cache with 'bfcadd' -#' @param rnames character() to match against rnames. Each element of -#' \code{rnames} must match exactly one record. Use \code{exact = -#' FALSE} to use regular expression matching. -#' @return For 'bfcrpath': The local file path location to load. -#' @examples -#' bfcrpath(bfc0, rids = rid3) -#' @aliases bfcrpath -#' @exportMethod bfcrpath -setMethod("bfcrpath", "BiocFileCacheBase", - function(x, rnames, ..., rids, exact = TRUE) -{ - if (!missing(rnames) && !missing(rids)) - stop("specify either 'rnames' or 'rids' not both.") - - update_time_and_path <- function(x, i) { - .sql_get_rpath(x, i) - } - - add_or_return_rname <- function(x, rname, ..., exact) { - res <- bfcrid(bfcquery(x, rname, field="rname", exact = exact)) - if (length(res) == 0L) { - ## obtain an exclusive lock to add 'rname' - id <- "add_or_return_rname" - locfile_path <- file.path(bfccache(x), id) - locfile <- .lock2(locfile_path, exclusive = TRUE) - tryCatch({ - ## need to re-check that the resource is still needed, - ## now that we have the exclusive lock - res <- bfcrid(bfcquery(x, rname, field="rname", exact = exact)) - if (length(res) == 0L) { - message("adding rname '", rname, "'") - names(bfcadd(x, rname, ...)) - } else { - names(update_time_and_path(x, res)) - } - }, error=function(e) { - warning( - "\ntrying to add rname '", rname, "' produced error:", - "\n ", conditionMessage(e) - ) - NA_character_ - }, finally = function() { - .unlock2(locfile_path) - }) - } else if (length(res) == 1L) { - names(update_time_and_path(x, res)) - } else { - warning("'rnames' ", - if (exact) "exact" else "regular expression", - " pattern", - "\n '", rname, "'", - "\n is not unique; use 'bfcquery()' to see matches.") - NA_character_ - } - } - - if (missing(rids)) - rids <- bfcrid(x) - - if (!missing(rnames)) { - rids0 <- vapply( - rnames, add_or_return_rname, character(1), x=x, ..., exact = exact - ) - if (anyNA(rids0)) { - rmdx <- setdiff(bfcrid(x), rids) - if (length(rmdx) > 0L) - bfcremove(x, rmdx) - stop("not all 'rnames' found or unique.") - } - bfcrpath(x, rids = rids0) - } else { - stopifnot(all(rids %in% bfcrid(x))) - update_time_and_path(x, rids) - } -}) - -#' @export -setGeneric("bfcupdate", - function(x, rids, ...) standardGeneric("bfcupdate"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcupdate,missing-method -#' @exportMethod bfcupdate -setMethod("bfcupdate", "missing", - function(x, rids, ...) -{ - bfcupdate(x=BiocFileCache(), rids=rids, ...) -}) - -#' @describeIn BiocFileCache Update a resource in the cache -#' @param rpath character() vector of replacement rpaths. -#' @return For 'bfcupdate': an updated \code{BiocFileCache} object, -#' invisibly. -#' @examples -#' bfcupdate(bfc0, rid3, rpath=fl3, rname="NewRname") -#' bfc0[[rid3]] = fl1 -#' bfcupdate(bfc0, "BFC5", fpath="http://google.com") -#' @aliases bfcupdate -#' @exportMethod bfcupdate -setMethod("bfcupdate", "BiocFileCache", - function(x, rids, ..., rname=NULL, rpath=NULL, fpath=NULL, - proxy="", progress=TRUE, config=list(), ask=TRUE) -{ - stopifnot(!missing(rids), all(rids %in% bfcrid(x))) - stopifnot( - is.null(rname) || (length(rids) == length(rname)), - is.null(rpath) || (length(rids) == length(rpath)), - is.null(fpath) || (length(rids) == length(fpath)) - ) - stopifnot( - is.null(rname) || is.character(rname), - is.null(rpath) || is.character(rpath), - is.null(fpath) || is.character(fpath) - ) - - if(is.null(rname) && is.null(rpath) && is.null(fpath)) { - stop("bfcupdate() has nothing to update.", - "\n Please set rname, rpath, or fpath", - call.=FALSE) - } - - info <- NULL - - for (i in seq_along(rids)) { - - .sql_set_time(x, rids[i]) - - if (!is.null(rname)) { - .sql_set_rname(x, rids[i], rname[i]) - } - - if (!is.null(rpath)) { - if (!file.exists(rpath[i])) - stop( - "bfcupdate() failed", - "\n rid: ", rids[i], - "\n rpath: ", sQuote(rpath[i]), - "\n reason: rpath does not exist.", - call.=FALSE - ) - .sql_set_rpath(x, rids[i], rpath[i]) - rtype <- unname(.sql_get_rtype(x, rids[i])) - if (identical(rtype, "relative") || identical(rtype, "web")) { - warning("updating rpath, changing rtype to 'local'") - .sql_set_rtype(x, rids[i], "local") - } - } - - if (!is.null(fpath)) { - if (.sql_get_rtype(x, rids[i]) != "web") - stop("bfcupdate() failed", - "\n rid: ", rids[i], - "\n reason: resource rtype is not 'web'", - call.=FALSE) - - if (ask) { - doit <- .util_ask( - "Setting a new remote path results in immediate\n", - " download and overwriting of existing file.\n", - " Continue?" - ) - } else { - doit <- TRUE - } - if (doit) { - .util_download_and_rename( - x, rids[i], proxy, progress, config, "bfcupdate()", fpath[i], ... - ) - .sql_set_fpath(x, rids[i], fpath[i]) - } - } - } - - invisible(x) -}) - -#' @rdname BiocFileCache-class -#' @export -setGeneric("bfcmeta<-", - function(x, name, ..., value) - standardGeneric("bfcmeta<-"), - signature = "x" -) - -#' @describeIn BiocFileCache add meta data table in database -#' @param name character(1) name of metadata table. -#' @return For 'bfcmeta': updated BiocFileCache, invisibly -#' @examples -#' meta = data.frame(list(rid = paste("BFC",seq_len(bfccount(bfc0)), sep=""), -#' num=seq(bfccount(bfc0),1,-1), -#' data=c(paste("Letter", -#' letters[seq_len(bfccount(bfc0))]))), -#' stringsAsFactors=FALSE) -#' bfcmeta(bfc0, name="resourcedata") <- meta -#' @aliases bfcmeta<- -#' @exportMethod bfcmeta<- -setReplaceMethod("bfcmeta", "BiocFileCacheBase", - function(x, name, ..., value) -{ - stopifnot("rid" %in% colnames(value)) - rids <- value$rid - stopifnot(all(rids %in% bfcrid(x))) - stopifnot(is.character(name), length(name) == 1L, !is.na(name)) - - if (name %in% .RESERVED$TABLES) - stop( - "'", name, "' cannot be added; reserved table names: ", - paste(sQuote(.RESERVED$TABLES), collapse=", ") - ) - - if (any(colnames(value) %in% .RESERVED$COLUMNS)) - stop( - "'value' (metadata) cannot contain colnames ", - paste(sQuote(.RESERVED$COLUMNS), collapse= ", ") - ) - - .sql_meta_gets(x, name, value, ...) - x -}) - -#' @export -setGeneric("bfcmetaremove", - function(x, name, ...) standardGeneric("bfcmetaremove"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcmetaremove,missing-method -#' @exportMethod bfcmetaremove -setMethod("bfcmetaremove", "missing", - function(x, name, ...) -{ - bfcmetaremove(x=BiocFileCache(), name=name, ...) -}) - -#' @describeIn BiocFileCache remove meta data table in database -#' @return For 'bfcmetaremove': updated BiocFileCache, invisibly -#' @examples -#' \dontrun{bfcmetaremove(bfc0, "resourcedata")} -#' @aliases bfcmetaremove -#' @exportMethod bfcmetaremove -setMethod("bfcmetaremove", "BiocFileCacheBase", - function(x, name, ...) -{ - stopifnot( - !missing(name), is.character(name), length(name) == 1L, !is.na(name) - ) - if (name %in% .RESERVED$TABLES) - stop("reserved table '", name, "' cannot be removed") - - .sql_meta_remove(x, name, ...) - - invisible(x) -}) - -#' @export -setGeneric("bfcmetalist", - function(x) standardGeneric("bfcmetalist"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcmetalist,missing-method -#' @exportMethod bfcmetalist -setMethod("bfcmetalist", "missing", - function(x) -{ - bfcmetalist(x=BiocFileCache()) -}) - -#' @describeIn BiocFileCache retrieve listing of metadata tables -#' @return For 'bfcmetalist': returns a character() of all metadata tables -#' currently in the database. If no metadata tables are available returns -#' character(0) -#' @examples -#' bfcmetalist(bfc0) -#' @aliases bfcmetalist -#' @exportMethod bfcmetalist -setMethod("bfcmetalist", "BiocFileCacheBase", - function(x) -{ - .sql_meta_list(x) -}) - -#' @export -setGeneric("bfcmeta", - function(x, name, ...) standardGeneric("bfcmeta"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcmeta,missing-method -#' @exportMethod bfcmeta -setMethod("bfcmeta", "missing", - function(x, name, ...) -{ - bfcmeta(x=BiocFileCache(), name=name, ...) -}) - -#' @describeIn BiocFileCache retrieve metadata table -#' @return For 'bfcmeta': returns a data.frame representation of database -#' table -#' @examples -#' tbl = bfcmeta(bfc0, "resourcedata") -#' tbl -#' @aliases bfcmeta -#' @exportMethod bfcmeta -setMethod("bfcmeta", "BiocFileCacheBase", - function(x, name, ...) -{ - if (missing(name)) { - tbls <- paste(sQuote(bfcmetalist(x)), collapse=", ") - if (!nzchar(tbls)) - tbls <- NA_character_ - stop("metadata table 'name' missing, possible values: ", tbls) - } - stopifnot(is.character(name), length(name) == 1L, !is.na(name)) - - .sql_meta(x, name, ...) -}) - -#' @export -setGeneric("bfcquerycols", - function(x) standardGeneric("bfcquerycols") -) - -#' @rdname BiocFileCache-class -#' @aliases bfcquerycols,missing-method -#' @exportMethod bfcquerycols -setMethod("bfcquerycols", "missing", - function(x) -{ - bfcquerycols(x=BiocFileCache()) -}) - -#' @describeIn BiocFileCache Get all the possible columns to query -#' @return For 'bfcquerycols': character() all columns in all database tables -#' available for query. -#' @examples -#' bfcquerycols(bfc0) -#' @aliases bfcquerycols -#' @exportMethod bfcquerycols -setMethod("bfcquerycols", "BiocFileCacheBase", - function(x) -{ - .get_all_colnames(x) -}) - -#' @export -setGeneric("bfcquery", - function(x, query, field=c("rname", "rpath", "fpath"), ..., exact = FALSE) - standardGeneric("bfcquery"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcquery,missing-method -#' @exportMethod bfcquery -setMethod("bfcquery", "missing", - function(x, query, field=c("rname", "rpath", "fpath"), ..., exact = FALSE) -{ - bfcquery(x=BiocFileCache(), query=query, field=field, ..., exact = exact) -}) - -#' @describeIn BiocFileCache query resource -#' @param query character() Regular expression pattern(s) to match in -#' resource. It will match the pattern against \code{fields}, -#' using \code{&} logic across query element. By default, case -#' sensitive. When \code{exact = TRUE}, \code{query} uses exact -#' matching. -#' @param field character() column names in resource to query, using -#' \code{||} logic across multiple field elements. By default, -#' matches pattern agains rname, rpath, and fpath. If exact -#' matching, may only be a single value. -#' @param exact logical(1) when FALSE, treat \code{query} as a regular -#' expression. When TRUE, use exact matching. For \code{bfcquery}, -#' the default is \code{FALSE} (regular expression matching; for -#' \code{bfcrpath}, the default is \code{TRUE} (exact matching). -#' @return For 'bfcquery': A \code{bfc_tbl} of current resources in -#' the database whose \code{field} contained query. If multiple -#' values are given, the resource must contain all of the -#' patterns. A tbl with zero rows is returned when no resources -#' match the query. -#' @examples -#' bfcquery(bfc0, "Test") -#' bfcquery(bfc0, "^Test1$", field="rname") -#' @aliases bfcquery -#' @exportMethod bfcquery -setMethod("bfcquery", "BiocFileCacheBase", - function(x, query, field=c("rname", "rpath", "fpath"), ..., exact = FALSE) -{ - stopifnot(is.character(query)) - stopifnot(all(field %in% .get_all_colnames(x))) - - keep <- TRUE - if (exact) { - tryCatch({ - where <- paste(field, "== :query", collapse=" OR ") - .sql_select_query(x, where, query = query) - }) - } else { - tbl <- .sql_get_resource_table(x) - for (q in query) - keep <- keep & Reduce(`|`, lapply(tbl[field], grepl, pattern = q, ...)) - rids <- intersect(tbl$rid[keep], bfcrid(x)) - bfcinfo(x, rids) - } -}) - -#' @export -setGeneric("bfccount", - function(x) standardGeneric("bfccount") -) - -#' @rdname BiocFileCache-class -#' @aliases bfccount,missing-method -#' @exportMethod bfccount -setMethod("bfccount", "missing", - function(x) -{ - bfccount(x=BiocFileCache()) -}) - -#' @describeIn BiocFileCache Get the number of objects in the file -#' cache or query. -#' @return For 'bfccount': integer(1) Number of objects in the cache -#' or query. -#' @examples -#' bfccount(bfc0) -#' bfccount(bfcquery(bfc0, "test")) -#' @aliases bfccount -#' @exportMethod bfccount -setMethod("bfccount", "BiocFileCacheBase", - function(x) -{ - bfccount(bfcinfo(x)) -}) - -#' @rdname BiocFileCache-class -#' @aliases bfccount,tbl_bfc-method -#' @exportMethod bfccount -setMethod("bfccount", "tbl_bfc", - function(x) -{ - .sql_get_nrows(x) -}) - -#' @export -setGeneric("bfcneedsupdate", - function(x, rids, ..., proxy="", config=list()) standardGeneric("bfcneedsupdate"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcneedsupdate,missing-method -#' @exportMethod bfcneedsupdate -setMethod("bfcneedsupdate", "missing", - function(x, rids, ..., proxy="", config=list()) -{ - bfcneedsupdate(x=BiocFileCache(), rids=rids, proxy=proxy, config=config) -}) - -#' @describeIn BiocFileCache check if a resource needs to be updated -#' @return For 'bfcneedsupdate': named logical vector if resource -#' needs to be updated. The name is the resource -#' 'rid'. \code{TRUE}: fpath \code{etag} or \code{modified} time of -#' web resource more recent than in BiocFileCache; \code{FALSE}: fpath -#' \code{etag} or \code{modified} time of web resource not more recent -#' than in BiocFileCache; \code{NA}: web resource etag and modified time -#' could not be determined. If the etag is available the function will use -#' that information definitively and only compare last modified time if -#' etag is not available. If there is an \code{expires} time that will be -#' used to initially determine if the resource should be updated. -#' @examples -#' bfcneedsupdate(bfc0, "BFC5") -#' @aliases bfcneedsupdate -#' @exportMethod bfcneedsupdate -setMethod("bfcneedsupdate", "BiocFileCacheBase", - function(x, rids, ..., proxy="", config=list()) -{ - if (missing(rids)) - rids <- .get_all_web_rids(x) - stopifnot(all(rids %in% bfcrid(x))) - if (!all(rids %in% .get_all_web_rids(x))) - stop("rids not all web resources") - - helper <- function(x, rid) { - file_time <- .sql_get_last_modified(x, rid) - fpath <- .sql_get_fpath(x, rid) - file_etag <- .sql_get_etag(x, rid) - file_expires <- .sql_get_expires(x, rid) - cache_info <- .httr_get_cache_info(fpath, proxy, config) - web_time <- cache_info[["modified"]] - web_etag <- cache_info[["etag"]] - - if (!is.na(file_expires)) - expired <- as.Date(file_expires, optional=TRUE) <= Sys.Date() - else - expired <- FALSE - - checkTime <- FALSE - if (expired){ - res <- TRUE - checkTime <- FALSE - } else { - - if (is.na(web_etag) || is.na(file_etag)) { - checkTime <- TRUE - } else { - res <- !identical(unname(file_etag), web_etag) - } - - if (checkTime) { - if (is.na(file_time) || is.na(web_time)) { - res <- NA - } else { - res <- as.POSIXlt(web_time, optional=TRUE) > - as.POSIXlt(file_time, optional=TRUE) - } - } - } - res - } # end helper - - result <- vapply(rids, helper, logical(1), x=x) - # if web resources hasn't been locally downloaded yet - result[rids %in% .get_rid_filenotfound(x)] = TRUE - setNames(result, rids) -}) - -#' @export -setGeneric("bfcdownload", - function(x, rid, proxy="", progress=TRUE, config=list(), ask=TRUE, FUN, ...) - standardGeneric("bfcdownload"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcdownload,missing-method -#' @param rid character(1) Unique resource id. -#' @exportMethod bfcdownload -setMethod("bfcdownload", "missing", - function(x, rid, proxy="", config=list(), ask=TRUE, FUN, ...) -{ - bfcdownload(x=BiocFileCache(), rid=rid, proxy=proxy, progress=TRUE, config=config, ask=ask, - FUN=FUN, ...) -}) - -#' @describeIn BiocFileCache Redownload resource to location in cache -#' @param FUN A specialized implemented function designed by the user. This -#' function can be used to perform and save the results of a post download -#' processing step rather than direct output. The function should ONLY take in -#' two file names: the first the raw downloaded file and the second the output -#' file for saved results. The output of the function should be TRUE/FALSE if -#' step was successful. See vignette section on Specialty Advance Use Case for -#' more details. -#' @return For 'bfcdownload': character(1) path to downloaded resource -#' in cache. -#' @examples -#' bfcdownload(bfc0, "BFC5") -#' @aliases bfcdownload -#' @exportMethod bfcdownload -setMethod("bfcdownload", "BiocFileCache", - function(x, rid, proxy="", progress=TRUE, config=list(), ask=TRUE, FUN, ...) -{ - stopifnot( - !missing(rid), length(rid) > 0L, - all(rid %in% bfcrid(x)), - all(.sql_get_rtype(x, rid) == "web") - ) - - .sql_set_time(x, rid) - - if (ask && any(file.exists(.sql_get_rpath(x, rid)))) { - doit <- .util_ask( - "bfcdownload() will overwrite exisiting files, continue?" - ) - } else { - doit <- TRUE - } - if (doit) - .util_download_and_rename(x, rid, proxy, progress, config, "bfcdownload()", - FUN=FUN, ...) - - bfcrpath(x, rids=rid) -}) - - -#' @export -setGeneric("bfcremove", - function(x, rids) standardGeneric("bfcremove"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcremove,missing-method -#' @exportMethod bfcremove -setMethod("bfcremove", "missing", - function(x, rids) -{ - bfcremove(x=BiocFileCache(), rids=rids) -}) - -#' @describeIn BiocFileCache Remove a resource to the database. If -#' the local file is located in \code{bfccache(x)}, the file will -#' also be deleted. This will not delete information in any metadata -#' table. -#' @return For 'bfcremove': updated BiocFileCache object, invisibly -#' @examples -#' bfcremove(bfc0, rid3) -#' bfcinfo(bfc0) -#' @aliases bfcremove -#' @exportMethod bfcremove -setMethod("bfcremove", "BiocFileCache", - function(x, rids) -{ - stopifnot(all(rids %in% bfcrid(x))) - - rpaths <- .sql_get_rpath(x, rids) - cached <- startsWith(rpaths, bfccache(x)) - - .sql_remove_resource(x, rids) - status <- .util_unlink(rpaths[cached]) - - invisible(x) -}) - -#' @export -setGeneric("bfcsync", - function(x, verbose = TRUE, ask = TRUE) standardGeneric("bfcsync"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases bfcsync,missing-method -#' @exportMethod bfcsync -setMethod("bfcsync", "missing", - function(x, verbose = TRUE, ask = TRUE) -{ - bfcsync(x=BiocFileCache(), verbose=verbose, ask=ask) -}) - -#' @describeIn BiocFileCache sync cache and resource. -#' @param verbose logical(1) If descriptive message and list of issues -#' should be included as output. -#' @return For 'bfcsync': logical(1) indicating whether the cache is -#' in sync (\code{TRUE}) or not. 'verbose' is TRUE by default, so -#' descriptive messages will also be included. -#' @examples -#' bfcsync(bfc0) -#' -#' if (!interactive()){ -#' # in interactive mode, in the sync above -#' # this was probably already removed -#' # noninteractive mode does not remove resources -#' # so can remove manually here -#' bfcremove(bfc0, "BFC1") -#' } -#' bfcsync(bfc0, FALSE) -#' @aliases bfcsync -#' @importFrom utils capture.output -#' @exportMethod bfcsync -setMethod("bfcsync", "BiocFileCache", - function(x, verbose=TRUE, ask = TRUE) -{ - stopifnot(is.logical(verbose), length(verbose) == 1L, !is.na(verbose)) - - # files not found - rids <- .get_rid_filenotfound(x) - - # files untracked in cache location - files <- file.path(bfccache(x), setdiff(dir(bfccache(x)),c(.CACHE_FILE, .CACHE_FILE_LOCK))) - paths <- .sql_get_rpath(x, bfcrid(x)) - # normalizePath on windows - # can't across platform - no opt on linux but added hidden on mac - if (tolower(.Platform$OS.type) == "windows") { - files = normalizePath(files) - paths = normalizePath(paths) - } - untracked <- setdiff(files, paths) - - rids0 <- rids; untracked0 <- untracked - - if (verbose && (length(rids) != 0L)) - message( - "entries without corresponding files: ", - paste0("'", rids, "'", collapse=" ") - ) - if (ask && (length(rids) != 0L)) { - doit <- .util_ask("delete ", length(rids), " entries?") - rids <- rids[doit] - } - - if (verbose && (length(untracked) != 0L)) - message( - "files without cache entries\n ", - paste(untracked, collpase="\n ") - ) - if (ask && (length(untracked) != 0L)) { - doit <- .util_ask("delete ", length(untracked), " files?") - untracked <- untracked[doit] - } - - .sql_remove_resource(x, rids) - .util_unlink(untracked) - - !length(setdiff(rids0, rids)) && !length(setdiff(untracked0, untracked)) -}) - - -#' @export -setGeneric("exportbfc", - function(x, rids, - outputFile="BiocFileCacheExport.tar", outputMethod=c("tar","zip"), - verbose=TRUE, ...) - standardGeneric("exportbfc"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases exportbfc,missing-method -#' @exportMethod exportbfc -setMethod("exportbfc", "missing", - function(x, rids, - outputFile="BiocFileCacheExport.tar", outputMethod=c("tar","zip"), - verbose=TRUE, ...) -{ - exportbfc(x=BiocFileCache(), rids=rids, - outputFile=outputFile, outputMethod=outputMethod, - verbose=verbose, ...) -}) - -#' @describeIn BiocFileCache Create exportable file containing -#' BiocFileCache. -#' @param outputFile character(1) The /basename for the -#' output archive. Please include appropriate extension based on -#' outMethod and any additional parameters selected for -#' \code{utils::tar} or \code{utils::zip} -#' @param outputMethod Either 'tar' or 'zip' for how the directory -#' should be archived. Default is 'tar'. -#' @return character(1) The outputFile path. -#' @examples -#' \dontrun{exportbfc(bfc)} -#' @aliases exportbfc -#' @exportMethod exportbfc -setMethod("exportbfc", "BiocFileCacheBase", - function(x, rids, - outputFile="BiocFileCacheExport.tar", outputMethod=c("tar","zip"), - verbose=TRUE, ...) -{ - if (missing(rids)) - rids <- bfcrid(x) - - stopifnot(all(rids %in% bfcrid(x))) - stopifnot(length(outputFile) == 1L, is.character(outputFile)) - outputMethod <- match.arg(outputMethod) - stopifnot(is.logical(verbose), length(verbose) == 1L) - - bfc <- x[rids] - if (length(bfc) == 0L) - stop("No valid rids selected") - - dir <- file.path(tempdir(), "BiocFileCacheExport") - dir.create(dir) - ids <- bfcrid(bfc) - - file.copy(.sql_dbfile(x), dir) - newbfc <- BiocFileCache(dir) - idrm <- setdiff(.get_all_rids(newbfc), ids) - if (length(idrm) != 0) - newbfc <- bfcremove(newbfc, rids=idrm) - - res <- vapply(ids, .util_export_file, character(1), - bfc=x, dir=dir) - .sql_set_time(x, ids) - # 'relative' = ok, 'web'= not download - # 'local' = file not in cache, 'NA' = file not found - if (any(res == "web", na.rm=TRUE)) { - webid <- names(which(res == "web")) - if (verbose) - message( - "The following are identified as web resources\n", - "but have not been downloaded yet. No associated\n", - "files will be exported:\n", - " ", paste0("'", webid, "'", collapse=" "), - "\n\n" - ) - } - if (any(res == "local", na.rm=TRUE)) { - locid <- names(which(res == "local")) - if (verbose) - message( - "The following are identified as local resources.\n", - "A copy of the file will be exported:\n", - " ", paste0("'", locid, "'", collapse=" "), - "\n\n" - ) - for (i in locid) { - orig <- .sql_get_rpath(x, i) - newpath <- file.path(dir, basename(orig)) - if (file.exists(newpath)) { - filename <- paste(basename(tempfile("", bfccache(newbfc))), - basename(orig), sep="_") - newpath <- file.path(dir, filename) - } - file.copy(orig, newpath) - } - } - if (any(is.na(res))) { - naid <- names(which(is.na(res))) - if (verbose) - message( - "The following had a file that was not found.\n", - "The file is not included and the rid will be removed\n", - "from the BiocFileCache object being exported:\n", - " ", paste0("'", naid, "'", collapse=" "), - "\n\n" - ) - newbfc <- bfcremove(newbfc, rids=naid) - } - - if (length(bfcmetalist(newbfc)) != 0) { - metaList <- bfcmetalist(newbfc) - res <- vapply(metaList, .sql_filter_metadata, logical(1), - bfc=newbfc, verbose=verbose) - } - - # tar/zip up directory - origdir <- getwd() - if (dirname(outputFile) == ".") - outputFile = file.path(origdir, outputFile) - setwd(dirname(dir)) - files = basename(dir) - - archive <- function(outputFile, how = c("tar", "zip"), files, ...) { - fun <- switch(how, tar = tar, zip = zip) - fun(outputFile, files, ...) - } - - # remove lock file from export - .util_unlink(file.path(dir, .CACHE_FILE_LOCK)) - - archive(outputFile=outputFile, how=outputMethod, files=files, ...) - setwd(origdir) - .util_unlink(dir, recursive=TRUE) - outputFile -}) - -#' @export -setGeneric("importbfc", - function(filename, archiveMethod=c("untar","unzip"), - exdir=".", ...) - standardGeneric("importbfc"), - signature = "filename" -) - -#' @describeIn BiocFileCache Import file created with exportbfc containing -#' BiocFileCache. -#' @param filename character(1) The name of the archive. -#' @param archiveMethod Either 'untar' or 'unzip' for how the directory should -#' be extracted. Default is 'untar'. -#' @param exdir Directory to extract files too. See \code{utils::untar} or -#' \code{utils::unzip} for more details. -#' @return A BiocFileCache object -#' @examples -#' \dontrun{importbfc("ExportBiocFileCache.tar")} -#' @aliases importbfc -#' @exportMethod importbfc -setMethod("importbfc", "character", - function(filename, archiveMethod=c("untar","unzip"), - exdir=".", ...) -{ - exportPath <- file.path(exdir, "BiocFileCacheExport") - stopifnot(!dir.exists(exportPath)) - stopifnot(length(exdir) == 1L, is.character(exdir)) - stopifnot(length(filename) == 1L, is.character(filename)) - archiveMethod = match.arg(archiveMethod) - - inflate <- function(filename, how = c("untar", "unzip"), exdir, ...) { - fun <- switch(how, untar = untar, unzip = unzip) - fun(filename, exdir=exdir, ...) - } - inflate(filename=filename, how=archiveMethod, exdir=exdir, ...) - bfc = BiocFileCache(exportPath) - bfc -}) - -#' @export -setGeneric("cleanbfc", - function(x, days = 120, ask = TRUE) standardGeneric("cleanbfc"), - signature = "x" -) - -#' @rdname BiocFileCache-class -#' @aliases cleanbfc,missing-method -#' @exportMethod cleanbfc -setMethod("cleanbfc", "missing", - function(x, days = 120, ask = TRUE) -{ - cleanbfc(x=BiocFileCache(), days=days, ask=ask) -}) - -#' @describeIn BiocFileCache Remove old/unused files in -#' BiocFileCache. If file to be removed is not in the bfccache -#' location it will not be deleted. Setting \code{days=-Inf} -#' will remove all cached files. -#' @param days integer(1) Number of days between accessDate and -#' currentDate; if exceeded entry will be deleted. -#' @return For 'cleanbfc': updated BiocFileCache, invisibly. -#' @examples -#' \dontrun{cleanbfc(bfc, ask=FALSE)} -#' @aliases cleanbfc -#' @exportMethod cleanbfc -setMethod("cleanbfc", "BiocFileCache", - function(x, days = 120, ask=TRUE) -{ - stopifnot(is.numeric(days), length(days) == 1L, !is.na(days)) - stopifnot(is.logical(ask), length(ask) == 1L, !is.na(ask)) - - rids <- .sql_clean_cache(x, days) - rpaths <- .sql_get_rpath(x, rids) - cached <- startsWith(rpaths, bfccache(x)) - - if (ask) { - txt0 <- paste("file ", sQuote(rpaths)) - txt <- sprintf("Remove id %s %s", sQuote(rids), ifelse(cached, txt0, "")) - doit <- vapply(txt, .util_ask, logical(1)) - - rids <- rids[doit] - cached <- cached & doit - } - - .sql_remove_resource(x, rids) - .util_unlink(rpaths[cached]) - - invisible(x) -}) - -#' @export -setGeneric("removebfc", - function(x, ask = TRUE) standardGeneric("removebfc"), - signature="x" -) - -#' @rdname BiocFileCache-class -#' @aliases removebfc,missing-method -#' @exportMethod removebfc -setMethod("removebfc", "missing", - function(x, ask = TRUE) -{ - removebfc(x=BiocFileCache(), ask=ask) -}) - -#' @describeIn BiocFileCache Completely remove the BiocFileCache -#' @return For 'removebfc': TRUE if successfully removed. -#' @examples -#' \dontrun{removebfc(bfc, ask=FALSE)} -#' @aliases removebfc -#' @exportMethod removebfc -setMethod("removebfc", "BiocFileCache", - function(x, ask=TRUE) -{ - stopifnot(is.logical(ask), length(ask) == 1L, !is.na(ask)) - - doit <- FALSE - txt <- paste("remove cache and", length(x), "resource(s)?") - if (!ask || .util_ask(txt)) - doit <- .util_unlink(bfccache(x), recursive=TRUE) - - doit -}) - -#' @describeIn BiocFileCache Display a \code{BiocFileCache} instance. -#' @param object A \code{BiocFileCache} instance. -#' @exportMethod show -setMethod("show", "BiocFileCacheBase", - function(object) -{ - cat("class: ", class(object), "\n", - "bfccache: ", bfccache(object), "\n", - "bfccount: ", bfccount(object), "\n", - "For more information see: bfcinfo() or bfcquery()\n", - sep="") -}) diff --git a/R/httr.R b/R/httr.R deleted file mode 100644 index 7002934..0000000 --- a/R/httr.R +++ /dev/null @@ -1,195 +0,0 @@ -# taken/based on httr::parse_http_date -.fmt_http_date <- function(x, failure = structure(NA_real_, class = "Date")) { - if (length(x) == 0) - return(NULL) - fmts <- c("%a, %d %b %Y %H:%M:%S", "%A, %d-%b-%y %H:%M:%S", - "%a %b %d %H:%M:%S %Y") - for (fmt in fmts) { - parsed <- as.POSIXct(strptime(x, fmt, tz = "GMT")) - if (all(!is.na(parsed))) - return(parsed) - } - rep(failure, length(x)) -} - -# taken/based on httr::parse_cache_control -.fmt_cache_control <- function(cachecontrol){ - if (is.null(cachecontrol)) - return(list()) - pieces <- strsplit(cachecontrol, ",")[[1]] - pieces <- gsub("^\\s+|\\s+$", "", pieces) - pieces <- tolower(pieces) - is_value <- grepl("=", pieces) - flags <- pieces[!is_value] - keyvalues <- strsplit(pieces[is_value], "\\s*=\\s*") - keys <- c(rep("flags", length(flags)), lapply(keyvalues, - "[[", 1)) - values <- c(flags, lapply(keyvalues, "[[", 2)) - stats::setNames(values, keys) -} - -# taken/based on httr::cache_info -.get_http_expires <- function(response){ - expires <- .fmt_http_date(resp_header(response, "expires"), Inf) %||% NULL - control <- .fmt_cache_control(resp_header(response, "cache-control")) - max_age <- as.integer(control$`max-age`) %||% NULL - if (!is.null(max_age)) { - expires <- .fmt_http_date(resp_header(response, "date")) + max_age - } else { - if (!is.null(resp_header(response, "expires"))) { - expires <- .fmt_http_date(resp_header(response, "expires"), -Inf) - } else { - expires <- NULL - } - } - expires -} - -.httr_get_cache_info <- - function(link, proxy, config) -{ - if(missing(config)) - config <- NULL - - if((length(config)==0)){ - config <- NULL - } else { - stopifnot(is.list(config)) - } - - if (missing(proxy)){ - proxy <- "" - } - if (proxy == ""){ - proxy <- NULL - } - - req <- request(link) %>% - req_method("HEAD") - - # Apply the proxy if it's not NULL - if (!is.null(proxy)) { - req <- req %>% req_proxy(proxy) - } - - # Apply the config if it's not NULL - if (!is.null(config)) { - req <- req %>% req_options(!!!config) - } - - response = tryCatch({ - req %>% req_perform() - }, warning = function(w) { - invokeRestart("muffleWarning") - }, error = function(e){ - message("Error while performing HEAD request.\n", - " Proceeding without cache information.") - response() - }) - - tryCatch({ - etag <- ifelse(resp_header_exists(response, "etag"), - gsub("\"", "",as.character(resp_header(response, "etag"))), - NA_character_) - last_mod <- ifelse(resp_header_exists(response, "last-modified"), - as.character(.fmt_http_date(resp_header(response, "last-modified"))), - NA_character_) - expires <- .get_http_expires(response) - expires <- ifelse(is.null(expires), NA_character_, as.character(expires)) - - c(etag = etag, modified = last_mod, expires = expires) - }, error = function(err) { - - if ("etag" %in% names(response$headers)){ - etag = as.character(response[["headers"]]["etag"]) - } else { - etag = NA_character_ - } - if ("last-modified" %in% names(response$headers)){ - modified = as.character(response[["headers"]]["last-modified"]) - } else { - modified = NA_character_ - } - if ("cache-control" %in% names(response$headers)){ - cachecontrol = - .fmt_cache_control(as.character(response[["headers"]]["cache-control"])) - max_age = as.integer(control$`max-age`) %||% NULL - if (!is.null(max_age)) { - expires <- .fmt_http_date(as.character(response[["headers"]]["date"])) + max_age - }else{ - if ("expires" %in% names(response$headers)){ - expires = as.character(response[["headers"]]["expires"]) - } else { - expires = NA_character_ - } - } - } else { - expires = NA_character_ - } - - c(etag = etag, modified = modified, expires = expires) - }) -} - -#' @importFrom utils packageVersion -.httr_download <- - function(websource, localfile, proxy, progress, config, ...) -{ - - ## retrieve file from hub to cache - tryCatch({ - - if (proxy == ""){ - proxy <- NULL - } - - if((length(config)==0)){ - config <- NULL - } else { - stopifnot(is.list(config)) - } - - if(missing(progress)){ - progress=TRUE - } - - if (!all(file.exists(dirname(localfile)))) dir.create(dirname(localfile), recursive=TRUE) - - # set up request using httr2 - req <- request(websource) - # This enables progress bars in httr2 - if((interactive() && progress)){ - req <- req %>% req_progress() - } - # Apply the proxy if it's not NULL - if (!is.null(proxy)) { - req <- req %>% req_proxy(proxy) - } - # Apply the config if it's not NULL - if (!is.null(config)) { - req <- req %>% req_options(!!!config) - } - ## httr2 req_perform does not have an overwrite - ## assume overwrite will occur automatically - ## Perform the request and capture the response - response <- req_perform(req, path=localfile, ...) - - cat("\n") ## line break after progress bar - -# No longer needed? -# if (length(status_code(response))) { -# if (status_code(response) != 302L) -# stop_for_status(response) -# } - - TRUE - }, error = function(err) { - warning("download failed", - "\n web resource path: ", sQuote(websource), - "\n local file path: ", sQuote(localfile), - "\n reason: ", conditionMessage(err), - call.=FALSE) - FALSE - }) - -} diff --git a/R/makeBiocFileCacheFromDataFrame.R b/R/makeBiocFileCacheFromDataFrame.R deleted file mode 100644 index 1023049..0000000 --- a/R/makeBiocFileCacheFromDataFrame.R +++ /dev/null @@ -1,212 +0,0 @@ -#' Make BiocFileCache objects from an existing data.frame -#' -#' If there are a lot of resources being added this could take some -#' time but if a cache is saved in a permanent location this should -#' only have to be run once. The original data.frame must have the -#' required columns 'rtype', 'fpath', and 'rpath'; See the vignette -#' for more information on the expected information contained in these -#' columns. Similarly, the optional columns 'rname', 'etag', -#' 'last_modified_time', and 'expires' may be included. Any additional columns -#' not listed as required or optional will be kept as an additional -#' metadata table in the BiocFileCache database. -#' -#' @param df data.frame or tibble to convert -#' @param cache character(1) On-disk location (directory path) of -#' cache. For default location see -#' \code{\link[tools]{R_user_dir}}. -#' @param actionLocal If local copy of file should be moved, copied or -#' left in original location. See 'action' param of bfcadd. -#' @param actionWeb If a local copy of a remote resource already -#' exists, should the file be copied or moved to the -#' cache. Locally downloaded remote resources must exist in the -#' cache location. -#' @param metadataName If there are additional columns of data in the -#' original data.frame besides required BiocFileCache columns, -#' this data will be added as a metadata table with this name. -#' @param ... additional arguments passed to `file.copy()`. -#' @param ask logical(1) Confirm creation of BiocFileCache. -#' -#' @return A BiocFileCache object -#' -#' @examples -#' ## Create a data.frame with the required columns -#' tempf <- tempfile(fileext = ".txt") -#' file.create(tempf) -#' df <- data.frame( -#' rtype = "local", -#' fpath = tempf, -#' rpath = tempf, -#' rname = "Example File 1", -#' etag = "etag1", -#' last_modified_time = as.character(Sys.Date()), -#' expires = as.character(Sys.Date() + 1), -#' stringsAsFactors = FALSE -#' ) -#' ## Create a BiocFileCache from the data.frame -#' bfc <- makeBiocFileCacheFromDataFrame( -#' df, cache = tempfile(), actionLocal = "move", -#' metadataName = "resourceMetadata", ask = FALSE -#' ) -#' bfc -#' bfcinfo(bfc) -#' removebfc(bfc, ask = FALSE) -#' -#' @export -setGeneric("makeBiocFileCacheFromDataFrame", - function(df, cache, - actionLocal=c("move","copy","asis"), actionWeb=c("move","copy"), - metadataName, - ..., ask = TRUE) - standardGeneric("makeBiocFileCacheFromDataFrame"), - signature = "df" -) - -#' @rdname makeBiocFileCacheFromDataFrame -#' @aliases makeBiocFileCacheFromDataFrame,ANY-method -#' @exportMethod makeBiocFileCacheFromDataFrame -setMethod("makeBiocFileCacheFromDataFrame", "ANY", - function(df, cache, - actionLocal=c("move","copy","asis"), actionWeb=c("move","copy"), - metadataName, - ..., ask = TRUE) -{ - stopifnot(is.data.frame(df)) - DF <- as.data.frame(df, stringsAsFactors = FALSE) - if (missing(cache)) - cache <- tools::R_user_dir("BiocFileCache", which="cache") - stopifnot( - is.character(cache), length(cache) == 1L, !is.na(cache), - !dir.exists(cache) - ) - actionLocal <- match.arg(actionLocal) - actionWeb <- match.arg(actionWeb) - - .required <- c("rtype", "fpath", "rpath") - .optional <- c("rname", "etag", "last_modified_time", "expires") - .possible <- c(.required, .optional) - if (!all(.required %in% names(DF))) { - stop("One of the following required columns in not in data.frame:", - "\n ", paste(.required, collapse=", "), - "\n Please insert into original data.frame") - } - .optional <- .optional[.optional %in% names(DF)] - .available <- c(.required, .optional) - metadata <- names(DF)[!names(DF) %in% .available] - if (any(metadata %in% c("rid",.RESERVED$COLUMNS))) { - nocols <- c("rid", setdiff(.RESERVED$COLUMNS, .possible)) - stop("The following are reserved column names:", - "\n ", paste(nocols, collapse=", "), - "\n Please rename offending column name.") - } - if (length(metadata) != 0) - stopifnot(!missing(metadataName), - is.character(metadataName), length(metadataName) == 1L, - !is.na(metadataName), !(metadataName %in% .RESERVED$TABLES)) - - # validity of .required columns - stopifnot(is.character(DF[["rtype"]]), - is.character(DF[["fpath"]]), - is.character(DF[["rpath"]])) - rtype <- DF[["rtype"]] - fpath <- DF[["fpath"]] - rpath <- DF[["rpath"]] - - stopifnot(all(rtype %in% c("web", "local"))) - web <- which(rtype == "web") - if (length(web) != 0L) { - webpaths <- fpath[web] - test <- startsWith(webpaths, "http") | startsWith(webpaths, "ftp") - if (!all(test)) - stop("Some source urls for files identified with 'rtype=web'\n", - " do not start with: http, https, or ftp") - } - nonweb <- which(rtype != "web") - if (length(nonweb) != 0L && !all(file.exists(rpath[nonweb]))) - stop("Not all files identified as 'rtype=local' have existing files") - - # validity of .optional columns - if (length(.optional) != 0L) { - check <- vapply(.optional, FUN = function(x, df) { - is.character(df[[x]]) - }, logical(1), df=DF) - if (!all(check)) - stop("The following columns must have entries of type 'character':", - "\n ", paste(.optional, collapse=", ")) - } - if ("last_modified_time" %in% .optional) { - check <- tryCatch({ - as.Date(DF[["last_modified_time"]]) - TRUE - }, error=function(e) { - warning(conditionMessage(e)) - FALSE - }) - if (!check) { - stop("Column 'last_modified_time' must have entries of type ", - "'character' that can be converted to Date via 'as.Date()'") - } - modified <- DF[["last_modified_time"]] - } else { - modified <- rep(NA_character_, nrow(DF)) - } - - if ("rname" %in% .optional) { - rname <- DF[["rname"]] - } else { - rname <- fpath - } - - if ("etag" %in% .optional) { - etag <- DF[["etag"]] - } else { - etag <- rep(NA_character_, nrow(DF)) - } - - if ("expires" %in% .optional) { - expires <- DF[["expires"]] - } else { - expires <- rep(NA_character_, nrow(DF)) - } - - bfc <- BiocFileCache(cache, ask = ask) - - # add resources to cache - for (i in seq_len(nrow(DF))) { - - if (rtype[i] == "web") { - npath <- fpath[i] - action <- actionWeb - } else { - npath <- rpath[i] - action <- actionLocal - } - - res <- bfcadd(bfc, rname=rname[i], fpath = npath, rtype = "auto", - action = action, download=FALSE, ...) - rid <- names(res) - .sql_set_last_modified(bfc, rid, modified[i]) - .sql_set_etag(bfc, rid, etag[i]) - .sql_set_expires(bfc, rid, expires[i]) - } - - # if local version of remote exists, copy or move - for (i in web) { - cpath <- bfcrpath(bfc, rids=paste0("BFC",i)) - opath <- rpath[i] - if (file.exists(opath)) { - switch(actionWeb, - copy = file.copy(opath, cpath, ...), - move = file.rename(opath, cpath) - ) - } - } - - # create metadata - if (length(metadata) != 0) { - tbl <- cbind(rid=paste0("BFC",seq_len(nrow(DF))), - DF[,metadata,drop=FALSE]) - bfcmeta(bfc, name=metadataName) <- tbl - } - - bfc -}) diff --git a/R/makeCachedActiveBinding.R b/R/makeCachedActiveBinding.R deleted file mode 100644 index 494cd28..0000000 --- a/R/makeCachedActiveBinding.R +++ /dev/null @@ -1,47 +0,0 @@ -#' makeCachedActiveBinding -#' -#' Like \code{\link{makeActiveBinding}} but the value of the active -#' binding gets only evaluated once and is "remembered". -#' -#' @param sym See \code{\link{makeActiveBinding}} in the \pkg{base} -#' package. -#' @param fun See \code{\link{makeActiveBinding}} in the \pkg{base} -#' package. -#' @param env See \code{\link{makeActiveBinding}} in the \pkg{base} -#' package. -#' @param verbose Set to TRUE to see caching in action (useful for -#' troubleshooting). -#' -#' @name makeCachedActiveBinding -#' @aliases makeCachedActiveBinding -#' @export makeCachedActiveBinding -#' -#' @examples -#' makeCachedActiveBinding("x", function() runif(1), verbose=TRUE) -#' x -#' x -makeCachedActiveBinding <- function(sym, fun, env=.GlobalEnv, verbose=FALSE) -{ - caching_env <- new.env(parent=emptyenv()) - fun2 <- function(value) { - if (!missing(value)) - stop("assignment to active binding '", sym, "' is not allowed") - val <- try(get(sym, envir=caching_env, inherits=FALSE), silent=TRUE) - if (inherits(val, "try-error")) { - if (verbose) - cat("evaluating and caching value ", - "for active binding '", sym, "' ... ", sep="") - val <- fun() - assign(sym, val, envir=caching_env) - if (verbose) - cat("OK\n") - } else { - if (verbose) - cat("using cached value for active binding '", sym, "'\n", - sep="") - } - val - } - makeActiveBinding(sym, fun2, env=env) -} - diff --git a/R/sql.R b/R/sql.R deleted file mode 100644 index cec6b9a..0000000 --- a/R/sql.R +++ /dev/null @@ -1,517 +0,0 @@ -#' @import RSQLite -#' @importFrom DBI dbExecute dbSendStatement -#' @import dbplyr -#' @importFrom dplyr %>% tbl select collect summarize filter n left_join -#' @importFrom curl curl_escape -#' @importFrom filelock lock unlock - -.formatID <- . %>% collect(Inf) %>% `[[`("rid") - -lock.env <- new.env() -lock.env$status <- NA - -.lock2 <- function(dbfile, exclusive) { - if (is.na(lock.env$status)) { - lock.env$status <- exclusive - lock(.sql_lock_path(dbfile), exclusive = exclusive) - } else if (lock.env$status || !exclusive) { - # Exclusive lock held by a caller is compatible - # with a subsequent request for a shared lock; - # we're not escalating privileges here. - NULL - } else { - stop("requested an exclusive lock when caller only holds a shared lock") - } -} - -.unlock2 <- function(loc) { - if (!is.null(loc)) { - lock.env$status <- NA - unlock(loc) - } -} - -.sql_file <- - function(bfc, file) -{ - file.path(bfccache(bfc), file) -} - -.sql_dbfile <- - function(bfc) -{ - .sql_file(bfc, .CACHE_FILE) -} - -.sql_cmd <- - function(cmd_name, add=FALSE, ...) -{ - sql_cmd_file <- - system.file(package="BiocFileCache", "schema", "BiocFileCache.sql") - sql_cmds <- readLines(sql_cmd_file) - grps <- cumsum(grepl("^--", sql_cmds)) - cmds <- split(sql_cmds, grps) - names <- vapply(cmds, "[[", character(1), 1) - cmds <- paste(cmds[[which(names == cmd_name)]], collapse="\n") - if (add) - cmds <- sprintf(cmds, ...) - cmds -} - -.sql_lock_path <- - function(dbfile) -{ - paste0(dbfile, '.LOCK') -} - -.sql_connect_RO <- - function(dbfile) -{ - ## See notes in AnnotationDbi::dbFileConnect - ## did not want to import AnnotationDbi in BFC because it is large - ## overkill for this function - if (!file.exists(dbfile)) - stop("DB file '", dbfile, "' not found") - - loc <- .lock2(dbfile, exclusive=FALSE) - - if (.Platform$OS.type == "unix") { - con <- dbConnect(SQLite(), dbname=dbfile, cache_size=64000L, - synchronous="off", flags=SQLITE_RO, vfs="unix-none") - } else { - ## Use default 'vfs' on Windows. - con <- dbConnect(SQLite(), dbname=dbfile, cache_size=64000L, - synchronous="off", flags=SQLITE_RO) - } - - list(lock=loc, con=con) -} - -.sql_connect_RW <- - function(dbfile) -{ - ## We also need a RW function to allow writing to the cache - - loc <- .lock2(dbfile, exclusive=TRUE) - - if (.Platform$OS.type == "unix") { - con <- dbConnect(SQLite(), dbname=dbfile, cache_size=64000L, - synchronous="off", vfs="unix-none") - } else { - ## Use default 'vfs' on Windows. - con <- dbConnect(SQLite(), dbname=dbfile, cache_size=64000L, - synchronous="off") - } - - list(lock=loc, con=con) -} - -.sql_disconnect <- - function(info) -{ - dbDisconnect(info$con) - .unlock2(info$lock) -} - -.sql_schema_version <- - function(bfc) -{ - tryCatch({ - info <- .sql_connect_RO(.sql_dbfile(bfc)) - con <- info$con - src <- src_dbi(con) - tbl <- tbl(src, "metadata") %>% collect(n = Inf) - }, finally={.sql_disconnect(info)}) - tbl$value[tbl$key=="schema_version"] -} - -## R / RSQLite, DBI interface - -.sql_db_execute <- - function(bfc, sql, ..., con) -{ - param <- data.frame(..., stringsAsFactors = FALSE) - if (nrow(param) == 0L) - param <- NULL - - if (missing(con)) { - info <- .sql_connect_RW(.sql_dbfile(bfc)) - con <- info$con - on.exit(.sql_disconnect(info)) - } - dbExecute(con, sql, params = param) -} - -.sql_db_get_query <- - function(bfc, sql, ..., con) -{ - param <- data.frame(..., stringsAsFactors = FALSE) - if (nrow(param) == 0L) - param <- NULL - - if (missing(con)) { - info <- .sql_connect_RO(.sql_dbfile(bfc)) - con <- info$con - on.exit(.sql_disconnect(info)) - } - dbGetQuery(con, sql, param) -} - -## BiocFileCache / RSQLite interface - -.sql_create_db <- - function(bfc) -{ - fl <- .sql_dbfile(bfc) - if (!file.exists(fl)) { - sql <- strsplit(.sql_cmd("-- CREATE_DB"), ";")[[1]] - tryCatch({ - info <- .sql_connect_RW(.sql_dbfile(bfc)) - con <- info$con - dbExecute(con, sql[[1]]) - ## update metadata table - .sql_db_execute(bfc, sql[[2]], con=con) - package_version <- as.character(packageVersion("BiocFileCache")) - .sql_db_execute( - bfc, sql[[3]], - key = c('schema_version', 'package_version'), - value = c(.CURRENT_SCHEMA_VERSION, package_version), - con=con) - ## create new resource table - .sql_db_execute(bfc, sql[[4]], con=con) - dbExecute(con, sql[[5]]) - }, finally={.sql_disconnect(info)}) - } - .sql_validate_version(bfc) - fl -} - -.sql_select_query <- - function(bfc, where, ...) -{ - sql <- .sql_cmd("-- SELECT_QUERY") - cmd <- sprintf(sql, where) - res <- .sql_db_get_query(bfc, cmd, ...) - class(res) <- c("tbl_bfc", class(res)) - res -} - -.sql_add_resource <- - function(bfc, rname, rtype, fpath, ext = NA_character_, fname = "unique") -{ - # The connection attempt handles locking if another process is adding a - # resource at the same time; by trying to connect first, we don't have to - # worry about whether the choice of temporary file name is thread-safe. - info <- .sql_connect_RW(.sql_dbfile(bfc)) - on.exit(if (!is.null(info)) { .sql_disconnect(info) }) - - rpath <- rep(path.expand(tempfile("", bfccache(bfc))), length(fpath)) - rtype <- unname(rtype) - dx <- rtype == "relative" | rtype == "web" - rpath[dx] <- basename(rpath[dx]) - - fpath[is.na(fpath)] <- rpath[is.na(fpath)] - ext[is.na(ext)] <- "" - bfname <- basename(fpath) - bfname <- curl_escape(bfname) - if (fname=="unique") { - rpath <- sprintf("%s_%s%s", rpath, bfname, ext) - } else { - rpath <- sprintf("%s%s",bfname, ext) - } - sql <- strsplit(.sql_cmd("-- INSERT"), ";")[[1]] - con <- info$con - dbExecute(con, sql[[1]]) - original_rid <- .sql_db_get_query(bfc, sql[[2]], con=con)[["rid"]] - .sql_db_execute( - bfc, sql[[3]], - rname = rname, rtype = rtype, fpath = fpath, rpath = rpath, - last_modified_time = as.Date(NA_character_), etag = NA_character_, - expires = NA_character_, con=con - ) - .sql_db_execute(bfc, sql[[4]], con=con) - rid <- .sql_db_get_query(bfc, sql[[2]], con=con)[["rid"]] - dbExecute(con, sql[[5]]) - - # Free the file, as .sql_get_rpath() reacquires the lock internally. - .sql_disconnect(info) - info <- NULL - - .sql_get_rpath(bfc, setdiff(rid, original_rid)) -} - -.sql_remove_resource <- - function(bfc, rid) -{ - sql <- .sql_cmd("-- REMOVE") - cmd <- sprintf(sql, paste0("'", rid, "'", collapse = ",")) - .sql_db_execute(bfc, cmd) -} - -.sql_get_resource_table <- - function(bfc, rids) -{ - tryCatch({ - info <- .sql_connect_RO(.sql_dbfile(bfc)) - con <- info$con - src <- src_dbi(con) - tbl <- tbl(src, "resource") - - if (missing(rids)) { - } else if (length(rids) == 0) { - tbl <- tbl %>% dplyr::filter(rid == NA_character_) - } else if (length(rids) == 1) { - tbl <- tbl %>% dplyr::filter(rid == rids) - } else { - tbl <- tbl %>% dplyr::filter(rid %in% rids) - } - - ## join metadata - meta <- setdiff(dbListTables(con), .RESERVED$TABLES) - for (m in meta) - tbl <- left_join(tbl, tbl(src, m), by="rid") - - tbl <- tbl %>% collect - }, finally={.sql_disconnect(info)}) - class(tbl) <- c("tbl_bfc", class(tbl)) - tbl %>% dplyr::select(-id) -} - -.sql_get_nrows <- - function(bfc) -{ - summarize(bfc, n=n()) %>% collect %>% `[[`("n") -} - -.sql_get_field <- - function(bfc, id, field) -{ - stopifnot(all(id %in% .get_all_rids(bfc))) - sql <- .sql_cmd("-- SELECT_COLUMN") - cmd <- sprintf(sql, field, paste0("'", id, "'", collapse = ",")) - res <- .sql_db_get_query(bfc, cmd) - setNames(res[[field]], res[["rid"]]) -} - -.sql_get_rname <- - function(bfc, rid) -{ - .sql_get_field(bfc, rid, "rname") -} - -.sql_get_rtype <- - function(bfc, rid) -{ - .sql_get_field(bfc, rid, "rtype") -} - -.sql_get_fpath <- - function(bfc, rid) -{ - .sql_get_field(bfc, rid, "fpath") -} - -.sql_get_rpath <- - function(bfc, rid) -{ - rtype <- .sql_get_rtype(bfc, rid) - rpath <- .sql_get_field(bfc, rid, "rpath") - idx <- rtype %in% c("relative", "web") - rpath[idx] <- file.path(bfccache(bfc), rpath)[idx] - rpath -} - -.sql_set_rpath <- - function(bfc, rid, rpath) -{ - sql <- .sql_cmd("-- UPDATE_PATH") - .sql_db_execute(bfc, sql, rid = rid, rpath = rpath) -} - -.sql_set_time <- - function(bfc, rid) -{ - sql <- .sql_cmd("-- UPDATE_TIME") - cmd <- sprintf(sql, paste0("'", rid, "'", collapse = ",")) - .sql_db_execute(bfc, cmd) -} - -.sql_set_rname <- - function(bfc, rid, rname) - -{ - sql <- .sql_cmd("-- UPDATE_RNAME") - .sql_db_execute(bfc, sql, rid = rid, rname = rname) -} - -.sql_set_rtype <- - function(bfc, rid, rtype) -{ - sql <- .sql_cmd("-- UPDATE_RTYPE") - .sql_db_execute(bfc, sql, rid = rid, rtype = rtype) -} - -.sql_clean_cache <- - function(bfc, days) -{ - mytbl <- .sql_get_resource_table(bfc) %>% - dplyr::select(rid, access_time) %>% collect(Inf) - accessDate <- as.Date(as.character(mytbl$access_time)) - diffTime <- Sys.Date() - accessDate - mytbl[diffTime > days, 1] %>% .formatID -} - -.get_all_rids <- - function(bfc) -{ - sql <- .sql_cmd("-- SELECT_IDS") - .sql_db_get_query(bfc, sql)[,1] -} - -.get_all_web_rids <- - function(bfc) -{ - sql <- .sql_cmd("-- SELECT_WEB") - .sql_db_get_query(bfc, sql)[,1] -} - -.sql_get_last_modified <- - function(bfc, rid) -{ - .sql_get_field(bfc, rid, "last_modified_time") -} - -.sql_set_last_modified <- - function(bfc, rid, last_modified_time) -{ - sql <- .sql_cmd("-- UPDATE_MODIFIED") - .sql_db_execute( - bfc, sql, rid = rid, last_modified_time = last_modified_time - ) -} - -.sql_get_etag <- - function(bfc, rid) -{ - .sql_get_field(bfc, rid, "etag") -} - -.sql_set_etag <- - function(bfc, rid, etag) -{ - sql <- .sql_cmd("-- UPDATE_ETAG") - .sql_db_execute(bfc, sql, rid = rid, etag = etag) -} -.sql_get_expires <- - function(bfc, rid) -{ - .sql_get_field(bfc, rid, "expires") -} - -.sql_set_expires <- - function(bfc, rid, expires) -{ - sql <- .sql_cmd("-- UPDATE_EXPIRES") - .sql_db_execute(bfc, sql, rid = rid, expires = expires) -} - -.sql_set_fpath <- - function(bfc, rid, fpath) -{ - sql <- .sql_cmd("-- UPDATE_FPATH") - .sql_db_execute(bfc, sql, rid = rid, fpath = fpath) -} - -.get_rid_filenotfound <- - function(bfc) -{ - allpaths <- bfcrpath(bfc) - names(allpaths)[!file.exists(allpaths)] -} - -.get_tbl_rid <- - function(tbl) -{ - tbl %>% .formatID -} - -.get_all_colnames <- - function(bfc) -{ - colnames(.sql_get_resource_table(bfc)) -} - -.get_nonrelative_ids <- - function(bfc) -{ - rpaths <- .sql_get_rpath(bfc, bfcrid(bfc)) - res <- startsWith(rpaths, bfccache(bfc)) - names(rpaths)[!res] -} - -## -## .sql_meta_* -## - -.sql_meta_gets <- - function(bfc, name, value, ...) -{ - tryCatch({ - info <- .sql_connect_RW(.sql_dbfile(bfc)) - con <- info$con - dbWriteTable(con, name, value, ...) - }, finally={.sql_disconnect(info)}) -} - -.sql_meta_remove <- - function(bfc, name, ...) -{ - tryCatch({ - info <- .sql_connect_RW(.sql_dbfile(bfc)) - con <- info$con - if (dbExistsTable(con, name)) - dbRemoveTable(con, name, ...) - }, finally={.sql_disconnect(info)}) -} - -.sql_meta <- - function(bfc, name, ...) -{ - tryCatch({ - info <- .sql_connect_RO(.sql_dbfile(bfc)) - con <- info$con - if (!dbExistsTable(con, name)) - stop("'", name, "' not found in database") - dbReadTable(con, name, ...) - }, finally={.sql_disconnect(info)}) -} - -.sql_meta_list <- - function(bfc) -{ - tryCatch({ - info <- .sql_connect_RO(.sql_dbfile(bfc)) - con <- info$con - res <- dbListTables(con) - setdiff(res, .RESERVED$TABLES) - }, finally={.sql_disconnect(info)}) -} - -.sql_filter_metadata <- - function(bfc, name, verbose) -{ - df <- bfcmeta(bfc, name) - rids <- bfcrid(bfc) - check <- as.character(df$rid) %in% rids - if (all(!check)) { - bfcmetaremove(bfc, name) - vl <- FALSE - } else if (any(!check)) { - df <- df[check,] - bfcmeta(bfc, name, overwrite=TRUE) <- df - vl <- FALSE - } else { - vl <- TRUE - } - vl -} diff --git a/R/sql_migration.R b/R/sql_migration.R deleted file mode 100644 index fa0df71..0000000 --- a/R/sql_migration.R +++ /dev/null @@ -1,148 +0,0 @@ -.sql_validate_version <- - function(bfc) -{ - schema_version <- .sql_schema_version(bfc) - - if (!schema_version %in% .SUPPORTED_SCHEMA_VERSIONS) - stop( - "unsupported schema version ", - "\n sqlite file: ", .sql_dbfile(bfc), - "\n file schema version: '", schema_version, "'", - "\n supported version(s): ", - paste(sQuote(.SUPPORTED_SCHEMA_VERSIONS), collapse=" ") - ) - - if (schema_version != .CURRENT_SCHEMA_VERSION) - .sql_migration(bfc) - - schema_version -} - -.sql_migration_update_schema_version <- - function(bfc, schema_version) -{ - ## update metadata table for package version and schema - sql <- .sql_cmd("-- MIGRATION_UPDATE_METADATA") - .sql_db_execute(bfc, sql, key = "schema_version", value = schema_version) - .sql_db_execute( - bfc, sql, key = "package_version", - value = as.character(packageVersion("BiocFileCache")) - ) - - schema_version -} - -.sql_migration <- - function(bfc) -{ - schema_version <- .sql_schema_version(bfc) - - if (.biocfilecache_flags$get_update_asked()) - return(schema_version) - - ## This is necessary for a few modifications from the old schema - ## We made web resource rpaths relative since we only allow to use - ## download and checks if using a cache location for the files - ## default last_modified_time to NA instead of Sys.Date for - ## local/relative/Non downloaded web resources We added option to - ## Non download resource which can't default to Sys.Date - - message("Current schema_version ", schema_version, " is out-of-date.\n\n", - "Current Version will NOT work as expect.\n", - "Recommend Updating to lastest schema_version.\n", - "Notable Changes:\n", - " 1. Web Resource 'rpath' stored as relative path\n", - " 2. Default last_modified time for\n", - " local/relative/nondownloaded/last_modified_notfound\n", - " resources is NA not Sys.Date\n", - " 3. Added etag to schema\n", - " 4. Added expires to schema\n") - doit <- .util_ask( - "Update current BiocFileCache to be consistent with\n", - " schema_version: ", .CURRENT_SCHEMA_VERSION, "\n", - " This will be a permanent change but only necessary once.\n", - " Continue?" - ) - .biocfilecache_flags$set_update_asked() - - if (!doit) { - warning("BiocFileCache schema not updated\n", - " bfccache(): ", bfccache(bfc)) - return() - } - - if (schema_version == "0.99.1") - schema_version <- .sql_migration_0991_to_0992(bfc) - - if (schema_version == "0.99.2") - schema_version <- .sql_migration_0992_to_0993(bfc) - - if (schema_version == "0.99.3") - schema_version <- .sql_migration_0993_to_0994(bfc) - - schema_version -} - -.sql_migration_0993_to_0994 <- - function(bfc) -{ - message("applying migration from 0.99.3 to 0.99.4") - sql <- .sql_cmd("-- MIGRATION_0_99_3_to_0_99_4") - .sql_db_execute(bfc, sql) - .sql_migration_update_schema_version(bfc, "0.99.4") -} - -.sql_migration_0992_to_0993 <- - function(bfc) -{ - message("applying migration from 0.99.2 to 0.99.3") - sql <- .sql_cmd("-- MIGRATION_0_99_2_to_0_99_3") - .sql_db_execute(bfc, sql) - .sql_migration_update_schema_version(bfc, "0.99.3") -} - -.sql_migration_0991_to_0992 <- - function(bfc) -{ - message("applying migration from 0.99.1 to 0.99.2") - ## truncate rpaths of all web resources - wid <- .get_all_web_rids(bfc) - badpaths <- bfcrpath(bfc, rids=wid) - pattern <- paste0(bfccache(bfc),"/", bfccache(bfc),"/") - check <- startsWith(badpaths, pattern) - if (any(!check)) { - ids <- wid[!check] - warning("Some web resources do not currently have rpath in cache.\n", - " Bad paths: ", paste0("'", ids, "'", collapse=" "), "\n", - " These resources will now be considered rtype='local'") - .sql_set_rtype(bfc, ids, "local") - } - - wid <- wid[check] - badpaths <- badpaths[check] - newpaths <- gsub(badpaths, pattern=pattern, replacement="") - message("Updating rpath for the following web resources:\n", - " ", paste0("'", wid, "'", collapse=" ")) - for(i in seq_along(wid)){ - .sql_set_rpath(bfc, wid[i], newpaths[i]) - } - - ## change local/relative lmt to NA - nonweb <- setdiff(.get_all_rids(bfc), wid) - if (length(nonweb) != 0) { - message("Updating last modified time for the following\n", - " non web resources:\n", - " ", paste0("'", nonweb, "'", collapse=" ")) - .sql_set_last_modified(bfc, nonweb, NA_character_) - } - - ## check last_modified of all web - for (i in seq_along(wid)) { - fpath <- .sql_get_fpath(bfc, wid[i]) - check_time <- .httr_get_cache_info(fpath)[["modified"]] - if (is.na(check_time)) - .sql_set_last_modified(bfc, wid[i], NA_character_) - } - - .sql_migration_update_schema_version(bfc, "0.99.2") -} diff --git a/R/utilities.R b/R/utilities.R deleted file mode 100644 index 7975953..0000000 --- a/R/utilities.R +++ /dev/null @@ -1,224 +0,0 @@ -.CACHE_FILE <- "BiocFileCache.sqlite" -.CACHE_FILE_LOCK <- "BiocFileCache.sqlite.LOCK" - -.CURRENT_SCHEMA_VERSION <- "0.99.4" - -.SUPPORTED_SCHEMA_VERSIONS <- c("0.99.1", "0.99.2", "0.99.3", "0.99.4") - -.RESERVED <- list( # dynamically, in .onLoad? - TABLES = c("metadata", "resource", "sqlite_sequence"), - COLUMNS = c( - "id", "rname", "create_time", "access_time", "rpath", "rtype", - "fpath", "last_modified_time", "etag", "expires" - ) -) - -.biocfilecache_flags <- local({ - update_asked <- FALSE - create_asked <- FALSE - ## used for unit tests -- default response to '.util_ask' - ask_response <- NULL - list(get_update_asked = function() { - update_asked - }, set_update_asked = function() { - update_asked <<- TRUE - }, get_create_asked = function() { - create_asked - }, set_create_asked = function() { - create_asked <<- TRUE - }, get_ask_response = function() { - ask_response - }, set_ask_response = function(value) { - #oresponse <- ask_response - ask_response <<- value - #invisible(oresponse) - }) -}) - -.util_standardize_rtype <- - function(rtype, fpath, action) -{ - stopifnot(length(rtype) == length(fpath), - length(fpath) == length(action)) - - vapply(seq_along(fpath), - function(i, rtype, fpath, action){ - .util_standardize_rtype_helper(rtype[i], fpath[i], action[i]) - }, - character(1), USE.NAMES=FALSE, rtype=rtype, fpath=fpath, - action=action) -} - -.util_standardize_rtype_helper<- - function(rtype, fpath, action) -{ - if (identical(unname(rtype), "auto")) { - test <- startsWith(fpath, "http") || startsWith(fpath, "ftp") - if (test) - rtype <- "web" - else if (action == "asis") - rtype <- "local" - else - rtype <- "relative" - } else if (rtype != "local" && action == "asis") { - warning( - "action = 'asis' requires rtype = 'local'; ", - "setting rtype = 'local'" - ) - rtype <- "local" - } - - rtype -} - - -.util_ask <- - function(..., .interactive = interactive()) -{ - if (!.interactive) - return(FALSE) - txt <- paste0(..., " (yes/no): ") - if (!is.null(.biocfilecache_flags$get_ask_response())) { - ## unit tests only - message(txt) - return(.biocfilecache_flags$get_ask_response()) - } - repeat { - response <- substr(tolower(readline(txt)), 1, 1) - doit <- switch(response, y = TRUE, n = FALSE, NA) - if (!is.na(doit)) - break - } - doit -} - -.util_unlink <- - function(rpaths, ...) -{ - gc() - status <- unlink(rpaths, ..., force=TRUE) == 0L - if (!all(status)) - warning( - "failed to unlink cache resource(s):", - "\n ", paste(sQuote(rpaths[status]), collapse="\n ") - ) - gc() - status -} - -.util_set_cache_info <- - function(bfc, rid, fpath = .sql_get_fpath(bfc, rid), proxy, config) -{ - if (length(rid) == 0L) - return(bfc) - - cache_info <- .httr_get_cache_info(fpath, proxy, config) - .sql_set_last_modified(bfc, rid, cache_info[["modified"]]) - .sql_set_etag(bfc, rid, cache_info[["etag"]]) - .sql_set_expires(bfc, rid, cache_info[["expires"]]) - bfc -} - -.util_download <- - function(bfc, rid, proxy, progress, config, call, ...) -{ - rpath <- .sql_get_rpath(bfc, rid) - fpath <- .sql_get_fpath(bfc, rid) - status <- Map( - .httr_download, fpath, rpath, - MoreArgs = list(proxy = proxy, progress = progress, config = config, ...) - ) - ok <- vapply(status, isTRUE, logical(1)) - if (!all(ok)) { - bfcremove(bfc, rid[!ok]) - warning( - call, " failed; resource removed", - "\n rid: ", paste(rid[!ok], collapse = " "), - "\n fpath: ", paste(sQuote(fpath[!ok]), collapse = "\n "), - "\n reason: download failed", - call. = FALSE - ) - } - .util_set_cache_info(bfc, rid[ok], proxy=proxy, config=config) - - if (!all(ok)) - stop(call, " failed; see warnings()") -} - -.util_download_and_rename <- - function(bfc, rid, proxy, progress, config, call, fpath = .sql_get_fpath(bfc, rid), - FUN, ...) -{ - rpath <- .sql_get_rpath(bfc, rid) - force(fpath) - - # The connection is not actually necessary - but we just use it to - # handle thread-safe locking, specifically to avoid race conditions - # from multiple threads choosing the same tempfile name during download. - info <- .sql_connect_RW(.sql_dbfile(bfc)) - on.exit(.sql_disconnect(info)) - - if (missing(FUN)) - FUN <- file.rename - - status <- Map(function(rpath, fpath) { - temppath <- tempfile(tmpdir=bfccache(bfc)) - - status <- .httr_download(fpath, temppath, proxy, progress, config, ...) - if (!status) - return("download failed") - - status <- tryCatch({ - st <- FUN(temppath, rpath) - if (file.exists(temppath)){ file.remove(temppath) } - st - }, error = function(err){ - warning("FUN() failed", - "\n reason: ", conditionMessage(err), - call.=FALSE) - FALSE - }) - - status - }, rpath, fpath) - - ok <- vapply(status, isTRUE, logical(1)) - if (!all(ok)) - warning( - call, " failed", - "\n rid: ", paste(rid[!ok], collapse=" "), - "\n file: ", paste(sQuote(fpath)[!ok], collapse = "\n "), - "\n reason: ", paste(unique(unlist(status[!ok])), collapse = ", "), - call. = FALSE - ) - - .util_set_cache_info(bfc, rid[ok], fpath[ok], proxy=proxy, config=config) - - if (!all(ok)) - stop("download failed; see warnings()", call.=FALSE) -} - -.util_export_file <- - function(bfc, rid, dir) -{ - - rtype <- .sql_get_rtype(bfc, rid) - rpath <- .sql_get_rpath(bfc, rid) - loc <- file.exists(rpath) - if (!loc) { - if (identical(unname(rtype), "web")) { - vl <- "web" - } else { - vl <- NA_character_ - } - } else { - if (identical(unname(rtype), "local")) { - vl <- "local" - } else { - newpath <- file.path(dir, basename(rpath)) - file.copy(rpath, newpath) - vl <- "relative" - } - } - vl -} diff --git a/R/zzz.R b/R/zzz.R deleted file mode 100644 index 4ee58df..0000000 --- a/R/zzz.R +++ /dev/null @@ -1,11 +0,0 @@ -globalVariables(c("rid", "id", "control", "access_time")) - -.onLoad <- function(libname, pkgname, ...) { - ## options from getOption or Sys.env or default, in that order - if (is.null(getBFCOption("CACHE"))) { - path <- tools::R_user_dir("BiocFileCache", which="cache") - opt <- getOption("BFC_CACHE", path) - opt <- Sys.getenv("BFC_CACHE", opt) - setBFCOption("CACHE", opt) - } -} diff --git a/README.md b/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/TODO.md b/TODO.md deleted file mode 100644 index 83770f6..0000000 --- a/TODO.md +++ /dev/null @@ -1,58 +0,0 @@ -######################### -# -# quick run -# -######################### - -library(devtools) -library(RSQLite) -library(DBI) -library(dplyr) -library(httr) -library(testthat) -document() -install() -library(BiocFileCache) -example("BiocFileCache-class") - -## SCHEMA help -library(devtools) -library(RSQLite) -library(dplyr) -library(httr) -library(DBI) -install() -library(BiocFileCache) -source("R/utilities.R") -source("R/sql.R") - -bfc = BiocFileCache() - -bfc0 <- BiocFileCache(tempfile()) -path <- bfcnew(bfc0, "NewResource") - - -sqlfile <- .sql_dbfile(bfc0) -con <- dbConnect(SQLite(), sqlfile) -dbReadTable(con, "resource") - -## meta data testing -x = BiocFileCache() - -bfcinfo() - -bfclistmeta() - -meta = as.data.frame(list(rid=c("BFC1", "BFC3"), info=c("something", "to add"), -num=c(1,3))) -meta2 = as.data.frame(list(rid=c("BFC5", "BFC6"), new=c("blah", "foo"), info=c(4,6))) - -bfcaddmeta(meta=meta) -bfcaddmeta(meta=meta2) -bfcaddmeta(meta=meta2, name="secondname") - -bfclistmeta() - -bfcinfo() -bfcinfo(rids=c("BFC11", "BFC7")) -bfcgetmeta(name="resourcedata") diff --git a/_pkgdown.yml b/_pkgdown.yml new file mode 100644 index 0000000..b510c36 --- /dev/null +++ b/_pkgdown.yml @@ -0,0 +1,26 @@ +url: https://bioconductor.github.io/BiocFileCache + +home: + strip_header: true + title: "BiocFileCache" + template: + bootstrap: 5 + params: + bootswatch: flatly + +navbar: + structure: + left: [intro, articles, reference, news] + right: [github] + components: + intro: ~ + articles: + text: "Articles" + href: articles/index.html + +vignettes: + - file: "BiocFileCache.Rmd" + home: TRUE + disable: TRUE + - file: "BiocFileCache_Troubleshooting.Rmd" + - file: "BiocFileCache_UseCases.Rmd" diff --git a/inst/schema/BiocFileCache.sql b/inst/schema/BiocFileCache.sql deleted file mode 100644 index 6924330..0000000 --- a/inst/schema/BiocFileCache.sql +++ /dev/null @@ -1,87 +0,0 @@ --- IF UPDATE SCHEME CHANGE VARIABLES IN utilities.R --- CREATE_DB -BEGIN TRANSACTION; -CREATE TABLE metadata ( - key TEXT UNIQUE NOT NULL, - value TEXT -); -INSERT INTO metadata ( - key, value -) VALUES (:key, :value); -CREATE TABLE resource ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - rid TEXT, - rname TEXT, - create_time DATETIME DEFAULT CURRENT_TIMESTAMP, - access_time DATETIME DEFAULT CURRENT_TIMESTAMP, - rpath TEXT, - rtype TEXT, - fpath TEXT, - last_modified_time DATETIME DEFAULT NA, - etag TEXT DEFAULT NA, - expires DATETIME DEFAULT NA -); -COMMIT; --- INSERT -BEGIN TRANSACTION; -SELECT rid FROM resource; -INSERT INTO resource ( - rname, rpath, rtype, fpath, last_modified_time, etag, expires -) VALUES ( - :rname, :rpath, :rtype, :fpath, :last_modified_time, :etag, :expires -); -UPDATE resource SET rid = "BFC" || id; -COMMIT; --- REMOVE -DELETE FROM resource WHERE rid IN (%s); --- SELECT_QUERY -SELECT * FROM resource WHERE %s; --- SELECT_COLUMN -SELECT rid, %s FROM resource WHERE rid IN (%s); --- SELECT_IDS -SELECT rid FROM resource; --- SELECT_WEB -SELECT rid FROM resource where rtype == 'web'; --- UPDATE_PATH -UPDATE resource -SET rpath = :rpath, access_time = CURRENT_TIMESTAMP -WHERE rid = :rid; --- UPDATE_TIME -UPDATE resource -SET access_time = CURRENT_TIMESTAMP -WHERE rid IN (%s); --- UPDATE_RNAME -UPDATE resource -SET rname = :rname, access_time = CURRENT_TIMESTAMP -WHERE rid = :rid; --- UPDATE_RTYPE -UPDATE resource -SET rtype = :rtype, access_time = CURRENT_TIMESTAMP -WHERE rid = :rid; --- UPDATE_MODIFIED -UPDATE resource -SET last_modified_time = :last_modified_time, access_time = CURRENT_TIMESTAMP -WHERE rid = :rid; --- UPDATE_FPATH -UPDATE resource -SET fpath = :fpath, access_time = CURRENT_TIMESTAMP -WHERE rid = :rid; --- UPDATE_ETAG -UPDATE resource -SET etag = :etag, access_time = CURRENT_TIMESTAMP -WHERE rid = :rid; --- UPDATE_EXPIRES -UPDATE resource -SET expires = :expires, access_time = CURRENT_TIMESTAMP -WHERE rid = :rid; --- MIGRATION_0_99_1_to_0_99_2 --- MIGRATION_0_99_2_to_0_99_3 -ALTER TABLE resource -ADD etag TEXT; --- MIGRATION_0_99_3_to_0_99_4 -ALTER TABLE resource -ADD expires DATETIME; --- MIGRATION_UPDATE_METADATA -UPDATE metadata -SET value = :value -WHERE key = :key diff --git a/man/BFCOption.Rd b/man/BFCOption.Rd deleted file mode 100644 index d9bd1ed..0000000 --- a/man/BFCOption.Rd +++ /dev/null @@ -1,40 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/BFCOption.R -\name{BFCOption} -\alias{BFCOption} -\alias{setBFCOption} -\alias{getBFCOption} -\title{BFCOption -These functions help get and set an R variable CACHE that controls the -default caching location.} -\usage{ -setBFCOption(arg, value) -} -\arguments{ -\item{arg}{character(1) option to get or set} - -\item{value}{The value to be assigned to the designated option} -} -\value{ -Value of request option or invisible successfully set option -} -\description{ -BFCOption -These functions help get and set an R variable CACHE that controls the -default caching location. -} -\details{ -Currently the only supported option is CACHE. This controls the default -location of the BiocFileCache caching directory. By default the value is -established by \code{tools::R_user_dir("BiocFileCache",which="cache")}. This -value can also be defaultly set by using system and global environment -variables visible \emph{before} the package is loaded. The variable that -should be set if utilized is \dQuote{BFC_CACHE} -} -\examples{ -origPath = getBFCOption('CACHE') -\donttest{setBFCOption('CACHE', "~/.myBFC") } -} -\author{ -Lori Shepherd -} diff --git a/man/BiocFileCache-class.Rd b/man/BiocFileCache-class.Rd deleted file mode 100644 index 2806518..0000000 --- a/man/BiocFileCache-class.Rd +++ /dev/null @@ -1,691 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/BiocFileCache-class.R -\name{BiocFileCache-class} -\alias{BiocFileCache-class} -\alias{BiocFileCache} -\alias{bfccache,BiocFileCacheBase-method} -\alias{bfccache} -\alias{bfccache,missing-method} -\alias{length,BiocFileCacheBase-method} -\alias{bfcrid} -\alias{bfcrid,missing-method} -\alias{bfcrid,BiocFileCacheReadOnly-method} -\alias{bfcrid,BiocFileCache-method} -\alias{[,BiocFileCache,character,missing-method} -\alias{[,BiocFileCacheReadOnly,character,missing-method} -\alias{[,BiocFileCache,missing,missing-method} -\alias{[,BiocFileCacheReadOnly,missing,missing-method} -\alias{[[,BiocFileCacheBase,character,missing-method} -\alias{[[<-,BiocFileCache,character,missing,character-method} -\alias{bfcnew,missing-method} -\alias{bfcnew,BiocFileCache-method} -\alias{bfcnew} -\alias{bfcadd,missing-method} -\alias{bfcadd,BiocFileCache-method} -\alias{bfcadd} -\alias{bfcinfo,missing-method} -\alias{bfcinfo,BiocFileCacheBase-method} -\alias{bfcinfo} -\alias{bfcrid,tbl_bfc-method} -\alias{bfcpath,missing-method} -\alias{bfcpath,BiocFileCacheBase-method} -\alias{bfcpath} -\alias{bfcrpath,missing-method} -\alias{bfcrpath,BiocFileCacheBase-method} -\alias{bfcrpath} -\alias{bfcupdate,missing-method} -\alias{bfcupdate,BiocFileCache-method} -\alias{bfcupdate} -\alias{bfcmeta<-} -\alias{bfcmeta<-,BiocFileCacheBase-method} -\alias{bfcmetaremove,missing-method} -\alias{bfcmetaremove,BiocFileCacheBase-method} -\alias{bfcmetaremove} -\alias{bfcmetalist,missing-method} -\alias{bfcmetalist,BiocFileCacheBase-method} -\alias{bfcmetalist} -\alias{bfcmeta,missing-method} -\alias{bfcmeta,BiocFileCacheBase-method} -\alias{bfcmeta} -\alias{bfcquerycols,missing-method} -\alias{bfcquerycols,BiocFileCacheBase-method} -\alias{bfcquerycols} -\alias{bfcquery,missing-method} -\alias{bfcquery,BiocFileCacheBase-method} -\alias{bfcquery} -\alias{bfccount,missing-method} -\alias{bfccount,BiocFileCacheBase-method} -\alias{bfccount} -\alias{bfccount,tbl_bfc-method} -\alias{bfcneedsupdate,missing-method} -\alias{bfcneedsupdate,BiocFileCacheBase-method} -\alias{bfcneedsupdate} -\alias{bfcdownload,missing-method} -\alias{bfcdownload,BiocFileCache-method} -\alias{bfcdownload} -\alias{bfcremove,missing-method} -\alias{bfcremove,BiocFileCache-method} -\alias{bfcremove} -\alias{bfcsync,missing-method} -\alias{bfcsync,BiocFileCache-method} -\alias{bfcsync} -\alias{exportbfc,missing-method} -\alias{exportbfc,BiocFileCacheBase-method} -\alias{exportbfc} -\alias{importbfc,character-method} -\alias{importbfc} -\alias{cleanbfc,missing-method} -\alias{cleanbfc,BiocFileCache-method} -\alias{cleanbfc} -\alias{removebfc,missing-method} -\alias{removebfc,BiocFileCache-method} -\alias{removebfc} -\alias{show,BiocFileCacheBase-method} -\title{BiocFileCache class} -\usage{ -BiocFileCache(cache = getBFCOption("CACHE"), ask = interactive()) - -\S4method{bfccache}{BiocFileCacheBase}(x) - -\S4method{bfccache}{missing}(x) - -\S4method{length}{BiocFileCacheBase}(x) - -bfcrid(x) - -\S4method{bfcrid}{missing}(x) - -\S4method{bfcrid}{BiocFileCacheReadOnly}(x) - -\S4method{bfcrid}{BiocFileCache}(x) - -\S4method{[}{BiocFileCache,character,missing}(x, i, j, ..., drop = TRUE) - -\S4method{[}{BiocFileCacheReadOnly,character,missing}(x, i, j, ..., drop = TRUE) - -\S4method{[}{BiocFileCache,missing,missing}(x, i, j, ..., drop = TRUE) - -\S4method{[}{BiocFileCacheReadOnly,missing,missing}(x, i, j, ..., drop = TRUE) - -\S4method{[[}{BiocFileCacheBase,character,missing}(x, i, j) - -\S4method{[[}{BiocFileCache,character,missing,character}(x, i, j, ...) <- value - -\S4method{bfcnew}{missing}( - x, - rname, - rtype = c("relative", "local"), - ext = NA_character_, - fname = c("unique", "exact") -) - -\S4method{bfcnew}{BiocFileCache}( - x, - rname, - rtype = c("relative", "local"), - ext = NA_character_, - fname = c("unique", "exact") -) - -\S4method{bfcadd}{missing}( - x, - rname, - fpath = rname, - rtype = c("auto", "relative", "local", "web"), - action = c("copy", "move", "asis"), - proxy = "", - download = TRUE, - progress = TRUE, - config = list(), - ext = NA_character_, - fname = c("unique", "exact"), - ... -) - -\S4method{bfcadd}{BiocFileCache}( - x, - rname, - fpath = rname, - rtype = c("auto", "relative", "local", "web"), - action = c("copy", "move", "asis"), - proxy = "", - download = TRUE, - progress = TRUE, - config = list(), - ext = NA_character_, - fname = c("unique", "exact"), - ... -) - -\S4method{bfcinfo}{missing}(x, rids) - -\S4method{bfcinfo}{BiocFileCacheBase}(x, rids) - -\S4method{bfcrid}{tbl_bfc}(x) - -\S4method{bfcpath}{missing}(x, rids) - -\S4method{bfcpath}{BiocFileCacheBase}(x, rids) - -\S4method{bfcrpath}{missing}(x, rnames, ..., rids, exact = TRUE) - -\S4method{bfcrpath}{BiocFileCacheBase}(x, rnames, ..., rids, exact = TRUE) - -\S4method{bfcupdate}{missing}(x, rids, ...) - -\S4method{bfcupdate}{BiocFileCache}( - x, - rids, - ..., - rname = NULL, - rpath = NULL, - fpath = NULL, - proxy = "", - progress = TRUE, - config = list(), - ask = TRUE -) - -bfcmeta(x, name, ...) <- value - -\S4method{bfcmeta}{BiocFileCacheBase}(x, name, ...) <- value - -\S4method{bfcmetaremove}{missing}(x, name, ...) - -\S4method{bfcmetaremove}{BiocFileCacheBase}(x, name, ...) - -\S4method{bfcmetalist}{missing}(x) - -\S4method{bfcmetalist}{BiocFileCacheBase}(x) - -\S4method{bfcmeta}{missing}(x, name, ...) - -\S4method{bfcmeta}{BiocFileCacheBase}(x, name, ...) - -\S4method{bfcquerycols}{missing}(x) - -\S4method{bfcquerycols}{BiocFileCacheBase}(x) - -\S4method{bfcquery}{missing}(x, query, field = c("rname", "rpath", "fpath"), ..., exact = FALSE) - -\S4method{bfcquery}{BiocFileCacheBase}(x, query, field = c("rname", "rpath", "fpath"), ..., exact = FALSE) - -\S4method{bfccount}{missing}(x) - -\S4method{bfccount}{BiocFileCacheBase}(x) - -\S4method{bfccount}{tbl_bfc}(x) - -\S4method{bfcneedsupdate}{missing}(x, rids, ..., proxy = "", config = list()) - -\S4method{bfcneedsupdate}{BiocFileCacheBase}(x, rids, ..., proxy = "", config = list()) - -\S4method{bfcdownload}{missing}( - x, - rid, - proxy = "", - progress = TRUE, - config = list(), - ask = TRUE, - FUN, - ... -) - -\S4method{bfcdownload}{BiocFileCache}( - x, - rid, - proxy = "", - progress = TRUE, - config = list(), - ask = TRUE, - FUN, - ... -) - -\S4method{bfcremove}{missing}(x, rids) - -\S4method{bfcremove}{BiocFileCache}(x, rids) - -\S4method{bfcsync}{missing}(x, verbose = TRUE, ask = TRUE) - -\S4method{bfcsync}{BiocFileCache}(x, verbose = TRUE, ask = TRUE) - -\S4method{exportbfc}{missing}( - x, - rids, - outputFile = "BiocFileCacheExport.tar", - outputMethod = c("tar", "zip"), - verbose = TRUE, - ... -) - -\S4method{exportbfc}{BiocFileCacheBase}( - x, - rids, - outputFile = "BiocFileCacheExport.tar", - outputMethod = c("tar", "zip"), - verbose = TRUE, - ... -) - -\S4method{importbfc}{character}(filename, archiveMethod = c("untar", "unzip"), exdir = ".", ...) - -\S4method{cleanbfc}{missing}(x, days = 120, ask = TRUE) - -\S4method{cleanbfc}{BiocFileCache}(x, days = 120, ask = TRUE) - -\S4method{removebfc}{missing}(x, ask = TRUE) - -\S4method{removebfc}{BiocFileCache}(x, ask = TRUE) - -\S4method{show}{BiocFileCacheBase}(object) -} -\arguments{ -\item{cache}{character(1) On-disk location (directory path) of -cache. For default location see -\code{\link[tools]{R_user_dir}}.} - -\item{ask}{logical(1) Ask before creating, updating, overwriting, -or removing cache or local file locations.} - -\item{x}{A \code{BiocFileCache} instance or, if missing, the result -of \code{BiocFileCache()}.} - -\item{i}{character() 'rid' identifiers.} - -\item{j}{Ignored.} - -\item{...}{For 'bfcadd', 'bfcupdate' and 'bfcdownload': Additional -arguments passed to internal download functions for use with -\code{httr2::req_perform}. For 'bfcrpaths': Additional arguments passed -to 'bfcadd', or \code{exact} passed to 'bfcquery'. For -'bfcquery': Additional arguments passed to \code{grepl}. For -'exportbfc': Additional arguments to the selected outputMethod -function. See \code{utils::tar} or \code{utils::zip} for more -information. For 'importbfc': Additional arguments to the -selected archiveMethod function. See \code{utils::untar} or -\code{utils::unzip} for more information.} - -\item{drop}{Ignored.} - -\item{value}{character(1) Replacement file path.} - -\item{rname}{character(1) Name of object in file cache. For -'bfcupdate' a character vector of replacement rnames.} - -\item{rtype}{character(1) 'local', 'relative', or 'web' indicating -if the resource is a local file, a relative path in the cache, -or a web resource. For \code{bfcnew}: local or relative are -only options. For \code{bfcadd}, the default 'auto' creates -relative or web paths, based on the path prefix.} - -\item{ext}{character(1) A file extension to add to the local -copy of the file (e.g., \sQuote{sqlite}, \sQuote{txt}, -\sQuote{tar.gz}).} - -\item{fname}{character(1). Options are \sQuote{unique} or -\sQuote{exact}. \sQuote{unique} provides each bfc resource with a unique -identifier when storing the file, allowing resources with the same name -to be stored in the cache. \sQuote{exact} uses the exact file name of the -resource; only one of foo/my.txt and bar/my.txt could be stored. Default -is \sQuote{unique}.} - -\item{fpath}{For bfcadd(), character(1) path to current file -location or remote web resource. If none is given, the rname is -assumed to also be the path location. For bfcupdate() -character() vector of replacement web resources.} - -\item{action}{character(1) How to handle the file: create a -\code{copy} of \code{fpath} in the cache directory; \code{move} -the file to the cache directory; or \code{asis} leave the file -in current location but save the path in the cache. If 'rtype -== "relative"', action can not be "asis".} - -\item{proxy}{character(1) (Optional) proxy server passed to -\code{httr2::req_proxy}} - -\item{download}{logical(1) If \code{rtype=web}, should remote -resource be downloaded locally immediately.} - -\item{progress}{TRUE/FALSE if progress bar for downloads in interactive -session should be shown} - -\item{config}{list() passed as argument to \code{httr2::req_options}. The -names of items should be valid curl options as defined in -\code{curl::curl_options}.} - -\item{rids}{character() Vector of rids.} - -\item{rnames}{character() to match against rnames. Each element of -\code{rnames} must match exactly one record. Use \code{exact = -FALSE} to use regular expression matching.} - -\item{exact}{logical(1) when FALSE, treat \code{query} as a regular -expression. When TRUE, use exact matching. For \code{bfcquery}, -the default is \code{FALSE} (regular expression matching; for -\code{bfcrpath}, the default is \code{TRUE} (exact matching).} - -\item{rpath}{character() vector of replacement rpaths.} - -\item{name}{character(1) name of metadata table.} - -\item{query}{character() Regular expression pattern(s) to match in -resource. It will match the pattern against \code{fields}, -using \code{&} logic across query element. By default, case -sensitive. When \code{exact = TRUE}, \code{query} uses exact -matching.} - -\item{field}{character() column names in resource to query, using -\code{||} logic across multiple field elements. By default, -matches pattern agains rname, rpath, and fpath. If exact -matching, may only be a single value.} - -\item{rid}{character(1) Unique resource id.} - -\item{FUN}{A specialized implemented function designed by the user. This -function can be used to perform and save the results of a post download -processing step rather than direct output. The function should ONLY take in -two file names: the first the raw downloaded file and the second the output -file for saved results. The output of the function should be TRUE/FALSE if -step was successful. See vignette section on Specialty Advance Use Case for -more details.} - -\item{verbose}{logical(1) If descriptive message and list of issues -should be included as output.} - -\item{outputFile}{character(1) The /basename for the -output archive. Please include appropriate extension based on -outMethod and any additional parameters selected for -\code{utils::tar} or \code{utils::zip}} - -\item{outputMethod}{Either 'tar' or 'zip' for how the directory -should be archived. Default is 'tar'.} - -\item{filename}{character(1) The name of the archive.} - -\item{archiveMethod}{Either 'untar' or 'unzip' for how the directory should -be extracted. Default is 'untar'.} - -\item{exdir}{Directory to extract files too. See \code{utils::untar} or -\code{utils::unzip} for more details.} - -\item{days}{integer(1) Number of days between accessDate and -currentDate; if exceeded entry will be deleted.} - -\item{object}{A \code{BiocFileCache} instance.} -} -\value{ -For 'BiocFileCache': a \code{BiocFileCache} instance. - -For 'bfccache': character(1) location of the directory - containing the cache. - -For 'length': integer(1) Number of objects in the file - cache. - -For '[': A subset of the BiocFileCache object. - -For '[[': named character(1) rpath for the given resource - in the cache. - -For '[[<-': Updated BiocFileCache, invisibly. - -For 'bfcnew': named character(1), the path to save your - object / file. The name of the return value is the unique rid - for the resource. - -For 'bfcadd': named character(1), the path to save your - object / file. The name of the character is the unique rid for - the resource. - -For 'bfcinfo': A \code{bfc_tbl} of current resources in the - database. - -For 'bfcpath': the file path location to load - -For 'bfcrpath': The local file path location to load. - -For 'bfcupdate': an updated \code{BiocFileCache} object, - invisibly. - -For 'bfcmeta': updated BiocFileCache, invisibly - -For 'bfcmetaremove': updated BiocFileCache, invisibly - -For 'bfcmetalist': returns a character() of all metadata tables - currently in the database. If no metadata tables are available returns - character(0) - -For 'bfcmeta': returns a data.frame representation of database - table - -For 'bfcquerycols': character() all columns in all database tables - available for query. - -For 'bfcquery': A \code{bfc_tbl} of current resources in - the database whose \code{field} contained query. If multiple - values are given, the resource must contain all of the - patterns. A tbl with zero rows is returned when no resources - match the query. - -For 'bfccount': integer(1) Number of objects in the cache - or query. - -For 'bfcneedsupdate': named logical vector if resource - needs to be updated. The name is the resource - 'rid'. \code{TRUE}: fpath \code{etag} or \code{modified} time of - web resource more recent than in BiocFileCache; \code{FALSE}: fpath - \code{etag} or \code{modified} time of web resource not more recent - than in BiocFileCache; \code{NA}: web resource etag and modified time - could not be determined. If the etag is available the function will use - that information definitively and only compare last modified time if - etag is not available. If there is an \code{expires} time that will be - used to initially determine if the resource should be updated. - -For 'bfcdownload': character(1) path to downloaded resource - in cache. - -For 'bfcremove': updated BiocFileCache object, invisibly - -For 'bfcsync': logical(1) indicating whether the cache is - in sync (\code{TRUE}) or not. 'verbose' is TRUE by default, so - descriptive messages will also be included. - -character(1) The outputFile path. - -A BiocFileCache object - -For 'cleanbfc': updated BiocFileCache, invisibly. - -For 'removebfc': TRUE if successfully removed. -} -\description{ -This class represents the location of files stored on disk. Use the -return value to add and retrieve files that persist across -sessions. -} -\details{ -The package defines 'BiocFileCache', 'BiocFileCacheBase' and -'BiocFileCacheReadOnly' classes. - -Slots unique to 'BiocFileCache' and related classes: -\describe{ - \item{'cache': }{character(1) on-disk location (directory path) of the - cache} - \item{'rid': }{character() of unique rids in the cache. } -} - -The cache creates an RSQLite database to keep track of local and remote -resources. Each item located in the database will have the following -information: -\describe{ - \item{'rid': }{resource id. Autogenerated. This is a unique identifier - automatically generated when a resource is added to the cache} - \item{'rname': }{resource name. This is given by the user when a - resource is added to the cache. It does not have to be unique - and can be updated at anytime. We recommend descriptive key - words and identifers.} - \item{'create_time': }{The date and time a resource is added to the cache.} - \item{'access_time': }{The date and time a resource is utilized - within the cache. The access time is updated when the resource - is updated or accessed} - \item{'rpath': }{resource path. This is the path to the local - (on-disk) file} - \item{'rtype': }{resource type. Either "relative", "local", or - "web", indicating if the resource has a remote origin} - \item{'fpath': }{If rtype is "web", this is the link to the - remote resource. It will be utilized to download or update the - remote data} - \item{'last_modified_time': }{For a remote resource, the - last_modified (if available) information for the local copy of - the data. This information is checked against the remote - resource to determine if the local copy is stale and needs to - be updated} -} - -All functions have a quick implementation where if the BiocFileCache object -is not passed as an argument, the function uses default 'BiocFileCache()' for -implementation. e.g 'bfcinfo()' can be used instead of -'bfcinfo(BiocFileCache())'. The only function this is not available for is -'bfcmeta()<-'; The BiocFileCache object must be defined as a varaible and - passed as an argument. See vignette("BiocFileCache") for more details. -} -\section{Methods (by generic)}{ -\itemize{ -\item \code{bfccache(BiocFileCacheBase)}: Get the location of the on-disk cache. - -\item \code{length(BiocFileCacheBase)}: Get the number of objects in the file -cache. - -\item \code{bfcrid(BiocFileCacheReadOnly)}: Get the rids of the object. - -\item \code{x[i}: Subset a BiocFileCache object. - -\item \code{x[[i}: Get a file path for select resources from -the cache. - -\item \code{`[[`(x = BiocFileCache, i = character, j = missing) <- value}: Set the file path of selected resources -from the cache. - -\item \code{bfcnew(BiocFileCache)}: Add a resource to the database - -\item \code{bfcadd(BiocFileCache)}: Add an existing resource to the database - -\item \code{bfcinfo(BiocFileCacheBase)}: list resources in database - -\item \code{bfcrid(tbl_bfc)}: Get the rids of the object - -\item \code{bfcpath(BiocFileCacheBase)}: display rpaths of resource. - -\item \code{bfcrpath(BiocFileCacheBase)}: display rpath of resource. If 'rnames' is -in the cache the path is returned, if it is not it will try to -add it to the cache with 'bfcadd' - -\item \code{bfcupdate(BiocFileCache)}: Update a resource in the cache - -\item \code{bfcmeta(BiocFileCacheBase) <- value}: add meta data table in database - -\item \code{bfcmetaremove(BiocFileCacheBase)}: remove meta data table in database - -\item \code{bfcmetalist(BiocFileCacheBase)}: retrieve listing of metadata tables - -\item \code{bfcmeta(BiocFileCacheBase)}: retrieve metadata table - -\item \code{bfcquerycols(BiocFileCacheBase)}: Get all the possible columns to query - -\item \code{bfcquery(BiocFileCacheBase)}: query resource - -\item \code{bfccount(BiocFileCacheBase)}: Get the number of objects in the file -cache or query. - -\item \code{bfcneedsupdate(BiocFileCacheBase)}: check if a resource needs to be updated - -\item \code{bfcdownload(BiocFileCache)}: Redownload resource to location in cache - -\item \code{bfcremove(BiocFileCache)}: Remove a resource to the database. If -the local file is located in \code{bfccache(x)}, the file will -also be deleted. This will not delete information in any metadata -table. - -\item \code{bfcsync(BiocFileCache)}: sync cache and resource. - -\item \code{exportbfc(BiocFileCacheBase)}: Create exportable file containing -BiocFileCache. - -\item \code{importbfc(character)}: Import file created with exportbfc containing -BiocFileCache. - -\item \code{cleanbfc(BiocFileCache)}: Remove old/unused files in -BiocFileCache. If file to be removed is not in the bfccache -location it will not be deleted. Setting \code{days=-Inf} -will remove all cached files. - -\item \code{removebfc(BiocFileCache)}: Completely remove the BiocFileCache - -\item \code{show(BiocFileCacheBase)}: Display a \code{BiocFileCache} instance. - -}} -\examples{ -# bfc <- BiocFileCache() # global cache -# bfc -bfc0 <- BiocFileCache(tempfile()) # temporary catch for examples -bfccache(bfc0) -length(bfc0) -path <- bfcnew(bfc0, "NewResource") -path -fl1 <- tempfile(); file.create(fl1) -bfcadd(bfc0, "Test1", fl1) # copy -fl2 <- tempfile(); file.create(fl2) -bfcadd(bfc0, "Test2", fl2, action="move") # move -fl3 <- tempfile(); file.create(fl3) -add3 <- bfcadd(bfc0, "Test3", fl3, rtype="local", action="asis") # reference -rid3 <- names(add3) - -bfc0 -file.exists(fl1) # TRUE -file.exists(fl2) # FALSE -file.exists(fl3) # TRUE - -# add a remote resource -url <- "https://httpbin.org/get" -bfcadd(bfc0, "TestWeb", fpath=url) -bfcinfo(bfc0) -bfcpath(bfc0, rid3) -bfcrpath(bfc0, rids = rid3) -bfcupdate(bfc0, rid3, rpath=fl3, rname="NewRname") -bfc0[[rid3]] = fl1 -bfcupdate(bfc0, "BFC5", fpath="http://google.com") -meta = data.frame(list(rid = paste("BFC",seq_len(bfccount(bfc0)), sep=""), - num=seq(bfccount(bfc0),1,-1), - data=c(paste("Letter", - letters[seq_len(bfccount(bfc0))]))), - stringsAsFactors=FALSE) -bfcmeta(bfc0, name="resourcedata") <- meta -\dontrun{bfcmetaremove(bfc0, "resourcedata")} -bfcmetalist(bfc0) -tbl = bfcmeta(bfc0, "resourcedata") -tbl -bfcquerycols(bfc0) -bfcquery(bfc0, "Test") -bfcquery(bfc0, "^Test1$", field="rname") -bfccount(bfc0) -bfccount(bfcquery(bfc0, "test")) -bfcneedsupdate(bfc0, "BFC5") -bfcdownload(bfc0, "BFC5") -bfcremove(bfc0, rid3) -bfcinfo(bfc0) -bfcsync(bfc0) - -if (!interactive()){ - # in interactive mode, in the sync above - # this was probably already removed - # noninteractive mode does not remove resources - # so can remove manually here - bfcremove(bfc0, "BFC1") -} -bfcsync(bfc0, FALSE) -\dontrun{exportbfc(bfc)} -\dontrun{importbfc("ExportBiocFileCache.tar")} -\dontrun{cleanbfc(bfc, ask=FALSE)} -\dontrun{removebfc(bfc, ask=FALSE)} -} diff --git a/man/makeBiocFileCacheFromDataFrame.Rd b/man/makeBiocFileCacheFromDataFrame.Rd deleted file mode 100644 index 5d4ee98..0000000 --- a/man/makeBiocFileCacheFromDataFrame.Rd +++ /dev/null @@ -1,88 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/makeBiocFileCacheFromDataFrame.R -\name{makeBiocFileCacheFromDataFrame} -\alias{makeBiocFileCacheFromDataFrame} -\alias{makeBiocFileCacheFromDataFrame,ANY-method} -\title{Make BiocFileCache objects from an existing data.frame} -\usage{ -makeBiocFileCacheFromDataFrame( - df, - cache, - actionLocal = c("move", "copy", "asis"), - actionWeb = c("move", "copy"), - metadataName, - ..., - ask = TRUE -) - -\S4method{makeBiocFileCacheFromDataFrame}{ANY}( - df, - cache, - actionLocal = c("move", "copy", "asis"), - actionWeb = c("move", "copy"), - metadataName, - ..., - ask = TRUE -) -} -\arguments{ -\item{df}{data.frame or tibble to convert} - -\item{cache}{character(1) On-disk location (directory path) of -cache. For default location see -\code{\link[tools]{R_user_dir}}.} - -\item{actionLocal}{If local copy of file should be moved, copied or -left in original location. See 'action' param of bfcadd.} - -\item{actionWeb}{If a local copy of a remote resource already -exists, should the file be copied or moved to the -cache. Locally downloaded remote resources must exist in the -cache location.} - -\item{metadataName}{If there are additional columns of data in the -original data.frame besides required BiocFileCache columns, -this data will be added as a metadata table with this name.} - -\item{...}{additional arguments passed to `file.copy()`.} - -\item{ask}{logical(1) Confirm creation of BiocFileCache.} -} -\value{ -A BiocFileCache object -} -\description{ -If there are a lot of resources being added this could take some -time but if a cache is saved in a permanent location this should -only have to be run once. The original data.frame must have the -required columns 'rtype', 'fpath', and 'rpath'; See the vignette -for more information on the expected information contained in these -columns. Similarly, the optional columns 'rname', 'etag', -'last_modified_time', and 'expires' may be included. Any additional columns -not listed as required or optional will be kept as an additional -metadata table in the BiocFileCache database. -} -\examples{ -## Create a data.frame with the required columns -tempf <- tempfile(fileext = ".txt") -file.create(tempf) -df <- data.frame( - rtype = "local", - fpath = tempf, - rpath = tempf, - rname = "Example File 1", - etag = "etag1", - last_modified_time = as.character(Sys.Date()), - expires = as.character(Sys.Date() + 1), - stringsAsFactors = FALSE -) -## Create a BiocFileCache from the data.frame -bfc <- makeBiocFileCacheFromDataFrame( - df, cache = tempfile(), actionLocal = "move", - metadataName = "resourceMetadata", ask = FALSE -) -bfc -bfcinfo(bfc) -removebfc(bfc, ask = FALSE) - -} diff --git a/man/makeCachedActiveBinding.Rd b/man/makeCachedActiveBinding.Rd deleted file mode 100644 index 5d31386..0000000 --- a/man/makeCachedActiveBinding.Rd +++ /dev/null @@ -1,30 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/makeCachedActiveBinding.R -\name{makeCachedActiveBinding} -\alias{makeCachedActiveBinding} -\title{makeCachedActiveBinding} -\usage{ -makeCachedActiveBinding(sym, fun, env = .GlobalEnv, verbose = FALSE) -} -\arguments{ -\item{sym}{See \code{\link{makeActiveBinding}} in the \pkg{base} -package.} - -\item{fun}{See \code{\link{makeActiveBinding}} in the \pkg{base} -package.} - -\item{env}{See \code{\link{makeActiveBinding}} in the \pkg{base} -package.} - -\item{verbose}{Set to TRUE to see caching in action (useful for -troubleshooting).} -} -\description{ -Like \code{\link{makeActiveBinding}} but the value of the active -binding gets only evaluated once and is "remembered". -} -\examples{ -makeCachedActiveBinding("x", function() runif(1), verbose=TRUE) -x -x -} diff --git a/tests/testthat.R b/tests/testthat.R deleted file mode 100644 index 189a412..0000000 --- a/tests/testthat.R +++ /dev/null @@ -1,4 +0,0 @@ -library(testthat) -library(BiocFileCache) - -test_check("BiocFileCache") diff --git a/tests/testthat/test_BiocFileCache_class.R b/tests/testthat/test_BiocFileCache_class.R deleted file mode 100644 index 4aac3eb..0000000 --- a/tests/testthat/test_BiocFileCache_class.R +++ /dev/null @@ -1,673 +0,0 @@ -context("BiocFileCache_class") - -test_that("BiocFileCache creation works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - expect_true(file.exists(bfccache(bfc))) - - # test that sql file also gets created - expect_true(file.exists(file.path(bfccache(bfc), "BiocFileCache.sqlite"))) - removebfc(bfc, ask=FALSE) - - fl <- tempfile() - bfc <- BiocFileCache(fl, ask = FALSE) - expect_true(file.exists(fl)) -}) - -test_that("bfcadd and bfcnew works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - fl <- tempfile(); file.create(fl) - expect_identical(length(bfc), 0L) - expect_identical(bfccount(bfcinfo(bfc)), 0L) - - # test file add and copy - rid <- bfcadd(bfc, 'test-1', fl) - expect_identical(length(bfc), 1L) - expect_identical(bfccount(bfcinfo(bfc)), 1L) - expect_true(file.exists(fl)) - # test that fname used unique identifier - expect_false(basename(fl) == basename(rid)) - - # test file add and location not in cache - path <- bfcadd(bfc, 'test-2', fl, rtype='local', action='asis') - rid <- names(path) - expect_identical(length(bfc), 2L) - expect_true(file.exists(fl)) - expect_identical(bfc[[rid]], setNames(fl, rid)) - - # test file add and move - rid <- bfcadd(bfc, 'test-3', fl, action='move') - expect_identical(length(bfc), 3L) - expect_true(!file.exists(fl)) - - # test add web resource - url <- "https://httpbin.org/get" - path <- bfcadd(bfc, 'test-4', url, rtype="web") - rid <- names(path) - expect_identical(length(bfc), 4L) - expect_true(file.exists(bfc[[rid]])) - - # test add new (return path to save) - path <- bfcnew(bfc, 'test-5') - expect_identical(length(bfc), 5L) - expect_identical(bfccount(bfcinfo(bfc)), 5L) - expect_true(!file.exists(path)) - expect_identical(bfc[[names(path)]], path) - - # test out of bounds and file not found - expect_error(bfc[[7]]) - suppressWarnings(expect_error(bfcadd( - bfc, 'test-6', "https://httpbin.org/status/404", rtype="web" - ))) - expect_error(bfcadd(bfc, 'test-2', fl, rtype='local', action='asis')) - - # test no fpath given - url <- "https://httpbin.org/get" - path <- bfcadd(bfc, url) - expect_identical(.sql_get_fpath(bfc,names(path)), - .sql_get_rname(bfc,names(path))) - - # test web resource not download - url <- "https://httpbin.org/get" - path <- bfcadd(bfc, 'test-noDownload', url, rtype="web", download=FALSE) - rid <- names(path) - expect_identical(length(bfc), 7L) - expect_false(file.exists(bfc[[rid]])) - expect_true(is.na(.sql_get_last_modified(bfc, rid))) - - # test relative paths - path <- bfcnew(bfc, "relative-test", "relative") - expect_identical( - .sql_get_rtype(bfc,names(path)), setNames("relative", names(path)) - ) - temp <- file.path(bfccache(bfc), .sql_get_field(bfc,names(path), "rpath")) - expect_identical( - .sql_get_rpath(bfc,names(path)), setNames(temp, names(path)) - ) - basename <- strsplit( - .sql_get_field(bfc, names(path), "rpath"), - split="_" - )[[1]][2] - expect_identical( - .sql_get_fpath(bfc,names(path)), setNames(basename, names(path)) - ) - - - fl <- tempfile(); file.create(fl) - path <- bfcadd(bfc, fl, rtype = "relative") - expect_identical( - .sql_get_rtype(bfc,names(path)), setNames("relative", names(path)) - ) - - temp <- file.path(bfccache(bfc), .sql_get_field(bfc,names(path), "rpath")) - expect_identical( - .sql_get_rpath(bfc,names(path)), setNames(temp, names(path)) - ) - expect_true(file.exists(fl)) - - path <- bfcadd(bfc, fl, rtype = "relative", action="move") - expect_identical( - .sql_get_rtype(bfc,names(path)), setNames("relative", names(path)) - ) - - temp <- file.path(bfccache(bfc), .sql_get_field(bfc,names(path), "rpath")) - expect_identical( - .sql_get_rpath(bfc,names(path)), setNames(temp, names(path)) - ) - expect_true(!file.exists(fl)) - - fl <- tempfile(); file.create(fl) - expect_warning(bfcadd(bfc, fl, rtype = "relative", action="asis")) - - # test fname arguments - fl_exact = tempfile(fileext=".bam"); file.create(fl_exact) - rid <- bfcadd(bfc, fl_exact, fname="exact") - expect_identical(basename(fl_exact), basename(rid)) - rid2 <- bfcadd(bfc, fl_exact, fname="unique") - expect_false(basename(fl_exact) == basename(rid2)) - -}) - -test_that("bfcadd() works for multiple inserts", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - fpath <- replicate(6L, tempfile()) - file.create(fpath) - rname <- letters[seq_along(fpath)] - - rpath <- bfcadd(bfc, rname[1:2], fpath[1:2], action = "asis") - expect_identical(rpath, setNames(fpath[1:2], names(rpath))) - - rpath <- bfcadd(bfc, rname[3], fpath[3], action = "asis") - expect_identical(rpath, setNames(fpath[3], names(rpath))) - - rpath <- bfcadd(bfc, rname[4:5], fpath[4:5]) - expect_identical(names(rpath), paste0("BFC", 4:5)) - expect_true(all(file.exists(rpath))) - - rpath <- bfcadd(bfc, rname[6], fpath[6]) - expect_identical(names(rpath), paste0("BFC", 6)) - expect_true(all(file.exists(rpath))) -}) - -test_that("bfcnew() works for multiple inserts", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - - rnames <- paste0("foo", 1:2) - rpath <- bfcnew(bfc, rnames) - expect_identical(bfcinfo(bfc)$rname, rnames) - - rnames <- "foo3" - rpath <- bfcnew(bfc, rnames, ext=".foo3") - expect_identical(tools::file_ext(rpath), "foo3") - - rnames <- paste0("foo", 4:5) - rpath <- bfcnew(bfc, rnames, ext=".foo4") - expect_identical(tools::file_ext(rpath), rep("foo4", 2)) - - rnames <- paste0("foo", 6:7) - ext <- paste0(".", rnames) - rpath <- bfcnew(bfc, rnames, ext=ext) - expect_identical(tools::file_ext(rpath), rnames) -}) - -# -# construct bfc for further test, avoiding construction in each -# -bfc <- BiocFileCache(tempfile(), ask = FALSE) -fl <- tempfile(); file.create(fl) -add1 <- bfcadd(bfc, 'test-1', fl) -rid1 <- names(add1) -add2 <- bfcadd(bfc, 'test-2', fl, rtype='local', action='asis') -rid2 <- names(add2) -url <- "https://httpbin.org/get" -add3 <- bfcadd(bfc, 'test-3', url, rtype="web") -rid3 <- names(add3) -path <- bfcnew(bfc, 'test-4') -rid4 <- names(path) -url <- "https://httpbin.org/get" -add5 <- bfcadd(bfc, 'test-5', url, rtype="web", download=FALSE) -rid5 <- names(add5) - -test_that("bfcinfo works", { - # print all - expect_identical(dim(as.data.frame(bfcinfo(bfc))), - c(5L, 10L)) - expect_is(bfcinfo(bfc), "tbl_df") - # print subset - expect_identical(dim(as.data.frame(bfcinfo(bfc, paste0("BFC", 1:3)))), - c(3L, 10L)) - # print one found and one not found - expect_error(bfcinfo(bfc, c(1, 6))) - - # index not found - expect_error(bfcinfo(bfc, 6)) - - # check rpaths updated - expect_identical(bfcinfo(bfc)[["rpath"]], unname(bfcrpath(bfc))) -}) - -test_that("bfcpath and bfcrpath works", { - # local file - expect_identical(length(bfcpath(bfc, rid1)), 1L) - expect_identical(names(bfcpath(bfc, rid1)), as.character(rid1)) - expect_identical(bfcpath(bfc, rid1), bfcrpath(bfc, rids=rid1)) - - # web file - expect_identical(length(bfcpath(bfc, rid3)), 1L) - expect_identical(names(bfcpath(bfc, rid3)), as.character(rid3)) - expect_identical(bfcpath(bfc, rid3), bfcrpath(bfc, rids=rid3)) - - # index not found - expect_error(bfcpath(bfc, 6)) - expect_error(bfcrpath(bfc, rids=6)) - - # expect error - expect_error(bfcrpath(bfc, rnames="testweb", rids="BFC5")) - - # multiple files - expect_identical(length(bfcrpath(bfc, rids=paste0("BFC", 1:3))), 3L) - expect_identical(length(bfcrpath(bfc)), 5L) - expect_identical(length(bfcpath(bfc)), length(bfc)) - expect_identical(length(bfcpath(bfc, rids=paste0("BFC", 1:3))), 3L) - expect_identical(length(bfcpath(bfc)), length(bfcrpath(bfc))) - - # test bfcrpath with rname - expect_identical(length(bfcrpath(bfc, c("test-1", "test-3"))), 2L) - suppressWarnings(expect_error(bfcrpath(bfc, "test"))) - url = "https://en.wikipedia.org/wiki/Bioconductor" - suppressWarnings(expect_error(bfcrpath(bfc, c("test-1",url, "notworking")))) - expect_identical(length(bfcrid(bfc)), 5L) - expect_identical(length(bfcrpath(bfc, c("test-1", url, "test-3"))), 3L) - expect_identical(length(bfcrid(bfc)), 6L) - expect_identical(bfccount(bfcinfo(bfc)), 6L) - expect_identical(unname(.sql_get_field(bfc, "BFC7", "rname")), url) - expect_identical(unname(.sql_get_fpath(bfc, "BFC7")), url) -}) - -test_that("bfcquery, bfcrpath allow regular expressions and exact matches", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - file.create(fl <- tempfile()) - fl1 <- bfcadd(bfc, "fl1", fl) - fl10 <- bfcadd(bfc, "fl10", fl) - ## bfcquery - expect_identical(NROW(bfcquery(bfc, "fl1", "rname")), 2L) - expect_identical(NROW(bfcquery(bfc, "fl1", "rname", exact = TRUE)), 1L) - expect_identical(NROW(bfcquery(bfc, "fl", "rname", exact = TRUE)), 0L) - ## bfcrpath - expect_error( - suppressWarnings(bfcrpath(bfc, "fl1", exact = FALSE)), - "not all 'rnames' found or unique." - ) - expect_identical(bfcrpath(bfc, "fl1", exact = TRUE), fl1) - expect_identical(bfcrpath(bfc, "fl1$", exact = FALSE), fl1) -}) - -test_that("check_rtype works", { - fun <- .util_standardize_rtype_helper - - # test web types - expect_identical(fun("auto", "http://somepath.com"), "web") - expect_identical(fun("auto", "ftp://somepath.com"), "web") - expect_identical(fun("local", "https://some.path", "web"), "local") - expect_identical(fun("relative", "https://some.path", "web"), "relative") - - # test not web type - expect_identical(fun("auto", "not/a/web/path", "copy"), "relative") - expect_identical(fun("auto", "not/a/web/path", "move"), "relative") - expect_identical(fun("auto", "not/a/web/path", "asis"), "local") - - # expect noopt - expect_identical(fun("local", "some/path", "copy"), "local") - expect_identical(fun("local", "some/path", "move"), "local") - expect_identical(fun("local", "some/path", "asis"), "local") - - expect_identical(fun("relative", "some/path", "copy"), "relative") - expect_identical(fun("relative", "some/path", "move"), "relative") - expect_warning(fun("relative", "some/path", "asis")) - suppressWarnings({ - expect_identical(fun("relative", "some/path", "asis"), "local") - }) -}) - -test_that("subsetting works", { - # out of bounds - expect_error(bfc[3:5]) - expect_error(bfc[10]) - - # empty - bfcsub3 <- bfc[] - expect_identical(length(bfcsub3), length(bfc)) - subin <- as.data.frame( - bfcinfo(bfcsub3)[,-which(names(bfcinfo(bfcsub3)) == "access_time")]) - bfcin <- as.data.frame( - bfcinfo(bfc)[,-which(names(bfcinfo(bfc)) == "access_time")]) - expect_identical(subin, bfcin) - - # test restricted methods on subset - expect_error(bfcnew(bfcsub3)) - expect_error(bfcadd(bfcsub3)) - expect_error(bfcupdate(bfcsub3, rname="test")) - fltemp <- tempfile(); file.create(fltemp) - expect_error(bfcsub3[[2]] <- fltemp) -}) - -test_that("bfcupdate works", { - # test [[<-, only updates rpath - fl2 <- tempfile(); file.create(fl2) - bfc[[rid2]] <- fl2 - expect_identical(unname(bfcpath(bfc, rid2)), fl2) - expect_error(bfc[[rid1]] <- "A/file/doesnt/work") - - # test errors, files not found - expect_error(bfcupdate(bfc, rid2, fpath="rid2/local/notweb", ask=FALSE)) - suppressWarnings(expect_error(bfcupdate( - bfc, rid3, fpath="https://httpbin.org/status/404", ask=FALSE - ))) - expect_error(bfcupdate(bfc, rid2, rpath="path/not/valid", ask=FALSE)) - - # test update fpath and rname - link = "https://en.wikipedia.org/wiki/Bioconductor" - suppressWarnings(bfcupdate( - bfc, rid3, fpath=link, rname="prepQuery", ask=FALSE - )) - vl <- as.character(unname(as.data.frame( - bfcinfo(bfc,rid3))[c("rname", "fpath")])) - expect_identical(vl, c("prepQuery", link)) - time <- as.data.frame(bfcinfo(bfc,rid3))$last_modified_time - expect_identical(time, - .httr_get_cache_info(link)[["modified"]]) - - # test rpath update and give second query example - suppressWarnings(bfcupdate(bfc, rid1, rpath=fl2, rname="prepQuery2")) - expect_identical(unname(bfcpath(bfc, rid1)), fl2) - - # test error - expect_error(bfcupdate(bfc, c(rid2, rid1), rname="oneName")) - expect_error(bfcupdate(bfc, 1:7)) -}) - -test_that("bfcmeta works", { - meta <- data.frame( - rid=paste("BFC", seq_len(bfccount(bfc)), sep=""), - num=seq(bfccount(bfc), 1, -1), - data=c(paste("Letter", letters[seq_len(bfccount(bfc))])), - stringsAsFactors=FALSE - ) - - # test no meta - expect_identical(bfcmetalist(bfc), character(0)) - expect_identical(names(bfcinfo(bfc)),bfcquerycols(bfc)) - - # try add meta with bad rid - expect_error(bfcmeta(bfc, name="resourcedata") <- meta) - # add valid - meta$rid[6] = "BFC7" - metaOrig = meta - bfcmeta(bfc, name="resourcedata") <- meta - expect_identical(bfcmetalist(bfc),"resourcedata") - expect_true("resourcedata" %in% bfcmetalist(bfc)) - - # add additional - bfcmeta(bfc, name="table2") <- meta - expect_identical(length(bfcmetalist(bfc)), 2L) - expect_true("table2" %in% bfcmetalist(bfc)) - - # try and add same table name - meta$num = seq(1, bfccount(bfc), 1) - expect_error(bfcmeta(bfc, name="table2") <- meta) - bfcmeta(bfc, name="table2", overwrite=TRUE) <- meta - expect_identical(length(bfcmetalist(bfc)), 2L) - - # try and add reserved table name - expect_error(bfcmeta(bfc, name="metadata") <- meta) - - # try and add with reserved col name - names(meta)[2] = "rpath" - expect_error(bfcmeta(bfc, name="table3") <- meta) - - # try add meta with missing column rid - names(meta)[1:2] = c("id", "num") - expect_error(bfcmeta(bfc, name="table3") <- meta) - - # remove table - bfcmetaremove(bfc, "table2") - expect_identical(length(bfcmetalist(bfc)), 1L) - expect_true(!("table2" %in% bfcmetalist(bfc))) - - # try and remove reserved table - expect_error(bfcmetaremove(bfc, "metadata")) - - # retrieve table - metaGet <- bfcmeta(bfc, "resourcedata") - expect_true(all(metaGet == metaOrig)) - - # retrieve bad table - expect_error(bfcmeta(bfc, "table2")) - - # querycols should include meta columns - expect_true(all(names(metaOrig) %in% bfcquerycols(bfc))) - expect_identical(names(bfcinfo(bfc)),bfcquerycols(bfc)) - -}) - -test_that("bfcquery and bfccount works", { - - # test count - expect_identical(bfccount(bfc), bfccount(bfcinfo(bfc))) - expect_identical(bfccount(bfc), length(bfc)) - - # query found - q1 <- as.data.frame(bfcquery(bfc, "prep")) - expect_identical(dim(q1)[1], 2L) - expect_identical(q1$rid, c(rid1,rid3)) - - # test query on fpath - q2 <- as.data.frame(bfcquery(bfc, "wiki")) - expect_identical(dim(q2)[1], 2L) - q2b <- as.data.frame(bfcquery(bfc, "wiki", field="fpath")) - q2 <- q2[,-which(names(q2) == "access_time")] - q2b <- q2b[,-which(names(q2b) == "access_time")] - expect_true(all(q2 == q2b, na.rm=TRUE)) - - # query not found - expect_identical(bfccount(bfcquery(bfc, "nothere")), 0L) - - # multiple value all found - path <- file.path(bfccache(bfc), "myFile") - file.create(path) - bfc[[rid2]] <- path - q3 <- as.data.frame(bfcquery(bfc, c("test-2", "myF"))) - expect_identical(dim(q3)[1], 1L) - expect_identical(q3$rid, rid2) - - # multi value some not found - expect_identical(bfccount(bfcquery(bfc, c("prep", "not"))), 0L) - - # test case sensitive - q3 <- as.data.frame(bfcquery(bfc, c("test-2", "myf"))) - expect_identical(dim(q3)[1], 0L) - q3 <- as.data.frame(bfcquery(bfc, c("test-2", "myf"), ignore.case=TRUE)) - expect_identical(dim(q3)[1], 1L) - - # test exact - q4 <- as.data.frame(bfcquery(bfc, "^test-4$")) - expect_identical(dim(q4)[1], 1L) - -}) - -test_that("bfcneedsupdate works", { - # test not web source - expect_error(bfcneedsupdate(bfc, rid4)) - # test out of bounds - expect_error(bfcneedsupdate(bfc, 7)) - - # test expires and last modified not available - link = "https://httpbin.org/get" - bfcupdate(bfc, rid3, fpath=link, ask=FALSE) - expect_true(is.na(bfcneedsupdate(bfc, rid3))) - expect_true(is.na(as.data.frame(bfcinfo(bfc,rid3))$last_modified_time)) - expect_true(is.na(as.data.frame(bfcinfo(bfc,rid3))$expires)) - - # remove those that aren't web - expect_identical( - length(bfcneedsupdate(bfc)), - length(.get_all_web_rids(bfc)) - ) - expect_identical( - names(bfcneedsupdate(bfc)), - as.character(.get_all_web_rids(bfc)) - ) - - # test non downloaded is TRUE - expect_true(bfcneedsupdate(bfc, rid5)) - - # test etag available and check order - link = "https://www.wikipedia.org/" - bfcupdate(bfc, rid3, fpath=link, ask=FALSE) - cache_info <- .httr_get_cache_info(link) - expect_identical(as.data.frame(bfcinfo(bfc,rid3))$last_modified_time, - cache_info[["modified"]]) - expect_identical(as.data.frame(bfcinfo(bfc,rid3))$etag, - cache_info[["etag"]]) - expect_true(!is.na(bfcneedsupdate(bfc, rid3))) - expect_true(!is.na(as.data.frame(bfcinfo(bfc,rid3))$etag)) - # wiki has expires so manually set to NA for testing - .sql_set_expires(bfc, rid3, NA_character_) - expect_false(bfcneedsupdate(bfc, rid3)) - .sql_set_etag(bfc, rid3, "somethingElse") - expect_true(bfcneedsupdate(bfc, rid3)) - .sql_set_etag(bfc, rid3, NA_character_) - expect_false(bfcneedsupdate(bfc, rid3)) - .sql_set_last_modified(bfc, rid3, - as.character(as.Date(.sql_get_last_modified(bfc, rid3)) - 1)) - expect_true(bfcneedsupdate(bfc, rid3)) - - # maually test expires - .sql_set_expires(bfc, rid3, as.character(as.Date(Sys.time()) + 2)) - .sql_set_etag(bfc, rid3, NA_character_) - .sql_set_last_modified(bfc, rid3,NA_character_) - expect_true(is.na(bfcneedsupdate(bfc, rid3))) - .sql_set_expires(bfc, rid3, as.character(as.Date(Sys.time()) -1)) - expect_true(bfcneedsupdate(bfc, rid3)) -}) - -test_that("bfcdownload works", { - response <- .biocfilecache_flags$set_ask_response(FALSE) - - time1 <- file.info(.sql_get_rpath(bfc, rid3))[["ctime"]] - temp <- bfcdownload(bfc, rid3, ask=TRUE) - time2 <- file.info(.sql_get_rpath(bfc, rid3))[["ctime"]] - expect_identical(time1, time2) - - temp <- bfcdownload(bfc, rid3, ask=FALSE) - time3 <- file.info(.sql_get_rpath(bfc, rid3))[["ctime"]] - expect_true(time1 < time3) - expect_error(bfcdownload(bfc, rid1)) - - url <- "http://bioconductor.org/packages/stats/bioc/BiocFileCache/BiocFileCache_stats.tab" - headFile <- - function(url, file) - { - dat <- readLines(url) - dat <- head(dat, n=3L) - writeLines(dat, file) - TRUE - } - rid <- names(bfcadd(bfc, rname="testFun", fpath=url, download=FALSE)) - temp <- bfcdownload(bfc, rid, FUN=headFile) - file <- readLines(temp) - expect_identical(length(file), 3L) - - expect_error(bfcdownload(bfc, rid, ask=FALSE, FUN=rnorm)) - - .biocfilecache_flags$set_ask_response(response) -}) - -test_that("exportbfc and importbfc works",{ - - bfc <- BiocFileCache(tempfile(), ask = FALSE) - fl <- tempfile(); file.create(fl) - add1 <- bfcadd(bfc, 'relative', fl) - rid1 <- names(add1) - add2 <- bfcadd(bfc, 'local', fl, rtype='local', action='asis') - rid2 <- names(add2) - url <- "https://httpbin.org/get" - add3 <- bfcadd(bfc, 'web', url, rtype="web") - rid3 <- names(add3) - path <- bfcnew(bfc, 'notfound') - rid4 <- names(path) - url <- "https://httpbin.org/get" - add5 <- bfcadd(bfc, 'webno', url, rtype="web", download=FALSE) - rid5 <- names(add5) - - dirloc <- dirname(bfccache(bfc)) - temploc <- file.path(dirloc, "ExportTest") - dir.create(temploc) - ids <- bfcrid(bfc) - res <- vapply(ids, .util_export_file, character(1), - bfc=bfc, dir=temploc) - expect_identical(length(list.files(temploc)), 2L) - expect_identical(unname(res), - c("relative", "local", "relative", NA_character_, "web")) - .util_unlink(temploc, recursive=TRUE) - expect_false(file.exists(file.path(dirloc, "BFCExport.tar"))) - file <- exportbfc(bfc, outputFile=file.path(dirloc, "BFCExport.tar"), - verbose=FALSE) - expect_true(file.exists(file.path(dirloc, "BFCExport.tar"))) - expect_false(dir.exists("BiocFileCacheExport")) - bfc2 <- importbfc(file, exdir=dirloc) - expect_true(dir.exists(file.path(dirloc,"BiocFileCacheExport"))) - expect_identical(bfccount(bfc2), 4L) - locpath <- file.path(dirloc, "BiocFileCacheExport") - expect_true(file.exists(file.path(locpath,"BiocFileCache.sqlite"))) - expect_identical(length(list.files(locpath)), 4L) - sub <- bfc[c(rid1,rid2)] - .util_unlink(locpath, recursive=TRUE) - file.remove(file) - file <- exportbfc(sub, outputFile=file.path(dirloc, "SubExport.zip"), - verbose=FALSE, outputMethod="zip") - expect_true(file.exists(file.path(dirloc, "SubExport.zip"))) - bfc3 <- importbfc(file, exdir=dirloc, archiveMethod="unzip") - expect_identical(bfccount(bfc3), 2L) - .util_unlink(locpath, recursive=TRUE) - file.remove(file) - removebfc(bfc, ask=FALSE) -}) - -test_that("bfcsync and bfcremove works", { - response <- .biocfilecache_flags$set_ask_response(FALSE) - ## setup - bfc2 <- BiocFileCache(tempfile(), ask = FALSE) - fl <- tempfile(); file.create(fl) - add1 <- bfcadd(bfc2, 'test-1', fl) - rid1 <- names(add1) - add2 <- bfcadd(bfc2, 'test-2', fl, rtype='local', action='asis') - rid2 <- names(add2) - url <- "https://httpbin.org/get" - add3 <- bfcadd(bfc2, 'test-3', url, rtype="web") - rid3 <- names(add3) - path <- bfcnew(bfc2, 'test-4') - rid4 <- names(path) - suppressWarnings(bfcupdate(bfc2, rid1, rpath=add3)) - add5 <- bfcnew(bfc2, "test-5", rtype="relative") - rid5 <- names(add5) - add6 <- bfcadd(bfc2, "test-6", fl, rtype="relative") - rid6 <- names(add6) - - # test sync - expect_message(bfcsync(bfc2)) - expect_false(bfcsync(bfc2, FALSE)) - - bfcremove(bfc2, rid4) - bfcremove(bfc2, rid5) - files <- file.path( - bfccache(bfc2), - setdiff(list.files(bfccache(bfc2)), c("BiocFileCache.sqlite", "BiocFileCache.sqlite.LOCK")) - ) - # normalizePath on windows - # can't across platform - no opt on linux but added hidden (private) - # on mac - paths <- .sql_get_rpath(bfc2, bfcrid(bfc2)) - if (tolower(.Platform$OS.type) == "windows"){ - files = normalizePath(files) - paths = normalizePath(paths) - } - untracked <- setdiff(files, paths) - .util_unlink(untracked) - expect_true(bfcsync(bfc2, FALSE)) - - # test that remove, deletes file if in cache - path <- .sql_get_rpath(bfc2, rid3) - expect_true(file.exists(path)) - bfcremove(bfc2, rid3) - expect_false(file.exists(path)) - - # test remove leaves file if not in cache - path <- .sql_get_rpath(bfc2, rid2) - expect_true(file.exists(path)) - bfcremove(bfc2, rid2) - expect_true(file.exists(path)) - - .biocfilecache_flags$set_ask_response(response) -}) - -test_that("cleanbfc works", { - # can't test functiuon but test helper - expect_true(length(.sql_clean_cache(bfc, 1)) == 0L) - - # manually change access_time so longer than a day - sql<- "UPDATE resource SET access_time = '2016-01-01' WHERE rid = :rid" - .sql_db_execute(bfc, sql, rid = rid1) - expect_identical(.sql_clean_cache(bfc, 1), rid1) - - ## bfclean() works on an empty cache - bfc <- BiocFileCache(tempfile(), ask = FALSE) - expect_identical(character(0), .sql_clean_cache(bfc, 1L)) -}) - -test_that("removebfc works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - path <- bfccache(bfc) - expect_true(file.exists(path)) - expect_true(removebfc(bfc, ask=FALSE)) - expect_false(file.exists(path)) -}) diff --git a/tests/testthat/test_httr.R b/tests/testthat/test_httr.R deleted file mode 100644 index e5d1954..0000000 --- a/tests/testthat/test_httr.R +++ /dev/null @@ -1,29 +0,0 @@ -context("httr2") - -test_that("internal .httr_get_cache_info works", { - - # example neither - url <- "https://httpbin.org/get" - info <- .httr_get_cache_info(url) - expect_true(all(is.na(info))) - expect_identical(length(info), 3L) - expect_identical(names(info), c("etag", "modified", "expires")) - - # example both - url <- "https://www.wikipedia.org/" - info <- .httr_get_cache_info(url) - expect_true(all(!is.na(info))) - expect_identical(length(info), 3L) - expect_identical(names(info), c("etag", "modified", "expires")) - - # example only time - url <- "https://en.wikipedia.org/wiki/Bioconductor" - info <- .httr_get_cache_info(url) - expect_true(is.na(info[["etag"]])) - expect_true(!is.na(info[["modified"]])) - expect_true(!is.na(info[["expires"]])) - expect_identical(length(info), 3L) - expect_identical(names(info), c("etag", "modified", "expires")) - # more tests in bfcneedsupdate - -}) diff --git a/tests/testthat/test_makeBiocFileCacheFromDataFrame.R b/tests/testthat/test_makeBiocFileCacheFromDataFrame.R deleted file mode 100644 index 461cc75..0000000 --- a/tests/testthat/test_makeBiocFileCacheFromDataFrame.R +++ /dev/null @@ -1,112 +0,0 @@ -context("makeBiocFileCacheFromDataFrame") - -test_that("makeBiocFileCacheFromDataFrame works",{ - - bfc2 <- BiocFileCache(tempfile(), ask = FALSE) - fl <- tempfile(); file.create(fl) - add1 <- bfcadd(bfc2, 'relative', fl) - add2 <- bfcadd(bfc2, 'local', fl, rtype='local', action='asis') - url <- "https://httpbin.org/get" - add3 <- bfcadd(bfc2, 'noDown', url, rtype="web", download=FALSE) - url <- "https://www.wikipedia.org/" - add4 <- bfcadd(bfc2, 'web', url, rtype="web") - fl <- tempfile(); file.create(fl) - add5 <- bfcadd(bfc2, 'localnoexist', fl, rtype='local', action='asis') - file.remove(fl) - - temp = bfcinfo(bfc2) - - # error directory already exists - expect_error(makeBiocFileCacheFromDataFrame( - temp, cache=bfccache(bfc2), actionLocal="copy", actionWeb="copy", - metadataName="resourceMetadata", ask = FALSE - ), "!dir.exists\\(cache\\) is not TRUE") - - newcache <- file.path(dirname(bfccache(bfc2)), "testNEW") - - # error reserved column names - expect_error(makeBiocFileCacheFromDataFrame( - temp, cache=newcache, actionLocal="copy", actionWeb="copy", ask = FALSE - ), "The following are reserved column names:.*") - - names(temp)[1] = "origID" - names(temp)[3] = "origTimeC" - names(temp)[4] = "origTimeA" - - # expect error metadataName missing without default - expect_error(makeBiocFileCacheFromDataFrame( - temp, cache=newcache, actionLocal="copy", actionWeb="copy", ask = FALSE - ), "!missing\\(metadataName\\) is not TRUE") - - - # error relative path - expect_error(makeBiocFileCacheFromDataFrame( - temp, cache=newcache, actionLocal="copy", actionWeb="copy", - metadataName="resourceMetadata", ask = FALSE - )) - - temp= temp[which(temp$rtype != "relative"),] - - # error local file doesn't exist - expect_error(makeBiocFileCacheFromDataFrame( - temp,cache=newcache, actionLocal="copy", actionWeb="copy", - metadataName="resourceMetadata", ask = FALSE - )) - - temp = temp[-which(temp$origID == names(add5)),] - temp$rpath = unname(bfcrpath(bfc2, - rids=as.character(temp$origID))) - - removebfc(bfc2, ask=FALSE) - newbfc <- makeBiocFileCacheFromDataFrame( - temp, cache=newcache, actionLocal="copy", actionWeb="copy", - metadataName="resourceMetadata", ask = FALSE - ) - - expect_identical(length(newbfc), 3L) - expect_identical(length(.get_all_web_rids(newbfc)), 2L) - expect_identical(length(.get_nonrelative_ids(newbfc)), 0L) - # neither web file will be found, only local and sqlite - expect_identical(length(list.files(bfccache(newbfc))), 2L) - expect_identical(ncol(bfcinfo(newbfc)), 13L) - expect_identical(length(bfcmetalist(newbfc)), 1L) - expect_identical(bfcinfo(newbfc)$origID, temp$origID) - expect_identical(bfcinfo(newbfc)$etag, temp$etag) - expect_identical(bfcinfo(newbfc)$fpath, temp$fpath) - expect_true(all(bfcinfo(newbfc)$rpath != temp$rpath)) - - - removebfc(newbfc, ask=FALSE) - names(temp)[2] = "origRname" - names(temp)[8] = "origlmt" - names(temp)[9] = "origetag" - newbfc <- makeBiocFileCacheFromDataFrame( - temp,cache=newcache, actionLocal="copy", actionWeb="copy", - metadataName="resourceMetadata", ask = FALSE - ) - expect_identical(ncol(bfcinfo(newbfc)), 16L) - - removebfc(newbfc, ask=FALSE) - # fail because required not available - names(temp)[5] = "origrpath" - expect_error(makeBiocFileCacheFromDataFrame( - temp, cache=newcache, actionLocal="copy", actionWeb="copy", ask = FALSE - )) - names(temp)[5] = "rpath" - names(temp)[6] = "origrtype" - expect_error(makeBiocFileCacheFromDataFrame(temp,cache=newcache, - actionLocal="copy", actionWeb="copy")) - names(temp)[6] = "rtype" - names(temp)[7] = "origfpath" - expect_error(makeBiocFileCacheFromDataFrame( - temp, cache=newcache, actionLocal="copy", actionWeb="copy", ask = FALSE - )) - names(temp)[7] = "fpath" - temp <- temp[,c("fpath","rpath","rtype")] - newbfc <- makeBiocFileCacheFromDataFrame( - temp, cache=newcache, actionLocal="copy", actionWeb="copy", ask = FALSE - ) - expect_identical(ncol(bfcinfo(newbfc)), 10L) - expect_identical(length(bfcmetalist(newbfc)), 0L) - removebfc(newbfc, ask=FALSE) -}) diff --git a/tests/testthat/test_sql.R b/tests/testthat/test_sql.R deleted file mode 100644 index 905cc0f..0000000 --- a/tests/testthat/test_sql.R +++ /dev/null @@ -1,140 +0,0 @@ -context("sql") - -test_that("schema versioning works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - expect_identical(.sql_schema_version(bfc), .CURRENT_SCHEMA_VERSION) - expect_identical(.sql_validate_version(bfc), .CURRENT_SCHEMA_VERSION) - - .sql_migration_update_schema_version(bfc, "0.99.1") - expect_identical(.sql_schema_version(bfc), "0.99.1") - - .sql_migration_update_schema_version(bfc, "0.0.1") - expect_error(.sql_validate_version(bfc), "unsupported schema version") -}) - -test_that(".sql_add_resource() works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - expect_identical(.sql_get_nrows(bfcinfo(bfc)), 0L) - - rpath <- .sql_add_resource(bfc, "foo1", "rtype", "fpath", NA) - expect_identical(names(rpath), "BFC1" ) - - rpath <- .sql_add_resource(bfc, c("foo2", "foo3"), "rtype", "fpath", NA) - expect_identical(names(rpath), c("BFC2", "BFC3")) - - .sql_remove_resource(bfc, "BFC3") - rpath <- .sql_add_resource(bfc, "foo4", "rtype", "fpath", NA) - expect_identical(names(rpath), "BFC4") -}) - -test_that(".sql_add_resource(ext=.) works", { - getext <- function(rpath) { - ext <- tools::file_ext(rpath) - ext[nzchar(ext)] <- sprintf(".%s", ext)[nzchar(ext)] - ext - } - - bfc <- BiocFileCache(tempfile(), ask = FALSE) - - ext <- "" - rpath <- .sql_add_resource(bfc, "foo1", "rtype", "fpath") - expect_identical(getext(rpath), ext) - - ext <- ".ext2" - rpath <- .sql_add_resource(bfc, "foo2", "rtype", "fpath", ext) - expect_identical(getext(rpath), ext) - - ext <- ".ext3" - rpath <- .sql_add_resource(bfc, c("foo3", "foo4"), "rtype", "fpath", ext) - expect_identical(getext(rpath), c(ext, ext)) - - ext <- c(".ext5", ".ext6") - rpath <- .sql_add_resource(bfc, c("foo5", "foo6"), "rtype", "fpath", ext) - expect_identical(getext(rpath), ext) -}) - -test_that(".sql_add_resource() sets last_modified_time to NA", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - - rid <- names(.sql_add_resource(bfc, "foo1", "rtype", "fpath")) - expected <- setNames(NA_real_, "BFC1") - expect_identical(.sql_get_last_modified(bfc, rid), expected) - expected <- setNames(NA_character_, "BFC1") - expect_identical(.sql_get_etag(bfc, rid), expected) -}) - -test_that(".sql_remove_resource() works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - expect_identical(.sql_remove_resource(bfc, "BFC1"), 0L) - - rpath <- .sql_add_resource(bfc, paste0("foo", 1:4), "rtype", "fpath", NA) - expect_identical(.sql_remove_resource(bfc, "BFC1"), 1L) - expect_identical(.sql_remove_resource(bfc, paste0("BFC", c(2, 4))), 2L) - expect_identical(bfccount(bfc), 1L) -}) - -test_that(".sql_get_field() works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - - rname <- "foo1" - rid <- names(.sql_add_resource(bfc, rname, "local", "fpath")) - expect_identical(.sql_get_field(bfc, rid, "rname"), setNames(rname, rid)) - - rname <- c("foo2", "foo3") - rid <- names(.sql_add_resource(bfc, rname, "local", "fpath")) - expect_identical(.sql_get_field(bfc, rid, "rname"), setNames(rname, rid)) -}) - -test_that(".sql_set_rpath() works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - rid <- names(.sql_add_resource(bfc, paste0("foo", 1:3), "local", "fpath")) - - rpath <- "bar1" - .sql_set_rpath(bfc, rid[1], rpath) - expect_identical(.sql_get_rpath(bfc, rid[1]), setNames(rpath, rid[1])) - - rpath <- paste0("bar", 2:3) - .sql_set_rpath(bfc, rid[2:3], rpath) - expect_identical(.sql_get_rpath(bfc, rid[2:3]), setNames(rpath, rid[2:3])) -}) - -test_that(".sql_get_rpath() works", { - bfc <- BiocFileCache(tempfile(), ask = FALSE) - - fpath <- "fpath" - rid <- names(.sql_add_resource(bfc, "foo1", "local", fpath)) - .sql_set_rpath(bfc, rid, fpath) - expect_identical(.sql_get_rpath(bfc, rid), setNames(fpath, rid)) - - rid <- names(.sql_add_resource(bfc, "foo2", "relative", fpath)) - .sql_set_rpath(bfc, rid, fpath) - expected <- setNames(file.path(bfccache(bfc), fpath), rid) - expect_identical(.sql_get_rpath(bfc, rid), expected) - - rid <- names(.sql_add_resource(bfc, "foo3", "web", fpath)) - .sql_set_rpath(bfc, rid, fpath) - expected <- setNames(file.path(bfccache(bfc), fpath), rid) - expect_identical(.sql_get_rpath(bfc, rid), expected) - - rid <- paste0("BFC", 1:3) - expected <- setNames(c(fpath, expected, expected), rid) - expect_identical(.sql_get_rpath(bfc, rid), expected) -}) - -test_that(".sql_add_resource() changes remote special", { - - url = - "https://bir190004-bucket01.mghp.osn.xsede.org/AnnotationHub/ncbi/uniprot/3.7/org.'Caballeronia_concitans'.eg.sqlite" - bfc <- BiocFileCache(tempfile(), ask = FALSE) - rpath <- path.expand(tempfile("", bfccache(bfc))) - ext <- "" - bfname <- basename(url) - bfname <- curl::curl_escape(bfname) - rpath <- sprintf("%s_%s%s", rpath, bfname, ext) - id1 <- bfcadd(bfc, url) - expect_identical(unname(.sql_get_rname(bfc, names(id1))), url) - expect_identical(unname(.sql_get_fpath(bfc, names(id1))), url) - # can't do identical because different random identifier - expect_true(grepl(bfname, basename(unname(.sql_get_rpath(bfc, names(id1)))))) - -}) diff --git a/tests/testthat/test_sql_migration.R b/tests/testthat/test_sql_migration.R deleted file mode 100644 index 627f555..0000000 --- a/tests/testthat/test_sql_migration.R +++ /dev/null @@ -1,3 +0,0 @@ -context("sql_migration") - -## TODO: migration tests diff --git a/tests/testthat/test_utility.R b/tests/testthat/test_utility.R deleted file mode 100644 index dcfff82..0000000 --- a/tests/testthat/test_utility.R +++ /dev/null @@ -1,6 +0,0 @@ -context("utility") - -test_that("utility works", { - response <- .util_ask("", .interactive = FALSE) - expect_identical(response, FALSE) -}) diff --git a/vignettes/BiocFileCache.Rmd b/vignettes/BiocFileCache.Rmd deleted file mode 100644 index 3973e69..0000000 --- a/vignettes/BiocFileCache.Rmd +++ /dev/null @@ -1,722 +0,0 @@ ---- -title: "BiocFileCache: Managing File Resources Across Sessions" -author: Lori Shepherd -output: - BiocStyle::html_document: - toc: true - toc_depth: 2 -vignette: > - %\VignetteEngine{knitr::rmarkdown} - %\VignetteIndexEntry{1. BiocFileCache Overview: Managing File Resources Across Sessions} - %\VignetteEncoding{UTF-8} - %\VignetteDepends{rtracklayer} ---- - -```{r setup, echo=FALSE} -knitr::opts_chunk$set(collapse=TRUE) -``` - -# Overview - -Organization of files on a local machine can be cumbersome. This is especially -true for local copies of remote resources that may periodically require a new -download to have the most updated information available. [BiocFileCache][] is -designed to help manage local and remote resource files stored locally. It -provides a convenient location to organize files and once added to the cache -management, the package provides functions to determine if remote resources are -out of date and require a new download. - -## Installation and Loading - -`BiocFileCache` is a _Bioconductor_ package and can be installed through -`BiocManager::install()`. - -```{r, eval = FALSE} -if (!"BiocManager" %in% rownames(installed.packages())) - install.packages("BiocManager") -BiocManager::install("BiocFileCache", dependencies=TRUE) -``` - -After the package is installed, it can be loaded into _R_ workspace by - -```{r, library, results='hide', warning=FALSE, message=FALSE} -library(BiocFileCache) -``` - -## Creating / Loading the Cache - -The initial step to utilizing [BiocFileCache][] in managing files is to create a -cache object specifying a location. We will create a temporary directory for use -with examples in this vignette. If a path is not specified upon creation, the -default location is a directory `~/.BiocFileCache` in the typical user cache -directory as defined by `tools::R_user_dir("", which="cache")`. - -```{r, create} -path <- tempfile() -bfc <- BiocFileCache(path, ask = FALSE) -``` - -If the path location exists and has been utilized to store files previously, the -previous object will be loaded with any files saved to the cache. If the path -location does not exist the user will be prompted to create the new directory. -If the session is not interactive to promt the user or the user decides not to -create the directory a temporary directory will be used. - -Some utility functions to examine the cache are: - - * `bfccache(bfc)` - * `length(bfc)` - * `show(bfc)` - * `bfcinfo(bfc)` - -`bfccache()` will show the cache path. **NOTE**: Because we are using temporary -directories, your path location will be different than shown. - -```{r, cacheloc} -bfccache(bfc) -length(bfc) -``` - -`length()` on a BiocFileCache will show the number of files currently being -tracked by the `BiocFileCache`. For more detailed information on what is store -in the `BiocFileCache` object, there is a show method which will display the -object, object class, cache path, and number of items currently being tracked. - -```{r, bfcshow} -bfc -``` - -`bfcinfo()` will list a table of `BiocFileCache` resource files being tracked in -the cache. It returns a [dplyr][] object of class `tbl_sqlite`. - -```{r, bfcinfo} -bfcinfo(bfc) -``` - -The table of resource files includes the following information: - - * `rid`: resource id. Autogenerated. This is a unique identifier automatically - generated when a resource is added to the cache. - * `rname`: resource name. This is given by the user when a resource is added to - the cache. It does not have to be unique and can be updated at anytime. We - recommend descriptive key words and identifiers. - * `create_time`: The date and time a resource is added to the cache. - * `access_time`: The date and time a resource is utilized within the cache. The - access time is updated when the resource is updated or downloaded. - * `rpath`: resource path. This is the path to the local file. - * `rtype`: resource type. Either "local" or "web", indicating if the resource - has a remote origin. - * `fpath`: If rtype is "web", this is the link to the remote resource. It will - be utilized to download the remote data. - * `last_modified_time`: For a remote resource, the last_modified (if available) - information for the local copy of the data. This information is checked - against the remote resource to determine if the local copy is stale and needs - to be updated. If it is not available or your resource is not a remote - resource, the last modified time will be marked as NA. - * `etag`: For a remote resource, the etag (if available) information for the - local copy of the data. This information is checked against the remote - resource to determine if the local copy is stale and needs to be updated. If - it is not available or your resource is not a remote resource, the etag will - be marked as NA. - * `expires`: For a remote resource, the expires (if available) information for - the local copy of the data. This information is checked against the - `Sys.time` to determine if the local copy needs to be updated. If it is not - available or your resource is not a remote resource, the expires will be - marked as NA. - -Now that we have created the cache object and location, let's explore adding -files that the cache will manage! - -## Adding / Tracking Resources - -Now that a `BiocFileCache` object and cache location has been created, files can -be added to the cache for tracking. There are two functions to add a resource to -the cache: - - * `bfcnew()` - * `bfcadd()` - -The difference between the options: `bfcnew()` creates an entry for a resource -and returns a filepath to save to. As there are many types of data that can be -saved in many different ways, `bfcnew()` allows you to save any _R_ data object -in the appropriate manner and still be able to track the saved file. `bfcadd()` -should be utilized when a file already exists or a remote resource is being -accessed. - -`bfcnew` takes the `BiocFileCache` object and a user specified `rname` and -returns a path location to save data to. (optionally) you can add the file -extension if you know the type of file that will be saved: - -```{r, bfcnew} -savepath <- bfcnew(bfc, "NewResource", ext=".RData") -savepath - -## now we can use that path in any save function -m = matrix(1:12, nrow=3) -save(m, file=savepath) - -## and that file will be tracked in the cache -bfcinfo(bfc) -``` - -`bfcadd()` is for existing files or remote resources. The user will still -specify an `rname` of their choosing but also must specify a path to local file -or web resource as `fpath`. If no `fpath` is given, the default is to assume the -`rname` is also the path location. If the `fpath` is a local file, there are a -few options for the user determined by the `action` argument. `action` will -allow the user to either `copy` the existing file into the cache directory, -`move` the existing file into the cache directory, or leave the file whereever -it is on the local system yet still track through the cache object `asis`. copy -and move will rename the file to the generated cache file path. If the `fpath` -is a remote source, the source will try to be downloaded, if it is successful it -will save in the cache location and track in the cache object; The original -source will be added to the cache information as `fpath`. If the user does not -want the remote resource to be downloaded initially, the argument -`download=FALSE` may be used to delay the download but add the resource to the -cache. Relative path locations may also be used, specified with -`rtype = "relative"`. This will store a relative location for the file within -the cache; only actions `copy` and `move` are available for relative paths. - -First let's use local files: - -```{r, bfcadd} -fl1 <- tempfile(); file.create(fl1) -add2 <- bfcadd(bfc, "Test_addCopy", fl1) # copy -# returns filepath being tracked in cache -add2 -# the name is the unique rid in the cache -rid2 <- names(add2) - -fl2 <- tempfile(); file.create(fl2) -add3 <- bfcadd(bfc, "Test2_addMove", fl2, action="move") # move -rid3 <- names(add3) - -fl3 <- tempfile(); file.create(fl3) -add4 <- bfcadd(bfc, "Test3_addAsis", fl3, rtype="local", - action="asis") # reference -rid4 <- names(add4) - -file.exists(fl1) # TRUE - copied from original location -file.exists(fl2) # FALSE - moved from original location -file.exists(fl3) # TRUE - left asis, original location tracked -``` - -Now let's add some examples with remote sources: - -```{r, bfcaddremote} -url <- "https://httpbin.org/get" -add5 <- bfcadd(bfc, "TestWeb", fpath=url) -rid5 <- names(add5) - -url2<- "https://bioconductor.org/packages/stats/bioc/BiocFileCache/BiocFileCache_2024_stats.tab" -add6 <- bfcadd(bfc, "TestWeb", fpath=url2) -rid6 <- names(add6) - -# add a remote resource but don't initially download -add7 <- bfcadd(bfc, "TestNoDweb", fpath=url2, download=FALSE) -rid7 <- names(add7) -# let's look at our BiocFileCache object now -bfc -bfcinfo(bfc) -``` - -Now that we are tracking resources, let's explore accessing their information! - -### Caveat - -Files will by default have a unique identifier added to the start of the -original file name (identifier_originalName) when added to the cache to allow -for multiple versions of the same file name. There is an option to override this -default behavior by using the `fname` argument of `bfcadd` or `bfcnew`. `fname` -takes one of two options: `unique` or `exact`. The `unique` option behaves as -default and adds a unique identifier to the original file name. The `exact` -option wil override and not add a unique identifier and an exact match to the -original file name will be added. - - -## Investigating / Accessing Resources - -Before we get into exploring individual resources, a helper function. Most of -the functions provided require the unique rid[s] assigned to a resource. The -`bfcadd` and `bfcnew` return the path as a named character vector, the name of -the character vector is the rid. However, you may want to access a resource -that you have added some time ago. - - * `bfcquery()` - -`bfcquery()` will take in a key word and search across the `rname`, `rpath`, and -`fpath` for any matching entries. The columns that are searched can be -controlled with the argument `field`. - -```{r, bfcquery} -bfcquery(bfc, "Web") - -bfcquery(bfc, "copy") - -q1 <- bfcquery(bfc, "BiocFileCache") -q1 -class(q1) -``` - -As you can see above `bfcquery()`, returns an object of class `tbl_sql` and can -be investiaged further utilizing methods for these classes, such as the package -`dplyr` methods. The `rid` can be seen in the first column of the table to be -used in other functions. To get a quick count of how many objects in the cache -matched the query, use `bfccount()`. - -```{r, bfccount} -bfccount(q1) -``` - - * `[` - -`[` allows for subsetting of the BiocFileCache object. The output will be a -BiocFileSubCache object. Users will still be able to query, remove (from the -subset object only), and access resources of the subset, however the resources -cannot be updated. - -```{r, bfcsubset} -bfcsubWeb = bfc[paste0("BFC", 5:6)] -bfcsubWeb -bfcinfo(bfcsubWeb) -``` - -There are three methods for retrieving the `BiocFileCache` resource path -location. - - * `[[` - * `bfcpath()` - * `bfcrpath()` - -The `[[` will access the `rpath` saved in the `BiocFileCache`. Retrieving this -location will return the path to the local version of the resource; allowing the -user to then use this path in any load/read methods most appropriate for the -resource. The `bfcpath()` and `bfcrpath()` both return a named character vector -also displaying the local file that can be used for retrieval. `bfcpath` -requires `rids` while `bfcrpath()` can use `rids` or `rnames` (but not -both). `bfcrpath()` can be used to add a resource into the cache when `rnames` -are specified; if the element in `rnames` is not found, it will try and add to -the cache with `bfcadd()`. - - -```{r, bfcbracket} -bfc[["BFC2"]] -bfcpath(bfc, "BFC2") -bfcpath(bfc, "BFC5") -bfcrpath(bfc, rids="BFC5") -bfcrpath(bfc) -bfcrpath(bfc, c("https://httpbin.org/get","Test3_addAsis")) -``` - -Managing remote resources locally involves knowing when to update the local copy -of the data. - - * `bfcneedsupdate()` - -`bfcneedsupdate()` is a method that will check the local copy of the data's -etag and last_modifed time to the etag and last_modified time of the remote -resource as well as an expires time. The cache saves this information when the -web resource is initially added. The expires time is checked against the current -Sys.time to see if the local resource has expired. If so the resource will deem -need to be updated; if unavailable or not expired will check the etag and -last_modified_time. The etag information is used definitively if it is -available, if it is not available it checks the last_modified time. If the -resource does not have a last_modified tag either, it is undetermined. If the -resource has not been download yet, it is `TRUE`. - -**Note:** This function does not automatically download the remote source if it - is out of date. Please see `bfcdownload()`. - -```{r, bfcneedsupdate} -bfcneedsupdate(bfc, "BFC5") -bfcneedsupdate(bfc, "BFC6") -bfcneedsupdate(bfc) -``` - -## Updating Resource Entries or Local Copy of Remote Data - -Just as you could access the `rpath`, the local resource path can be set with - - * `[[<-` - -The file must exist in order to be replaced in the `BiocFileCache`. If the user -wishes to rename, they must make a copy (or touch) the file first. - -```{r, bfcrename} -fileBeingReplaced <- bfc[[rid3]] -fileBeingReplaced - -# fl3 was created when we were adding resources -fl3 - -bfc[[rid3]]<-fl3 -bfc[[rid3]] -``` - -The user may also wish to change the `rname` or `fpath` associated with a -resource in addition to the `rpath`. This can be done with - - * `bfcupdate()` - -Again, if changing the `rpath` the file must exist. If a `fpath` is being -updated, the data will be downloaded and the user will be prompted to overwrite -the current file specified in `rpath`. If the user does not want to be prompted -about overwritting of files, `ask=FALSE` may be used. - -```{r, bfcupdate} -bfcinfo(bfc, "BFC1") -bfcupdate(bfc, "BFC1", rname="FirstEntry") -bfcinfo(bfc, "BFC1") -``` - -Now let's update a web resource - -```{r, bfcupdateremote} -suppressPackageStartupMessages({ - library(dplyr) -}) -bfcinfo(bfc, "BFC6") %>% select(rid, rpath, fpath) -bfcupdate(bfc, "BFC6", fpath=url, rname="Duplicate", ask=FALSE) -bfcinfo(bfc, "BFC6") %>% select(rid, rpath, fpath) -``` - -Lastly, remote resources may require an update if the Data is out of date (See -`bfcneedsupdate()`). The `bfcdownload` function will attempt to download from -the original resource saved in the cache as `fpath` and overwrite the out of -date file `rpath` - - * `bfcdownload()` - -The following confirms that resources need updating, and the performs the update - -```{r, bfcdownload} -rid <- "BFC5" -test <- !identical(bfcneedsupdate(bfc, rid), FALSE) # 'TRUE' or 'NA' -if (test) - tryCatch({ - bfcdownload(bfc, rid, ask=FALSE) - }, error = function(e) { - message("Error downloading resource: ", conditionMessage(e)) - }) -``` - -## Adding MetaData - -The following functions are provided for metadata: - - * `bfcmeta()<-` - * `bfcmeta()` - * `bfcmetalist()` - * `bfcmetaremove()` - -Additional metadata can be added as `data.frames` that become tables in the sql -database. The `data.frame` must contain a column `rid` that matches the `rid` -column in the cache. Any metadata added will then be displayed when accessing -the cache. Metadata is added with `bfcmeta()<-`. A table `name` must be provided -as an argument. Users can add multiple metadata tables as long as the names are -unique. Tables may be appended or overwritten using additional arguments -`append=TRUE` or `overwrite=TRUE`. - -```{r, bfcmetadata} -names(bfcinfo(bfc)) -meta <- as.data.frame(list(rid=bfcrid(bfc)[1:3], idx=1:3)) -bfcmeta(bfc, name="resourceData") <- meta -names(bfcinfo(bfc)) -``` -The metadata tables that exist can be listed with `bfcmetalist()` and can be -retrieved with `bfcmeta()`. - -```{r, bfcmetalist} -bfcmetalist(bfc) -bfcmeta(bfc, name="resourceData") -``` - -Lastly, metadata can be removed with `bfcmetaremove()`. - -```{r, bfcmetaremove} -bfcmetaremove(bfc, name="resourceData") -``` - -**Note:** - -While quick implementations of all the functions exist where if you -don't specify a BiocFileCache object it will operate on `BiocFileCache()`, -this option is not available for `bfcmeta()<-`. This function must always -specify a BiocFileCache object by first defining a variable and then passing -that variable into the function. - -Example of ERROR: -```{r eval=FALSE} -bfcmeta(name="resourceData") <- meta -Error in bfcmeta(name = "resourceData") <- meta : - target of assignment expands to non-language object -``` -Correct implementation: -```{r eval=FALSE} -bfc <- BiocFileCache() -bfcmeta(bfc, name="resourceData") <- meta -``` -All other functions have a default, if the BiocFileCache object is missing it -will operate on the default cache `BiocFileCache()`. - -## Removing Resources - -Now that we have added resources, it is also possible to remove a resource. - - * `bfcremove()` - -When you remove a resource from the cache, it will also delete the local file -but only if it is stored in the cache directory as given by `bfccache(bfc)`. If -it is a path to a file somewhere else on the user system, it will only be -removed from the `BiocFileCache` object but the file not deleted. - -```{r, bfcremove} -# let's remind ourselves of our object -bfc - -bfcremove(bfc, "BFC6") -bfcremove(bfc, "BFC1") - -# let's look at our BiocFileCache object now -bfc -``` - -There is another helper function that may be of use: - - * `bfcsync()` - -This function will compare two things: - - 1. If any `rpath` cannot be found (This would occur if `bfcnew()` is used and - the path was not used to save an object) - 2. If there are files in the cache directory (`bfccache(bfc)`), that are not - being tracked by the `BiocFileCache` object - -```{r, bfcsync} -# create a new entry that hasn't been used -path <- bfcnew(bfc, "UseMe") -rmMe <- names(path) -# We also have a file not being tracked because we updated rpath - -bfcsync(bfc) - -# you can suppress the messages and just have a TRUE/FALSE -bfcsync(bfc, FALSE) - -# -# Let's do some cleaning to have a synced object -# -bfcremove(bfc, rmMe) -unlink(fileBeingReplaced) - -bfcsync(bfc) -``` - -## Exporting and Importing Cache - -There is a helper function to export a BiocFileCache and associated files as a -tar or zip archive as well as the appropriate import function. - - * `exportbfc()` - * `importbfc()` - -The `exportbfc` function will take in a BiocFileCache object or subsetted object -and create a tar or zip archive that can then be shared to other collaborators -on different computer systems. The user can choose where the archive is created -with `outputFile`; the current working directory and the name -`BiocFileCacheExport.tar` is used as default. By default a tar archive is -created, but the user can create a zip archive instead using the argument -`outputMethod="zip"`. Any additional argument to the `utils::zip` or -`utils::tar` may also be utilized. - -The following are some example calls: -```{r eval=FALSE} -# export entire biocfilecache -exportbfc(bfc) - -# export the first 4 entries of biocfilecache -# as a compressed tar -exportbfc(bfc, rids=paste0("BFC", 1:4), - outputFile="BiocFileCacheExport.tar.gz", compression="gzip") - -# export the subsetted object of web resources as zip -sub1 <- bfc[bfcrid(bfcquery(bfc, "web", field='rtype'))] -exportbfc(sub1, outputFile = "BiocFileCacheExportWeb.zip", - outMethod="zip") -``` - -The archive once inflated on a users system will have a fully functional copy of -the sent cache. The archive can be extracted manually and the path used in the -constructor `BiocFileCache()` or for convenience the function `importbfc` may be -utilized. The `importbfc` function takes in a path to the appropriate tar or zip -file, the argument `archiveMethod` indicating if `untar` or `unzip` should be -used (the default is untar), a path to where the archive should be extracted to -as `exdir`, and any additional arguments to the `utils::untar` and -`utils::unzip` methods. The function will extract the files and load the -associated BiocFileCache object into the R session. - -The following are example calls to load the above example exported objects: -```{r eval=FALSE} - -bfc <- importbfc("BiocFileCacheExport.tar") - -bfc2 <- importbfc("BiocFileCacheExport.tar.gz", compression="gzip") - -bfc3 <- importbfc("BiocFileCacheExportWeb.zip", archiveMethod="unzip") -``` - -## Creating a Cache from Existing Data - -There exists the following helper functions to convert existing data to a -BiocFileCache: - - * `makeBiocFileCacheFromDataFrame` - -These functions may take awhile to run if there are a lot of resources, however -if the BiocFileCache is stored in a permanent location it will only need to be -run once. - -### Create a BiocFileCache from an Existing data.frame - -`makeBiocFileCacheFromDataFrame` takes an existing data.frame and creates a -BiocFileCache object. The cache location can be specified by the `cache` -argument. The `cache` must not already exist and the user will be prompted to -create the location. If the user opts 'N', the cache will be created in a -temporary directory and this function will have to be run again upon a new R -session. The original data.frame must contain the required BiocFileCache columns -`rtype`, `rpath`, and `fpath` as described in the section 1.2 "Creating / -Loading the Cache". The optional columns `rname`, `last_modified_time`, `etag` -and `expires` may also be specified in the original data.frame although are not -required and will be populated with defaults if missing. For resources with -`rtype="local"`, the `actionLocal` will control if the local copy of the file is -copied or moved to the cache location, or if it is left asis on the local -system; A local copy of the file must exist if the resource is identified as -`rtype=local`. For resources with `rtype="web"`, `actionWeb` will control if the -local copy of the remote file is copied or moved to the cache location. It is a -requirement of BiocFileCache that all remote resources download their local copy -to the cache location. A local copy of the file does not have to exist and can -be downloaded into the cache at a later time. Any additional columns of the -original data.frame besides those required or optional BiocFileCache columns, -are separated and added to the BiocFileCache as a meta data table with the name -given as `metadataName`. See section 1.6 on "Adding Metadata". - -The following is an example data.frame with minimal columns 'rtype', 'rpath', -and 'fpath' and one additional column that will become metadata 'keywords'. The -'rpath' can be `NA` as these are remote resources (`rtype='web'`) that have not -been downloaded yet. - -```{r, mock} -tbl <- data.frame(rtype=c("web","web"), - rpath=c(NA_character_,NA_character_), - fpath=c("https://httpbin.org/get", - "https://en.wikipedia.org/wiki/Bioconductor"), - keywords = c("httpbin", "wiki"), stringsAsFactors=FALSE) -tbl -``` - -```{r eval=FALSE} - -newbfc <- makeBiocFileCacheFromDataFrame(tbl, - cache=file.path(tempdir(),"BFC"), - actionWeb="copy", - actionLocal="copy", - metadataName="resourceMetadata") - -``` - -## Cleaning or Removing Cache - -Finally, there are two function involved with cleaning or deleting the cache: - - * `cleanbfc()` - * `removebfc()` - -`cleanbfc()` will evaluate the resources in the `BiocFileCache` object and -determine which, if any, have not been created, redownloaded, or updated in a -specified number of days. If `ask=TRUE`, each entry that is above that threshold -will ask if it should be removed from the cache object and the file deleted -(only deleted if in `bfccache(bfc)` location). If `ask=FALSE`, it does not ask -about each file and automatically removes and deletes the file. The default -number of days is 120. If a resource has not needed any updates, this function -could give a false positive. It is also does not take into account how many time -the resource was loaded by retrieving the path (ie. via [[, bfcpath, bfcrpath), -so may not be an accurate indication of how often the resource is -utilized. Please use this function with caution. - -```{r eval=FALSE} -cleanbfc(bfc) -``` - -`removebfc()` will remove the `BiocFileCache` complete from the system. Any -files saved in `bfccache(bfc)` directory will also be deleted. - -```{r eval=FALSE} -removebfc(bfc) -``` -**Note** Use with caution! - -# Access Behind a Proxy - -BiocFileCache uses CRAN package `httr2` functions for accessing and downloading -web resources. This can be problematic if operating behind a -proxy. Unfortunately unlike the previously used `httr::set_config`, there is no -option to globally set the proxy for httr2 requests. You can pass proxy -information into the bfcadd, bfcupdate, bfcneedsupdate, and bfcdownload -functions. - -```{r eval=FALSE} -proxy <- "http://my_user:my_password@myproxy:8080" -bfcadd(bfc, rname="uniquename", fpath="https://remoteresource", proxy=proxy) -``` -You can also set a `https_proxy` environment variable. It should be a character -vector similar to the format above. - -# Other configuration options for resource downloading - -As mentioned previously, There is no global option like `httr::set_config` to -set configuration options when using httr2. A `config` argument may be passed to -bfcadd, bfcupdate, bfcneedsupdate, and bfcdownload functions. This argument is a -R list object that will be passed to `httr2::req_options`. The names of the -items should be valid curl options as defined in `curl::curl_options`. - -```{r eval=FALSE} -ssl_opts <- list(verbose = 1L,ssl_verifypeer = 0L, ssl_verifyhost = 0L) -bfcadd(bfc, rname="uniquename", fpath="https://remoteresource", config=ssl_opts) -``` -# Group Cache Access - -The situation may occur where a cache is desired to be shared across multiple -users on a system. This presents permissions errors. To allow access to -multiple users create a group that the users belong to and that the cache -belongs too. Permissions of potentially two files need to be altered depending -on what you would like individuals to be able to accomplish with the cache. A -read-only cache will require manual manipulatios of the -BiocFileCache.sqlite.LOCK so that the group permissions are `g+rw`. To allow -users to download files to the shared cache, both the -BiocFileCache.sqlite.LOCK file and the BiocFileCache.sqlite file will need group -permissions to `g+rw`. Please google how to create a user group for your system -of interest. To find the location of the cache to be able to change the group -and file permissions, you may run the following in R if you used the default location: -`tools::R_user_dir("BiocFileCache", which="cache")` or if you created a unique -location, something like the following: `bfc = -BiocFileCache(cache="someUniquelocation"); bfccache(bfc)`. For quick reference -in linux you will use `chown currentuser:newgroup` to change the group and -`chmod` to change the file permissions: `chmod 660` or `chmod g+rw` should -accomplish the correct permissions. - -# Summary - -It is our hope that this package allows for easier management of local and -remote resources. - -# SessionInfo - -```{r, sessioninfo} -sessionInfo() - -``` - - - -[BiocFileCache]: https://bioconductor.org/packages/BiocFileCache -[dplyr]: https://cran.r-project.org/package=dplyr diff --git a/vignettes/BiocFileCache_Troubleshooting.Rmd b/vignettes/BiocFileCache_Troubleshooting.Rmd deleted file mode 100644 index 687267c..0000000 --- a/vignettes/BiocFileCache_Troubleshooting.Rmd +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: "BiocFileCache Troubleshooting" -author: Lori Shepherd -output: - BiocStyle::html_document: - toc: true - toc_depth: 2 -vignette: > - %\VignetteEngine{knitr::rmarkdown} - %\VignetteIndexEntry{3. BiocFileCache Troubleshooting} - %\VignetteEncoding{UTF-8} - %\VignetteDepends{rtracklayer} ---- - -```{r setup, echo=FALSE} -knitr::opts_chunk$set(collapse=TRUE) -``` - -# Overview - -Organization of files on a local machine can be cumbersome. This is especially -true for local copies of remote resources that may periodically require a new -download to have the most updated information available. [BiocFileCache][] is -designed to help manage local and remote resource files stored locally. It -provides a convenient location to organize files and once added to the cache -management, the package provides functions to determine if remote resources are -out of date and require a new download. - -## Installation and Loading - -`BiocFileCache` is a _Bioconductor_ package and can be installed through -`BiocManager::install()`. - -```{r, eval = FALSE} -if (!"BiocManager" %in% rownames(installed.packages())) - install.packages("BiocManager") -BiocManager::install("BiocFileCache", dependencies=TRUE) -``` - -After the package is installed, it can be loaded into _R_ workspace by - -```{r, results='hide', warning=FALSE, message=FALSE} -library(BiocFileCache) -``` - -## Creating / Loading the Cache - -The initial step to utilizing [BiocFileCache][] in managing files is to create a -cache object specifying a location. We will create a temporary directory for use -with examples in this vignette. If a path is not specified upon creation, the -default location is a directory `~/.BiocFileCache` in the typical user cache -directory as defined by `tools::R_user_dir("", which="cache")`. - -```{r, create} -path <- tempfile() -bfc <- BiocFileCache(path, ask = FALSE) -``` - -# Access Behind a Proxy - -BiocFileCache uses CRAN package `httr2` functions for accessing and downloading -web resources. This can be problematic if operating behind a -proxy. Unfortunately unlike the previously used `httr::set_config`, there is no -option to globally set the proxy for httr2 requests. You can pass proxy -information into the bfcadd, bfcupdate, bfcneedsupdate, and bfcdownload -functions. - -```{r eval=FALSE} -proxy <- "http://my_user:my_password@myproxy:8080" -bfcadd(bfc, rname="uniquename", fpath="https://remoteresource", proxy=proxy) -``` -You can also set a `https_proxy` environment variable. It should be a character -vector similar to the format above. - -# Other configuration options for resource downloading - -As mentioned previously, There is no global option like `httr::set_config` to -set configuration options when using httr2. A `config` argument may be passed to -bfcadd, bfcupdate, bfcneedsupdate, and bfcdownload functions. This argument is a -R list object that will be passed to `httr2::req_options`. The names of the -items should be valid curl options as defined in `curl::curl_options`. - -```{r eval=FALSE} -ssl_opts <- list(verbose = 1L,ssl_verifypeer = 0L, ssl_verifyhost = 0L) -bfcadd(bfc, rname="uniquename", fpath="https://remoteresource", config=ssl_opts) -``` - -# Group Cache Access - -The situation may occur where a cache is desired to be shared across multiple -users on a system. This presents permissions errors. To allow access to -multiple users create a group that the users belong to and that the cache -belongs too. Permissions of potentially two files need to be altered depending -on what you would like individuals to be able to accomplish with the cache. A -read-only cache will require manual manipulatios of the -BiocFileCache.sqlite.LOCK so that the group permissions are `g+rw`. To allow -users to download files to the shared cache, both the -BiocFileCache.sqlite.LOCK file and the BiocFileCache.sqlite file will need group -permissions to `g+rw`. Please google how to create a user group for your system -of interest. To find the location of the cache to be able to change the group -and file permissions, you may run the following in R if you used the default location: -`tools::R_user_dir("BiocFileCache", which="cache")` or if you created a unique -location, something like the following: `bfc = -BiocFileCache(cache="someUniquelocation"); bfccache(bfc)`. For quick reference -in linux you will use `chown currentuser:newgroup` to change the group and -`chmod` to change the file permissions: `chmod 660` or `chmod g+rw` should -accomplish the correct permissions. - - -# Lock file Troubleshooting - -Two issues have been commonly reported regarding the lock file. - -## Permissions - -There could be permission ERROR regarding group and public access. See the -previous `Group Cache Access` section. - -## Cannot lock file / no lock available - -This is an issue with filelock on particular systems. Particular partitions and -non standard file systems may not support filelock. The solution is to use a -different section of the system to create the cache. The easiest way to define a -new cache location is by using environment variables. - -In R: - -`Sys.setenv(BFC_CACHE=)` - -Alternatively, you can set an environment variable globally to avoid having to -set uniquely in each R session. Please google for specific instructions for -setting environment variables globally for your particular OS system. - -Other common filelock implemented packages that have specific environment -variables to control location are: - - * BiocFileCache: BFC_CACHE - * ExperimentHub: EXPERIMENT_HUB_CACHE - * AnnotationHub: ANNOTATION_HUB_CACHE - * biomaRt: BIOMART_CACHE - -# Default Caching Location Update - -As of BiocFileCache version > 1.15.1, the default caching location has -changed. The default cache is now controlled by the function `tools::R_user_dir` -instead of `rappdirs::user_cache_dir`. Users who have utilized the default -BiocFileCache location, to continue using the created cache, must move the cache and its -files to the new default location or delete the old cache and have to redownload -any previous files. - -## Option 1: Moving Files - -The following steps can be used to move the files to the new location: - -1. Determine the old location by running the following in R - `rappdirs::user_cache_dir(appname="BiocFileCache")` - -2. Determine the new location by running the following in R - `tools::R_user_dir("BiocFileCache", which="cache")` - -3. Move the files to the new location. You can do this manually or do the -following steps in R. Remember if you have a lot of cached files, this may take -awhile and you will need permissions on all the files in order to move them. - -```{r, eval=FALSE} - # make sure you have permissions on the cache/files - # use at own risk - - moveFiles<-function(package){ - olddir <- path.expand(rappdirs::user_cache_dir(appname=package)) - newdir <- tools::R_user_dir(package, which="cache") - dir.create(path=newdir, recursive=TRUE) - files <- list.files(olddir, full.names =TRUE) - moveres <- vapply(files, - FUN=function(fl){ - filename = basename(fl) - newname = file.path(newdir, filename) - file.rename(fl, newname) - }, - FUN.VALUE = logical(1)) - if(all(moveres)) unlink(olddir, recursive=TRUE) - } - - - package="BiocFileCache" - moveFiles(package) - -``` - - -## Option 2: Specify a Cache Location Explicitly - -Users may always specify a unique caching location by providing the `cache` argument to the BiocFileCache -constructor; however users must always specify this location as it will not be -recognized by default in subsequent runs. - -Alternatively, the default caching location may also be controlled by a -user-wise or system-wide environment variable. Users may set the environment -variable `BFC_CACHE` to the old location to continue using as default location. - - -## Option 3: Delete the old cache - -Lastly, if a user does not care about the already existing default cache, the -old location may be deleted to move forward with the new default location. This -option should be used with caution. Once deleted, old cached resources will no -longer be available and have to be re-downloaded. - -One can do this manually by navigating to the location indicated in the ERROR -message as `Problematic cache:` and deleting the folder and all its content. - - -The following can be done to delete through R code: - -**CAUTION** This will remove the old cache and all downloaded resources. - - -```{r, eval=FALSE} -library(BiocFileCache) - - -package = "BiocFileCache" - -BFC_CACHE = rappdirs::user_cache_dir(appname=package) -Sys.setenv(BFC_CACHE = BFC_CACHE) -bfc = BiocFileCache(BFC_CACHE) -## CAUTION: This removes the cache and all downloaded resources -removebfc(bfc, ask=FALSE) - -## create new empty cache in new default location -bfc = BiocFileCache(ask=FALSE) - -``` - -# SessionInfo - -```{r, sessioninfo} -sessionInfo() - -``` - - - -[BiocFileCache]: https://bioconductor.org/packages/BiocFileCache -[dplyr]: https://cran.r-project.org/package=dplyr diff --git a/vignettes/BiocFileCache_UseCases.Rmd b/vignettes/BiocFileCache_UseCases.Rmd deleted file mode 100644 index 219093f..0000000 --- a/vignettes/BiocFileCache_UseCases.Rmd +++ /dev/null @@ -1,421 +0,0 @@ ---- -title: "BiocFileCache Use Cases" -author: Lori Shepherd -output: - BiocStyle::html_document: - toc: true - toc_depth: 2 -vignette: > - %\VignetteEngine{knitr::rmarkdown} - %\VignetteIndexEntry{2. BiocFileCache: Use Cases} - %\VignetteEncoding{UTF-8} - %\VignetteDepends{rtracklayer} ---- - -```{r setup, echo=FALSE} -knitr::opts_chunk$set(collapse=TRUE) -``` - -# Overview - -Organization of files on a local machine can be cumbersome. This is especially -true for local copies of remote resources that may periodically require a new -download to have the most updated information available. [BiocFileCache][] is -designed to help manage local and remote resource files stored locally. It -provides a convenient location to organize files and once added to the cache -management, the package provides functions to determine if remote resources are -out of date and require a new download. - -## Installation and Loading - -`BiocFileCache` is a _Bioconductor_ package and can be installed through -`BiocManager::install()`. - -```{r, eval = FALSE} -if (!"BiocManager" %in% rownames(installed.packages())) - install.packages("BiocManager") -BiocManager::install("BiocFileCache", dependencies=TRUE) -``` - -After the package is installed, it can be loaded into _R_ workspace by - -```{r, results='hide', warning=FALSE, message=FALSE} -library(BiocFileCache) -``` - -## Creating / Loading the Cache - -The initial step to utilizing [BiocFileCache][] in managing files is to create a -cache object specifying a location. We will create a temporary directory for use -with examples in this vignette. If a path is not specified upon creation, the -default location is a directory `~/.BiocFileCache` in the typical user cache -directory as defined by `tools::R_user_dir("", which="cache")`. - -```{r} -path <- tempfile() -bfc <- BiocFileCache(path, ask = FALSE) -``` - -# Use Cases - -## Local cache of an internet resource - -One use for [BiocFileCache][] is to save local copies of remote -resources. The benefits of this approach include reproducibility, -faster access, and access (once cached) without need for an internet -connection. An example is an Ensembl GTF file (also available via -[AnnotationHub][]) - -```{r, url} -## paste to avoid long line in vignette -url <- paste( - "ftp://ftp.ensembl.org/pub/release-71/gtf", - "homo_sapiens/Homo_sapiens.GRCh37.71.gtf.gz", - sep="/") -``` - -For a system-wide cache, simply load the [BiocFileCache][] package and -ask for the local resource path (`rpath`) of the resource. - -```{r, eval=FALSE} -library(BiocFileCache) -bfc <- BiocFileCache() -path <- bfcrpath(bfc, url) -``` - -Use the path returned by `bfcrpath()` as usual, e.g., - -```{r, eval=FALSE} -gtf <- rtracklayer::import.gff(path) -``` - -A more compact use, the first or any time, is - -```{r, eval=FALSE} -gtf <- rtracklayer::import.gff(bfcrpath(BiocFileCache(), url)) -``` - -Ensembl releases do not change with time, so there is no need to check -whether the cached resource needs to be updated. - -## Cache of experimental computations - -One might use [BiocFileCache][] to cache results from experimental -analysis. The `rname` field provides an opportunity to provide -descriptive metadata to help manage collections of resources, without -relying on cryptic file naming conventions. - -Here we create or use a local file cache in the directory in which we are -doing our analysis. - -```{r, eval=FALSE} -library(BiocFileCache) -bfc <- BiocFileCache("~/my-experiment/results") -``` - -We perform our analysis... - -```{r, eval=FALSE} -suppressPackageStartupMessages({ - library(DESeq2) - library(airway) -}) -data(airway) -dds <- DESeqDataData(airway, design = ~ cell + dex) -result <- DESeq(dds) -``` - -...and then save our result in a location provided by -[BiocFileCache][]. - -```{r, eval=FALSE} -saveRDS(result, bfcnew(bfc, "airway / DESeq standard analysis")) -``` - -Retrieve the result at a later date - -```{r, eval=FALSE} -result <- readRDS(bfcrpath(bfc, "airway / DESeq standard analysis")) -``` - -One might imagine the following workflow: - -```{r eval=FALSE} -suppressPackageStartupMessages({ - library(BiocFileCache) - library(rtracklayer) -}) - -# load the cache -path <- file.path(tempdir(), "tempCacheDir") -bfc <- BiocFileCache(path) - -# the web resource of interest -url <- "ftp://ftp.ensembl.org/pub/release-71/gtf/homo_sapiens/Homo_sapiens.GRCh37.71.gtf.gz" - -# check if url is being tracked -res <- bfcquery(bfc, url, exact=TRUE) - -if (bfccount(res) == 0L) { - - # if it is not in cache, add - ans <- bfcadd(bfc, rname="ensembl, homo sapien", fpath=url) - -} else { - - # if it is in cache, get path to load - rid = res$rid - ans <- bfcrpath(bfc, rid) - - # check to see if the resource needs to be updated - check <- bfcneedsupdate(bfc, rid) - # check can be NA if it cannot be determined, choose how to handle - if (is.na(check)) check <- TRUE - if (check){ - ans < - bfcdownload(bfc, rid) - } -} - -# ans is the path of the file to load -ans - -# we know because we search for the url that the file is a .gtf.gz, -# if we searched on other terms we can use 'bfcpath' to see the -# original fpath to know the appropriate load/read/import method -bfcpath(bfc, names(ans)) - -temp = GTFFile(ans) -info = import(temp) -``` - -```{r, ensemblremote, eval=TRUE} - -# -# A simpler test to see if something is in the cache -# and if not start tracking it is using `bfcrpath` -# - -suppressPackageStartupMessages({ - library(BiocFileCache) - library(rtracklayer) -}) - -# load the cache -path <- file.path(tempdir(), "tempCacheDir") -bfc <- BiocFileCache(path, ask=FALSE) - -# the web resources of interest -url <- "ftp://ftp.ensembl.org/pub/release-71/gtf/homo_sapiens/Homo_sapiens.GRCh37.71.gtf.gz" - -url2 <- "ftp://ftp.ensembl.org/pub/release-71/gtf/rattus_norvegicus/Rattus_norvegicus.Rnor_5.0.71.gtf.gz" - -# if not in cache will download and create new entry -pathsToLoad <- bfcrpath(bfc, c(url, url2)) - -pathsToLoad - -# now load files as see fit -info = import(GTFFile(pathsToLoad[1])) -class(info) -summary(info) -``` - -```{r eval=FALSE} -# -# One could also imagine the following: -# - -library(BiocFileCache) - -# load the cache -bfc <- BiocFileCache() - -# -# Do some work! -# - -# add a location in the cache -filepath <- bfcnew(bfc, "R workspace") - -save(list = ls(), file=filepath) - -# now the R workspace is being tracked in the cache -``` - -## Cache to manage package data - -A package may desire to use BiocFileCache to manage remote data. The following -is example code providing some best practice guidelines. - -1. Creating the cache - -Assumingly, the cache could potentially be called in a variety of places within -code, examples, and vignette. It is desirable to have a wrapper to the -BiocFileCache constructor. The following is a suggested example for a package -called `MyNewPackage`: - -```{r, eval=FALSE} -.get_cache <- - function() -{ - cache <- tools::R_user_dir("MyNewPackage", which="cache") - BiocFileCache::BiocFileCache(cache) -} -``` -Essentially this will create a unique cache for the package. If run -interactively, the user will have the option to permanently create the package -cache, else a temporary directory will be used. - -2. Resources in the cache - -Managing remote resources then involves a function that will query to see if the -resource has been added, if it is not it will add to the cache and if it has it -checks if the file needs to be updated. - -```{r, eval=FALSE} -download_data_file <- - function( verbose = FALSE ) -{ - fileURL <- "http://a_path_to/someremotefile.tsv.gz" - - bfc <- .get_cache() - rid <- bfcquery(bfc, "geneFileV2", "rname")$rid - if (!length(rid)) { - if( verbose ) - message( "Downloading GENE file" ) - rid <- names(bfcadd(bfc, "geneFileV2", fileURL )) - } - if (!isFALSE(bfcneedsupdate(bfc, rid))) - bfcdownload(bfc, rid) - - bfcrpath(bfc, rids = rid) -} -``` - -## Processing web resources before caching - -A case has been identified where it may be desired to do some -processing of web-based resources before saving the resource in the -cache. This can be done through specific options of the `bfcadd()` and -`bfcdownload()` functions. - -1. Add the resource with `bfcadd()` using the `download=FALSE` argument. -2. Download the resource with `bfcdownload()` using the `FUN` argument. - -The `FUN` argument is the name of a function to be applied before -saving the downloaded file into the cache. The default is -`file.rename`, simply copying the downloaded file into the cache. A -user-supplied function must take ONLY two arguments. When invoked, the -arguments will be: - -1. `character(1)` A temporary file containing the resource as - retrieved from the web. -2. `character(1)` The BiocFileCache location where the processed file - should be saved. - -The function should return a `TRUE` on success or a `character(1)` -description for failure on error. As an example: - -```{r, preprocess} -url <- "http://bioconductor.org/packages/stats/bioc/BiocFileCache/BiocFileCache_stats.tab" - -headFile <- # how to process file before caching - function(from, to) -{ - dat <- readLines(from) - writeLines(head(dat), to) - TRUE -} - -rid <- bfcquery(bfc, url, "fpath")$rid -if (!length(rid)) # not in cache, add but do not download - rid <- names(bfcadd(bfc, url, download = FALSE)) - -update <- bfcneedsupdate(bfc, rid) # TRUE if newly added or stale -if (!isFALSE(update)) # download & process - bfcdownload(bfc, rid, ask = FALSE, FUN = headFile) - -rpath <- bfcrpath(bfc, rids=rid) # path to processed result -readLines(rpath) # read processed result -``` - -Note: By default bfcadd uses the webfile name as the saved local file. If the -processing step involves saving the data in a different format, utilize the -bfcadd argument `ext` to assign an extension to identify the type of file that -was saved. -For example -``` -url = "https://httpbin.org/get" -bfcadd("myfile", url, download=FALSE) -# would save a file `_get` in the cache -bfcadd("myfile", url, download=FALSE, ext=".Rdata") -# would save a file `_get.Rdata` in the cache -``` - -# Access Behind a Proxy - -BiocFileCache uses CRAN package `httr2` functions for accessing and downloading -web resources. This can be problematic if operating behind a -proxy. Unfortunately unlike the previously used `httr::set_config`, there is no -option to globally set the proxy for httr2 requests. You can pass proxy -information into the bfcadd, bfcupdate, bfcneedsupdate, and bfcdownload -functions. - -```{r eval=FALSE} -proxy <- "http://my_user:my_password@myproxy:8080" -bfcadd(bfc, rname="uniquename", fpath="https://remoteresource", proxy=proxy) -``` -You can also set a `https_proxy` environment variable. It should be a character -vector similar to the format above. - -# Other configuration options for resource downloading - -As mentioned previously, There is no global option like `httr::set_config` to -set configuration options when using httr2. A `config` argument may be passed to -bfcadd, bfcupdate, bfcneedsupdate, and bfcdownload functions. This argument is a -R list object that will be passed to `httr2::req_options`. The names of the -items should be valid curl options as defined in `curl::curl_options`. - -```{r eval=FALSE} -ssl_opts <- list(verbose = 1L,ssl_verifypeer = 0L, ssl_verifyhost = 0L) -bfcadd(bfc, rname="uniquename", fpath="https://remoteresource", config=ssl_opts) -``` - -# Group Cache Access - -The situation may occur where a cache is desired to be shared across multiple -users on a system. This presents permissions errors. To allow access to -multiple users create a group that the users belong to and that the cache -belongs too. Permissions of potentially two files need to be altered depending -on what you would like individuals to be able to accomplish with the cache. A -read-only cache will require manual manipulatios of the -BiocFileCache.sqlite.LOCK so that the group permissions are `g+rw`. To allow -users to download files to the shared cache, both the -BiocFileCache.sqlite.LOCK file and the BiocFileCache.sqlite file will need group -permissions to `g+rw`. Please google how to create a user group for your system -of interest. To find the location of the cache to be able to change the group -and file permissions, you may run the following in R if you used the default location: -`tools::R_user_dir("BiocFileCache", which="cache")` or if you created a unique -location, something like the following: `bfc = -BiocFileCache(cache="someUniquelocation"); bfccache(bfc)`. For quick reference -in linux you will use `chown currentuser:newgroup` to change the group and -`chmod` to change the file permissions: `chmod 660` or `chmod g+rw` should -accomplish the correct permissions. - -# Summary - -It is our hope that this package allows for easier management of local and -remote resources. - - -# SessionInfo - -```{r, sessioninfo} -sessionInfo() - -``` - - - -[BiocFileCache]: https://bioconductor.org/packages/BiocFileCache -[dplyr]: https://cran.r-project.org/package=dplyr