/
checksums.R
362 lines (337 loc) · 11.9 KB
/
checksums.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
utils::globalVariables(c(
"actualFile", "algorithm", "checksum", "checksum.x", "checksum.y",
"filesize", "filesize.x", "filesize.y",
"i.algorithm", "i.checksum", "i.filesize", "result"
))
################################################################################
#' Calculate checksum
#'
#' Verify (and optionally write) checksums.
#' Checksums are computed using [.digest()], which is simply a
#' wrapper around `digest::digest`.
#'
#' @note In version 1.2.0 and earlier, two checksums per file were required
#' because of differences in the checksum hash values on Windows and Unix-like
#' platforms. Recent versions use a different (faster) algorithm and only require
#' one checksum value per file.
#' To update your \file{CHECKSUMS.txt} files using the new algorithm, see
#' <https://github.com/PredictiveEcology/SpaDES/issues/295#issuecomment-246513405>.
#'
#' @param path Character string giving the directory path containing `CHECKSUMS.txt`
#' file, or where it will be written if `checksumFile = TRUE`.
#'
#' @param write Logical indicating whether to overwrite `CHECKSUMS.txt`.
#' Default is `FALSE`, as users should not change this file.
#' Module developers should write this file prior to distributing
#' their module code, and update accordingly when the data change.
#'
#' @param quickCheck Logical. If `TRUE`, then this will only use file sizes,
#' rather than a digest::digest hash. This is generally faster,
#' but will be *much* less robust.
#'
#' @param checksumFile The filename of the checksums file to read or write to.
#' The default is \file{CHECKSUMS.txt} located at
#' `file.path(path, module, "data", checksumFile)`.
#' It is likely not a good idea to change this, and should
#' only be used in cases such as `Cache`, which can
#' evaluate if the `checksumFile` has changed.
#'
#' @param files An optional character string or vector of specific files to checksum.
#' This may be very important if there are many files listed in a
#' `CHECKSUMS.txt` file, but only a few are to be checksummed.
#'
#' @param ... Passed to [digest::digest()] and [utils::write.table()].
#' For `digest`, the notable argument is `algo`. For `write.table`,
#' the notable argument is `append`.
#'
#' @inheritParams Cache
#' @return A `data.table` with columns: `result`, `expectedFile`,
#' `actualFile`, `checksum.x`, `checksum.y`,
#' `algorithm.x`, `algorithm.y`, `filesize.x`, `filesize.y`
#' indicating the result of comparison between local file (`x`) and
#' expectation based on the `CHECKSUMS.txt` file.
#'
#' @author Alex Chubaty
#' @export
#' @rdname Checksums
#'
#' @examples
#' \dontrun{
#' modulePath <- file.path(tempdir(), "myModulePath")
#' dir.create(modulePath, recursive = TRUE, showWarnings = FALSE)
#' moduleName <- "myModule"
#' cat("hi", file = file.path(modulePath, moduleName)) # put something there for this example
#'
#' ## verify checksums of all data files
#' Checksums(modulePath, files = moduleName)
#'
#' ## write new CHECKSUMS.txt file
#' Checksums(files = moduleName, modulePath, write = TRUE)
#' }
#'
setGeneric("Checksums", function(path, write, quickCheck = FALSE,
checksumFile = identifyCHECKSUMStxtFile(path),
files = NULL, verbose = getOption("reproducible.verbose", 1),
...) {
standardGeneric("Checksums")
})
#' @importFrom data.table setnames
#' @importFrom methods formalArgs
#' @importFrom stats na.omit
#' @importFrom utils read.table write.table
#' @rdname Checksums
setMethod(
"Checksums",
signature = c(
path = "character", quickCheck = "ANY",
write = "logical", files = "ANY"
),
definition = function(path, write, quickCheck, checksumFile, files, verbose = getOption("reproducible.verbose", 1), ...) {
defaultHashAlgo <- "xxhash64"
defaultWriteHashAlgo <- "xxhash64"
dots <- list(...)
dotsWriteTable <- dots[names(dots) %in% formalArgs(write.table)]
dots <- dots[names(dots) %in% formalArgs(digest::digest)]
checkPath(path, create = write)
if (!file.exists(checksumFile)) {
writeChecksumsTable(.emptyChecksumsFileContent, checksumFile, dotsWriteTable)
}
if (is.null(files)) {
files <- list.files(path, full.names = TRUE)
files <- grep(files,
pattern = makeRelative(checksumFile, path),
value = TRUE, invert = TRUE
)
} else {
isAbs <- isAbsolutePath(files)
if (any(!isAbs)) {
files[!isAbs] <- makeAbsolute(files[!isAbs], path)
}
}
txt <- if (file.size(checksumFile) == 0) {
.emptyChecksumsFileContent
} else {
read.table(checksumFile,
header = TRUE,
stringsAsFactors = FALSE
)
}
txt <- as.data.table(lapply(txt, as.character))
set(txt, NULL, "file", makeRelative(txt$file, path))
if (is.null(txt$filesize)) txt$filesize <- rep("", NROW(txt))
txtRead <- txt # keep a copy even if writing
if (!(!write && file.info(checksumFile)$size > 0)) {
txt <- data.frame(
file = character(0), checksum = character(0),
filesize = character(0), stringsAsFactors = FALSE
)
}
if (is.null(dots$algo)) {
if (NROW(files)) {
if (write) {
dots$algo <- defaultWriteHashAlgo
} else {
dots$algo <- defaultHashAlgo
}
} else {
dots$algo <- character()
}
}
stStart <- Sys.time()
messagePrepInputs("Checking local files...", sep = "", verbose = verbose)
filesToCheck <- if (length(txt$file) & length(files)) {
files[makeRelative(files, path) %in% txt$file]
} else {
files
}
if (length(filesToCheck) != length(files)) {
# Could be a case of user passing file path that is not with subdirectories; offer help
justByBasename <- basename(txt$file) %in% basename(files)
if (sum(justByBasename) == length(files)) {
messagePrepInputs(
"Files found in CHECKSUMS.txt that match by basename; using these.\n",
" User should specify all files (e.g., targetFile, alsoExtract, archive)\n",
" with subfolders specified."
)
filesToCheck <- unique(c(filesToCheck, makeAbsolute(txt$file[justByBasename], path)))
}
}
filesToCheck <- filesToCheck[file.exists(filesToCheck)] # remove non existing files
# filesToCheck <- filesToCheck[!dir.exists(filesToCheck)] # remove directories # need to keep directories b/c e.g., gdb files need directories
if (!is.null(txt$algorithm)) {
if (!write) {
dots$algo <- unique(txt[txt$file %in% makeRelative(filesToCheck, path), ][["algorithm"]])
dots$algo <- dots$algo[!is.na(dots$algo)][1]
# dots$algo <- na.omit(dots$algo)[1]
if (is.na(dots$algo)) dots$algo <- defaultWriteHashAlgo
}
} else {
if (NROW(txt)) {
txt$algorithm <- defaultWriteHashAlgo
} else {
txt$algorithm <- character()
}
if (NROW(txtRead)) {
txtRead$algorithm <- defaultWriteHashAlgo
} else {
txtRead$algorithm <- character()
}
}
if (is.null(txt$filesize)) {
quickCheck <- FALSE
messagePrepInputs(" Not possible to use quickCheck;\n ",
" CHECKSUMS.txt file does not have filesizes",
sep = "", verbose = verbose
)
}
checksums <- rep(list(rep("", length(filesToCheck))), 2)
dirs <- dir.exists(filesToCheck)
filesToCheckWODirs <- filesToCheck[!dirs]
if (quickCheck | write) {
checksums[[2]][!dirs] <- do.call(.digest,
args = append(
list(file = filesToCheckWODirs, quickCheck = TRUE),
dots
)
)
}
if (!quickCheck | write) {
checksums[[1]][!dirs] <- do.call(.digest,
args = append(
list(file = filesToCheckWODirs, quickCheck = FALSE),
dots
)
)
}
if (any(dirs)) {
checksums[[1]][dirs] <- "dir"
checksums[[2]][dirs] <- 0
}
verboseTmp <- difftime(Sys.time(), stStart) > 8
messagePrepInputs("Finished checking local files.", sep = "", verbose = verbose - 1 + verboseTmp)
filesToCheckRel <- makeRelative(filesToCheck, path)
out <- if (length(filesToCheck)) {
data.table(
file = filesToCheckRel, checksum = checksums[[1]],
filesize = checksums[[2]], algorithm = dots$algo, stringsAsFactors = FALSE
)
} else {
data.table(
file = character(0), checksum = character(0), filesize = character(0),
algorithm = character(0), stringsAsFactors = FALSE
)
}
out1 <- data.table::copy(out)
if (write) {
writeChecksumsTable(out1, checksumFile, dotsWriteTable)
txt <- txtRead
txt <- txt[out, on = colnames(out)]
# txt1Old <- dplyr::right_join(txt1Old, out)
}
txt1 <- data.table::copy(txt)
out[, actualFile := file]
if (write) {
out <- txt[out, on = "file"]
} else {
out <- out[txt, on = "file"]
}
setnames(out, "file", "expectedFile")
if (quickCheck) {
out[, result := ifelse(filesize != i.filesize, "FAIL", "OK")]
} else {
out[, result := ifelse(checksum != i.checksum, "FAIL", "OK")]
}
data.table::setorderv(out, "result", order = -1L, na.last = TRUE)
out <- out[, .SD[1, ], by = "expectedFile"]
out <- checksumsDirsOk(out)
results.df <- out[, list(
"result" = result,
"expectedFile" = expectedFile,
"actualFile" = actualFile,
"checksum.x" = i.checksum,
"checksum.y" = checksum,
"algorithm.x" = i.algorithm,
"algorithm.y" = algorithm,
"filesize.x" = i.filesize,
"filesize.y" = filesize
)]
return(invisible(results.df))
}
)
#' @rdname Checksums
setMethod(
"Checksums",
signature = c(
path = "character", quickCheck = "ANY",
write = "missing", files = "ANY"
),
definition = function(path, quickCheck, checksumFile, files, verbose, ...) {
Checksums(path,
write = FALSE, quickCheck = quickCheck, checksumFile = checksumFile,
files = files, verbose = verbose, ...
)
}
)
#' @keywords internal
writeChecksumsTable <- function(out, checksumFile, dots) {
out <- out[.orderDotsUnderscoreFirst(out$file), ] ## sort by filename alphabetically
do.call(write.table,
args = append(
list(
x = out, file = checksumFile, eol = "\n",
col.names = !isTRUE(dots$append),
row.names = FALSE
),
dots
)
)
}
#' Calculate the hashes of multiple files
#'
#' Internal function. Wrapper for [digest::digest()] using `xxhash64`.
#'
#' @param file Character vector of file paths.
#' @param ... Additional arguments to `digest::digest`.
#'
#' @return A character vector of hashes.
#'
#' @author Alex Chubaty
#' @importFrom digest digest
#' @keywords internal
#' @rdname digest
setGeneric(".digest", function(file, quickCheck, ...) {
standardGeneric(".digest")
})
#' @rdname digest
setMethod(
".digest",
signature = c(file = "character"),
definition = function(file, quickCheck, algo = "xxhash64", ...) {
if (quickCheck) {
fs <- file.size(file)
as.character(fs) # need as.character for empty case
} else {
as.character(
unname(
unlist(
lapply(file, function(f) {
digest::digest(object = f, file = TRUE, algo = algo, ...)
})
)
)
) # need as.character for empty case # nolint
}
}
)
checksumsDirsOk <- function(out) {
cscols <- "checksum.x|i.checksum"
if (any(grepl(cscols, colnames(out)))) {
cscol <- grep(cscols, colnames(out), value = TRUE)[1]
dirsHave <- unique(dirname(out[!get(cscol) %in% "dir" & result == "OK"]$expectedFile))
dirsHave <- grep("\\.", dirsHave, value = TRUE, invert = TRUE)
if (length(dirsHave)) {
out[get(cscol) %in% "dir" & expectedFile %in% dirsHave, result := "OK"]
}
}
out
}