/
preProcess.R
1753 lines (1633 loc) · 62.9 KB
/
preProcess.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
utils::globalVariables(c(
"reproducible.inputPaths", "successfulCheckSumFilePath", "successfulDir"
))
#' @param n Number of non-null arguments passed to `preProcess`.
#' E.g., passing `n = 1` returns combinations with only a single non-NULL parameter.
#' If `NULL` (default), all parameter combinations are returned.
#'
#' @export
#' @rdname preProcess
preProcessParams <- function(n = NULL) {
p1 <- data.frame(
url = c("char", "NULL", "NULL", "NULL"),
targetFile = c("NULL", "char", "NULL", "NULL"),
archive = c("NULL", "NULL", "char", "NULL"),
alsoExtract = c("NULL", "NULL", "NULL", "char"),
Result = c(
"Download, extract all files if an archive, guess at 'targetFile', load into R.",
"Load 'targetFile' into R.",
"Extract all files, guess at 'targetFile', load into R.",
"Guess at 'targetFile' from files in 'alsoExtract', load into R."
),
FirstChecksum = c(
"Write or append all new files.",
"Write or append 'targetFile'.",
"Write or append all new files.",
"Write or append all new files."
),
SecondChecksum = c(
"Same as first; no 'targetFile'.*",
"No downloading, so no checksums used.",
"No downloading, so no checksums used.",
"No downloading, so no checksums used."
),
stringsAsFactors = FALSE
)
p2 <- data.frame(
url = c("char", "char", "char", "NULL", "NULL", "NULL"),
targetFile = c("char", "NULL", "NULL", "char", "char", "NULL"),
archive = c("NULL", "char", "NULL", "NULL", "char", "char"),
alsoExtract = c("NULL", "NULL", "char", "char", "NULL", "char"),
Result = c(
"Download, extract all files if an archive, load 'targetFile' into R.",
"Download, extract all files, guess at 'targetFile', load into R.",
"Download, extract only named files in 'alsoExtract', guess at 'targetFile', load into R.",
"Load 'targetFile' into R.",
"Extract all files, load 'targetFile' into R.",
" Extract only named files in 'alsoExtract', guess at 'targetFile', load into R."
),
FirstChecksum = c(
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files."
),
SecondChecksum = c(
"Use Checksums, skip downloading.",
"Same as first; no 'targetFile'.*",
"Same as first; no 'targetFile'.*",
"No downloading, so no checksums used.",
"No downloading, so no checksums used.",
"No downloading, so no checksums used."
),
stringsAsFactors = FALSE
)
p3 <- data.frame(
url = c("char", "char", "char", "char", "char", "char", "NULL"),
targetFile = c("char", "NULL", "NULL", "char", "char", "char", "char"),
archive = c("char", "char", "char", "NULL", "NULL", "char", "char"),
alsoExtract = c("NULL", "char", "'similar'", "char", "'similar", "NULL", "char"),
Result = c(
"Download, extract all files, load 'targetFile' into R.",
"Download, extract files named in 'alsoExtract', guess at 'targetFile', load into R.",
"Download, extract all files (can't understand \"similar\"), guess at 'targetFile', load into R.",
"Download, if an archive, extract files named in 'targetFile' and 'alsoExtract', load 'targetFile' into R.",
"Download, if an archive, extract files with same base as 'targetFile', load 'targetFile' into R.",
"Download, extract all files from archive, load 'targetFile' into R.",
"Extract files named in 'alsoExtract' from archive, load 'targetFile' into R."
),
FirstChecksum = c(
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files.",
"Write or append all new files."
),
SecondChecksum = c(
"Use Checksums, skip downloading.",
"Use Checksums, skip downloading.",
"Same as first; no 'targetFile'.",
"Use Checksums, skip downloading.",
"Use Checksums, skip downloading.",
"Use Checksums, skip downloading.",
"No downloading, so no checksums used."
),
stringsAsFactors = FALSE
)
p4 <- data.frame(
url = c("char", "char"),
targetFile = c("char", "char"),
archive = c("char", "char"),
alsoExtract = c("char", "'similar'"),
Result = c(
"Download, extract files named in 'targetFile' and 'alsoExtract', load 'targetFile' into R.",
"Download, extract all files with same basename as 'targetFile', load 'targetFile' into R."
),
FirstChecksum = c(
"Write or append all new files.",
"Write or append all new files."
),
SecondChecksum = c(
"Use Checksums, skip downloading.",
"Use Checksums, skip downloading."
),
stringsAsFactors = FALSE
)
if (is.null(n)) {
rbind(p1, p2, p3, p4)
} else if (n == 1) {
p1
} else if (n == 2) {
p2
} else if (n == 3) {
p3
} else if (n == 4) {
p4
}
}
#' Download, Checksum, Extract files
#'
#' This does downloading (via `downloadFile`), checksumming (`Checksums`),
#' and extracting from archives (`extractFromArchive`), plus cleaning up of input
#' arguments (e.g., paths, function names).
#' This is the first stage of three used in `prepInputs`.
#'
#' @return
#' A list with 5 elements: `checkSums` (the result of a `Checksums`
#' after downloading), `dots` (cleaned up `...`, including deprecated argument checks),
#' `fun` (the function to be used to load the `preProcess`ed object from disk),
#' and `targetFilePath` (the fully qualified path to the `targetFile`).
#'
#' @section Combinations of `targetFile`, `url`, `archive`, `alsoExtract`:
#'
#' Use `preProcessParams()` for a table describing various parameter combinations and their
#' outcomes.
#'
#' `*` If the `url` is a file on Google Drive, checksumming will work
#' even without a `targetFile` specified because there is an initial attempt
#' to get the remove file information (e.g., file name). With that, the connection
#' between the `url` and the filename used in the \file{CHECKSUMS.txt} file can be made.
#'
#' @inheritParams prepInputs
#' @inheritParams downloadFile
#'
#' @author Eliot McIntire
#' @export
#' @importFrom data.table fread setDT
preProcess <- function(targetFile = NULL, url = NULL, archive = NULL, alsoExtract = NULL,
destinationPath = getOption("reproducible.destinationPath", "."),
fun = NULL, dlFun = NULL,
quick = getOption("reproducible.quick"),
overwrite = getOption("reproducible.overwrite", FALSE),
purge = FALSE,
verbose = getOption("reproducible.verbose", 1),
.tempPath, ...) {
if (missing(.tempPath)) {
.tempPath <- tempdir2(rndstr(1, 6))
on.exit(
{
unlink(.tempPath, recursive = TRUE)
},
add = TRUE
)
}
dlFunCaptured <- substitute(dlFun)
prepInputsAssertions(environment())
verboseCFS <- verbose
isAlreadyQuoted <- any(grepl("quote", dlFunCaptured))
if (isAlreadyQuoted) {
dlFunCaptured <- eval(dlFunCaptured)
}
dots <- list(...)
fun <- .checkFunInDots(fun = fun, dots = dots)
dots <- .checkDeprecated(dots, verbose = verbose)
teamDrive <- getTeamDrive(dots)
# remove trailing slash -- causes unzip fail if it is there
destinationPath <- normPath(destinationPath)
checkSumFilePath <- identifyCHECKSUMStxtFile(destinationPath)
if (!is.null(archive)) {
if (any(is.na(archive))) {
if (all(!is.character(archive))) {
archive <- as.character(archive)
}
}
}
targetFileGuess <- NULL
if (is.null(targetFile) || is.null(archive)) {
targetFileGuess <- .guessAtFile(
url = url, archive = archive, targetFile = targetFile,
destinationPath = destinationPath, verbose = verbose,
team_drive = teamDrive
)
if (is.null(archive)) {
archive <- .isArchive(targetFileGuess)
}
}
if (is.logical(alsoExtract)) {
alsoExtract <- c("none", "all")[alsoExtract + 1]
}
targetFilePath <- getTargetFilePath(
targetFile, archive, targetFileGuess, verbose,
destinationPath, alsoExtract, checkSumFilePath
)
targetFile <- makeRelative(targetFilePath, destinationPath)
alsoExtract <- guessAlsoExtract(targetFile, alsoExtract, checkSumFilePath)
if (!dir.exists(destinationPath)) {
if (isFile(destinationPath)) {
stop("destinationPath must be a directory")
}
checkPath(destinationPath, create = TRUE)
}
messagePrepInputs("Preparing: ", targetFile, verbose = verbose)
needChecksums <- 0
archive <- setupArchive(archive, destinationPath)
filesToCheck <- na.omit(unique(c(archive, targetFilePath, alsoExtract)))
# Need to run checksums on all files in destinationPath because we may not know what files we
# want if targetFile, archive, alsoExtract not specified
# This will switch destinationPath to be same as reproducible.inputPaths
# This means that we need to modify some of the paths that were already absolute to destinationPath
inputPaths <- runChecksums(destinationPath, checkSumFilePath, filesToCheck, verbose)
list2env(inputPaths, environment()) # reproducible.inputPaths, destinationPathUser, destinationPath, checkSums
if (!is.null(inputPaths$destinationPathUser)) { # i.e., it changed
targetFilePath <- makeRelative(targetFilePath, inputPaths$destinationPathUser)
targetFilePath <- makeAbsolute(targetFilePath, destinationPath)
filesToCheck <- makeRelative(filesToCheck, inputPaths$destinationPathUser)
filesToCheck <- makeAbsolute(filesToCheck, destinationPath)
if (!is.null(archive)) {
archive <- makeRelative(archive, inputPaths$destinationPathUser)
archive <- makeAbsolute(archive, destinationPath)
}
}
if (is(checkSums, "try-error")) {
needChecksums <- 1
checkSums <- .emptyChecksumsResult
}
# This will populate a NULL archive if archive is local or
archiveOut <- dealWithArchive(
archive, url, targetFile, checkSums, alsoExtract,
destinationPath, teamDrive, verbose
)
list2env(archiveOut, envir = environment()) # checkSums, archive, fileGuess
# NOW -- archive will exist if it didn't before
# Double check that targetFile and alsoExtract are correct paths, given that in archive, they may be in sub-folders
needEmptyChecksums <- FALSE
if (is.logical(purge)) purge <- as.numeric(purge)
if (purge == 1) {
unlink(checkSumFilePath)
needChecksums <- 1
}
if (purge > 1) {
checkSums <- .purge(
checkSums = checkSums, purge = purge, targetFile = targetFile,
archive = archive, url = url, alsoExtract = alsoExtract
)
needChecksums <- 2
}
neededFiles <- c(targetFile, makeAbsolute(alsoExtract, destinationPath)) # if (!is.null(alsoExtract)) basename2(alsoExtract))
if (is.null(neededFiles)) neededFiles <- makeAbsolute(archive)
# remove "similar" from needed files. It is for extracting.
neededFiles <- grep("similar$", neededFiles, value = TRUE, invert = TRUE)
# Deal with "similar" in alsoExtract -- maybe this is obsolete with new feature that uses file_name_sans_ext
if (is.null(alsoExtract)) {
filesInsideArchive <- .listFilesInArchive(archive) # will be relative
neededFiles <- checkRelative(neededFiles, destinationPath, filesInsideArchive)
if (isTRUE(length(filesInsideArchive) > 0)) {
checkSums <- .checkSumsUpdate(destinationPath, makeAbsolute(filesInsideArchive, destinationPath),
checkSums = checkSums
)
}
neededFiles <- unique(c(neededFiles, filesInsideArchive))
} else {
outFromSimilar <- .checkForSimilar(neededFiles, alsoExtract, archive, targetFile,
destinationPath = destinationPath, checkSums,
checkSumFilePath = checkSumFilePath, url, verbose = verboseCFS
)
verboseCFS <- verbose - 1
list2env(outFromSimilar, environment()) # neededFiles, checkSums
}
neededFiles <- unique(makeAbsolute(neededFiles, destinationPath))
neededFiles <- grep("none$", neededFiles, value = TRUE, invert = TRUE)
# alsoExtract <- grep("none$", alsoExtract, value = TRUE, invert = TRUE)
filesToChecksum <- if (is.null(archive) || isTRUE(is.na(archive))) {
NULL
} else {
archive
}
filesToChecksum <- unique(c(filesToChecksum, neededFiles))
isOK <- .compareChecksumsAndFilesAddDirs(checkSums, filesToChecksum, destinationPath) # also checks dirs, so adds lines
if (isTRUE(!all(isOK))) {
results <- .tryExtractFromArchive(
archive = if (isTRUE(is.na(archive))) NULL else archive,
neededFiles = neededFiles,
alsoExtract = alsoExtract, destinationPath = destinationPath,
checkSums = checkSums, needChecksums = needChecksums,
checkSumFilePath = checkSumFilePath,
filesToChecksum = filesToChecksum,
targetFilePath = targetFilePath, quick = quick,
verbose = verbose, .tempPath = .tempPath
)
list2env(results, environment()) # neededFiles, checkSums, filesExtr, targetFilePath, filesToChecksum, needChecksums
if (needChecksums > 0) {
checkSums <- appendChecksumsTable(
checkSumFilePath = checkSumFilePath,
filesToChecksum = unique(filesToChecksum),
destinationPath = destinationPath,
append = results$needChecksums >= 2
)
needChecksums <- 0
}
}
# Check for local copies in all values of reproducible.inputPaths
# At the end of this function, the files will be present in destinationPath, if they existed
# in options("reproducible.inputPaths")
localChecks <- .checkLocalSources(neededFiles,
checkSums = checkSums,
checkSumFilePath = checkSumFilePath,
otherPaths = reproducible.inputPaths,
destinationPath, needChecksums = needChecksums, verbose = verbose
)
list2env(localChecks, environment()) # neededFiles, checkSums, needChecksums, successfulDir, successfulCheckSumFilePath
# Change the destinationPath to the reproducible.inputPaths temporarily, so
# download happens there. Later it will be linked to the user destinationPath
if (!is.null(reproducible.inputPaths)) {
# may already have been changed above
outCheck <- if (!is.null(targetFilePath)) {
!file.exists(targetFilePath)
} else {
TRUE
} ## if NULL, it doesn't exist and we want to proceed
if (outCheck) { # skip if it already existed locally
if (is.null(destinationPathUser)) {
destinationPathUser <- destinationPath
}
on.exit(
{
destinationPath <- destinationPathUser
},
add = TRUE
)
if (!identical(destinationPath, reproducible.inputPaths)) {
# CHANGE destinationPath FOR REMAINDER OF THIS FUNCTION
neededFilesNew <- makeRelative(neededFiles, destinationPath)
targetFilePathNew <- makeRelative(targetFilePath, destinationPath)
destinationPathNew <- reproducible.inputPaths[1]
archiveExistInDestDir <- if (!isNULLorNA(archive)) {
file.exists(archive)
} else {
FALSE
}
existInDestDir <- if (!isNULLorNA(neededFiles)) {
file.exists(neededFiles)
} else {
FALSE
}
if (any(existInDestDir)) {
linkOrCopy(neededFiles[existInDestDir],
makeAbsolute(neededFilesNew[existInDestDir],
absoluteBase = destinationPathNew
),
verbose = verbose - 1
)
}
if (any(archiveExistInDestDir)) {
linkOrCopy(archive[archiveExistInDestDir],
makeAbsolute(makeRelative(archive[archiveExistInDestDir], destinationPath),
absoluteBase = destinationPathNew
),
verbose = verbose - 1
)
}
targetPath <- targetFilePathNew
destinationPath <- destinationPathNew
neededFiles <- neededFilesNew
}
if (isTRUE(any(grepl(archive, pattern = destinationPathUser)))) {
# might have a "." as destinationPath -- messes with grepl
patt <- if (grepl("^\\.", destinationPathUser)) {
gsub("^\\.", "^\\\\.", destinationPathUser)
} else {
destinationPathUser
}
archive <- gsub(archive, pattern = patt, replacement = destinationPath)
}
targetFilePath <- makeAbsolute(targetFilePath, destinationPath)
neededFiles <- makeAbsolute(neededFiles, destinationPath)
}
}
###############################################################
# Download
###############################################################
downloadFileResult <- downloadFile(
archive = if (isTRUE(is.na(archive))) NULL else archive,
targetFile = targetFile, neededFiles = neededFiles, destinationPath = destinationPath,
quick = quick, checkSums = checkSums, dlFun = dlFunCaptured, url = url,
checksumFile = asPath(checkSumFilePath), needChecksums = needChecksums,
overwrite = overwrite, purge = purge, # may need to try purging again if no target,
# archive or alsoExtract were known yet
verbose = verbose, .tempPath = .tempPath, ...
)
downloadFileResult <- .fixNoFileExtension(
downloadFileResult = downloadFileResult,
targetFile = targetFile, archive = archive,
destinationPath = destinationPath, verbose = verbose
)
# Post downloadFile -- put objects into this environment
if (!is.null(downloadFileResult$targetFilePath)) {
targetFilePath <- makeAbsolute(downloadFileResult$neededFiles, destinationPath)
}
checkSums <- downloadFileResult$checkSums
needChecksums <- downloadFileResult$needChecksums
neededFiles <- downloadFileResult$neededFiles
# If the download was of an archive, then it is possible the archive path is wrong
if (!isTRUE(is.na(archive))) {
if (identical(downloadFileResult$downloaded, downloadFileResult$archive)) {
archive <- downloadFileResult$downloaded
}
# archive specified, alsoExtract is NULL --> now means will extract all
if (is.null(archive)) archive <- downloadFileResult$archive
}
###############################################################
# redo "similar" after download
###############################################################
outFromSimilar <- .checkForSimilar(
neededFiles = neededFiles, alsoExtract = alsoExtract,
archive = archive, targetFile = targetFile,
destinationPath = destinationPath, checkSums = checkSums,
checkSumFilePath = checkSumFilePath,
url = url, verbose = verboseCFS
)
verboseCFS <- verbose - 1
list2env(outFromSimilar, environment()) # neededFiles, checkSums
# don't include targetFile in neededFiles -- extractFromArchive deals with it separately
if (length(neededFiles) > 1) alsoExtract <- setdiff(neededFiles, targetFile)
# To this point, we only have the archive in hand -- include this in the list of filesToChecksum
filesToChecksum <- if (isTRUE(is.na(archive)) || (is.null(archive))) {
downloadFileResult$downloaded
} else {
archive
}
on.exit(
{
if (needChecksums > 0) {
appendChecksumsTable(
checkSumFilePath = checkSumFilePath,
filesToChecksum = filesToChecksum,
destinationPath = destinationPath,
append = (needChecksums == 2)
)
}
needChecksums <- 0
},
add = TRUE
)
# Stage 1 - Extract from archive
filesToChecksum <- unique(c(filesToChecksum, neededFiles))
isOK <- .compareChecksumsAndFilesAddDirs(checkSums, filesToChecksum, destinationPath)
if (isTRUE(!all(isOK))) {
filesExtracted <- .tryExtractFromArchive(
archive = archive,
neededFiles = neededFiles,
alsoExtract = alsoExtract,
destinationPath = destinationPath,
checkSums = checkSums,
needChecksums = needChecksums,
checkSumFilePath = checkSumFilePath,
filesToChecksum = filesToChecksum,
targetFilePath = targetFilePath,
quick = quick, verbose = verbose,
.tempPath = .tempPath
)
# this changes targetFilePath to have folder if the extraction included a folder
list2env(filesExtracted, environment()) # neededFiles, checkSums, filesExtr, targetFilePath, filesToChecksum, needChecksums
} else {
if (!is.null(.isArchive(archive))) {
messagePrepInputs(" Skipping extractFromArchive attempt: no files missing", verbose = verbose)
}
if (!is.null(targetFilePath))
if (!makeAbsolute(targetFilePath, destinationPath) %in%
makeAbsolute(neededFiles, destinationPath)) {
if (!basename2(targetFilePath) %in% makeRelative(neededFiles, destinationPath)) {
targetFilePath <- grep(basename2(targetFilePath), neededFiles, value = TRUE)
}
}
filesExtr <- c(filesToChecksum, neededFiles)
filesExtr <- setdiff(filesExtr, .isArchive(filesExtr))
}
filesExtr <- unique(c(filesExtr, filesToChecksum))
# link back to destinationPath if options("reproducible.inputPaths") was used.
# destinationPath had been overwritten to be options("reproducible.inputPaths")
if (!is.null(reproducible.inputPaths)) {
if (!is.null(destinationPathUser)) { # retrieved file locally
foundInInputPaths <- grepl(normPath(destinationPath), normPath(filesExtr))
# Make sure they are all in options("reproducible.inputPaths"), accounting for
# the fact that some may have been in sub-folders -- i.e., don't deal with these
if (isTRUE(any(foundInInputPaths))) {
whFilesExtrInIP <- which(file.exists(filesExtr[foundInInputPaths]))
if (length(whFilesExtrInIP)) {
from <- filesExtr[whFilesExtrInIP]
to <- makeAbsolute(makeRelative(from, destinationPath), destinationPathUser)
if (!isTRUE(all(from %in% to))) {
messagePrepInputs("...using copy in getOption('reproducible.inputPaths')...",
verbose = verbose)
}
outHLC <- hardLinkOrCopy(from, to)
filesExtr[foundInInputPaths] <- to
}
}
# targetFilePath may be already in destinationPathUser, depending on when it was created
if (!is.null(targetFilePath)) {
if (!identical(to, targetFilePath)) {
targetFilePathTmp <- to[basename(to) %in% basename(targetFilePath)]
if (any(file.exists(targetFilePathTmp))) {
targetFilePath <- targetFilePathTmp
} else {
targetFilePath <- makeAbsolute(
makeRelative(targetFilePath, destinationPath),
destinationPathUser
)
}
}
}
destinationPath <- destinationPathUser
} else {
foundInLocalPaths <- grepl(normPath(destinationPath), normPath(filesExtr))
# Make sure they are all in options("reproducible.inputPaths"), accounting for
# the fact that some may have been in sub-folders -- i.e., don't deal with these
if (isTRUE(any(foundInLocalPaths))) {
whFilesExtrInLP <- which(file.exists(filesExtr[foundInLocalPaths]))
if (length(whFilesExtrInLP)) {
from <- filesExtr[whFilesExtrInLP]
to <- makeAbsolute(makeRelative(from, destinationPath), reproducible.inputPaths)
if (!isTRUE(all(from %in% to))) {
messagePrepInputs("... copying to getOption('reproducible.inputPaths')...",
verbose = verbose)
}
outHLC <- hardLinkOrCopy(from, to)
}
}
}
}
# if it was a nested file
if (any(fileExt(neededFiles) %in% c("zip", "tar", "rar")) && !isTRUE(is.na(archive))) {
nestedArchives <- neededFiles[fileExt(neededFiles) %in% c("zip", "tar", "rar")]
nestedArchives <- makeAbsolute(nestedArchives[1], destinationPath)
messagePrepInputs("There are still archives in the extracted files.",
" preProcess will try to extract the files from ", basename2(nestedArchives), ".",
" If this is incorrect, please supply archive.",
verbose = verbose
)
# Guess which files inside the new nested
nestedTargetFile <- .listFilesInArchive(archive = nestedArchives)
outFromSimilar <- .checkForSimilar(
alsoExtract = alsoExtract,
archive = nestedArchives,
neededFiles = nestedTargetFile,
destinationPath = destinationPath,
checkSums = checkSums,
checkSumFilePath = checkSumFilePath,
targetFile = targetFile, verbose = verboseCFS
)
neededFiles <- outFromSimilar$neededFiles
checkSums <- outFromSimilar$checkSums
# don't include targetFile in neededFiles -- extractFromArchive deals with it separately
if (length(neededFiles) > 1) alsoExtract <- setdiff(neededFiles, targetFile)
# To this point, we only have the archive in hand -- include this in the list of filesToChecksum
filesToChecksum <- if (is.null(archive)) downloadFileResult$downloaded else basename2(archive)
on.exit(
{
if (needChecksums > 0) {
# needChecksums 1 --> write a new checksums.txt file
# needChecksums 2 --> append to checksums.txt
appendChecksumsTable(
checkSumFilePath = checkSumFilePath,
filesToChecksum = filesToChecksum,
destinationPath = destinationPath,
append = (needChecksums == 2)
)
}
needChecksums <- 0
},
add = TRUE
)
extractedFiles <- .tryExtractFromArchive(
archive = nestedArchives, neededFiles = neededFiles,
alsoExtract = alsoExtract, destinationPath = destinationPath,
checkSums = checkSums, needChecksums = needChecksums,
checkSumFilePath = checkSumFilePath, filesToChecksum = filesToChecksum,
targetFilePath = targetFilePath, quick = quick,
verbose = verbose, .tempPath = .tempPath
)
filesExtr <- c(filesExtr, extractedFiles$filesExtr)
}
targetParams <- .guessAtTargetAndFun(targetFilePath, destinationPath,
filesExtracted = filesExtr,
fun, verbose = verbose
) # passes through if all known
targetFile <- makeRelative(targetParams$targetFilePath, destinationPath)
targetFilePath <- targetParams$targetFilePath
funChar <- targetParams$fun
## targetFilePath might still be NULL, need destinationPath too
if (is.null(targetFilePath)) {
if (is.null(filesExtr)) {
if (!is.null(downloadFileResult$downloaded)) {
targetFilePath <- downloadFileResult$downloaded
}
} else {
targetFilePath <- filesExtr
}
}
if (is.null(targetFile) && !is.null(targetFilePath)) {
targetFile <- makeRelative(targetFilePath, destinationPath)
}
## Convert the fun as character string to function class, if not already
fun <- .extractFunction(funChar)
if (needChecksums > 0) {
## needChecksums 1 --> write a new CHECKSUMS.txt file
## needChecksums 2 --> append to CHECKSUMS.txt file
## needChecksums 3 --> append to checkSumFilePath file OR successfulCheckSumFilePath, not both
if (needChecksums == 3) {
# successfulCheckSumFilePath we do not need to update. Determine which one this is, and do
# other
if (identical(checkSumFilePath, successfulCheckSumFilePath)) { # if it was in checkSumFilePath
checkSumFilePath <- identifyCHECKSUMStxtFile(successfulDir) # run Checksums in IP
}
}
csps <- destinationPath
if (!is.null(reproducible.inputPaths)) {
csps <- c(csps, reproducible.inputPaths)
}
for (csp in csps) {
checkSumFilePath <- identifyCHECKSUMStxtFile(csp)
checkSums <- appendChecksumsTable(
checkSumFilePath = checkSumFilePath,
filesToChecksum = basename2(unique(filesToChecksum)),
destinationPath = csp,
append = needChecksums >= 2
)
needChecksums <- 0
}
if (!is.null(reproducible.inputPaths) && needChecksums != 3) {
checkSumFilePathInputPaths <- identifyCHECKSUMStxtFile(reproducible.inputPaths[[1]])
suppressMessages({
checkSums <- appendChecksumsTable(
checkSumFilePath = checkSumFilePathInputPaths,
filesToChecksum = unique(filesToChecksum),
destinationPath = destinationPath,
append = needChecksums == 2
)
needChecksums <- 0
})
}
on.exit(
{
needChecksums <- 0
},
add = TRUE,
after = FALSE
) # effectively remove appendChecksums in other
# on.exit because it is done here
}
failStop <- FALSE
if (is.null(targetFilePath)) {
failStop <- TRUE
} else if (!isTRUE(file.exists(targetFilePath))) {
failStop <- TRUE
}
if (isTRUE(failStop)) {
stop(
"targetFile appears to be misspecified at: ", targetFilePath, ". ",
"Possibly, it does not exist in the specified archive, ",
"or the file doesn't exist in destinationPath"
)
}
archiveInChecksums <- checkSums$actualFile %in% makeRelative(archive, destinationPath) # basename2 is needed in checksums
if (any(archiveInChecksums)) {
checkSums[which(archiveInChecksums), result := "ArchiveOK"]
}
out <- list(
checkSums = checkSums,
dots = dots,
fun = fun,
funChar = funChar,
targetFilePath = targetFilePath,
destinationPath = destinationPath,
object = downloadFileResult$object
)
return(out)
}
#' Purge individual line items from checksums file
#'
#' @inheritParams downloadFile
#' @keywords internal
#' @rdname purge
.purge <- function(checkSums, purge, targetFile, archive, alsoExtract, url, destinationPath) {
purgeChar <- as.character(purge)
checkSums <- tryCatch(
switch(purgeChar,
"2" = checkSums[!(checkSums$expectedFile %in% makeRelative(targetFile, destinationPath)), ],
"3" = checkSums[!(checkSums$expectedFile %in% makeRelative(archive, destinationPath)), ],
"4" = checkSums[!(checkSums$expectedFile %in% makeRelative(alsoExtract, destinationPath)), ],
"5" = checkSums[!(checkSums$expectedFile %in% makeRelative(unique(c(targetFile, alsoExtract)), destinationPath)), ], # nolint
"6" = checkSums[!(checkSums$expectedFile %in%
makeRelative(unique(c(targetFile, alsoExtract, archive)), destinationPath)), ], # nolint
"7" = checkSums[!(checkSums$expectedFile %in%
makeRelative(unique(c(targetFile, alsoExtract, archive, url)), destinationPath)), ] # nolint
),
error = function(x) checkSums
)
checkSums
}
#' @keywords internal
.emptyChecksumsResult <- data.table::data.table(
expectedFile = character(),
actualFile = character(),
result = character()
)
#' @keywords internal
.emptyChecksumsFileContent <- data.frame(
file = character(),
checksum = character(),
filesize = character(),
algorithm = character()
)
#' @keywords internal
#' @importFrom utils getFromNamespace
.extractFunction <- function(fun, envir = parent.frame()) {
if (!is.null(fun)) {
if (is.call(fun)) {
fun
} else {
suppressWarnings(isNAFun <- is.na(fun))
if (!any(isNAFun)) {
if (!is.function(fun)) {
if (any(grepl("::", fun))) {
fun2 <- strsplit(fun, "::")[[1]]
pkg <- fun2[1]
fun <- fun2[2]
fun <- getFromNamespace(fun, pkg)
} else {
fun <- get(fun, envir)
}
}
}
}
}
fun
}
#' @keywords internal
.guessAtFile <- function(url, archive, targetFile, destinationPath,
verbose = getOption("reproducible.verbose", 1), team_drive = NULL) {
# if (is.null(targetFile)) {
guessedFile <- if (!is.null(url)) {
gf <- file.path(destinationPath, basename2(url))
# Test for just Google ID supplied
isGID <- all(grepl("^[A-Za-z0-9_-]{33}$", url), # Has 33 characters as letters, numbers or - or _
!grepl("\\.[^\\.]+$", url)) # doesn't have an extension
if (any(grepl("drive.google.com", url), isGID)) {
if (isGID) message("url seems to be a Google Drive ID")
# if (grepl("drive.google.com", url)) {
# ie <- isTRUE(internetExists())
# if (ie) {
gf <- assessGoogle(
url = url, archive = archive, targetFile = targetFile,
destinationPath = destinationPath, verbose = verbose, team_drive = NULL
)
gf <- makeAbsolute(gf, destinationPath)
# }
}
gf
} else {
NULL
}
normPath(guessedFile)
}
# COPIED FROM REQUIRE
# urlExists <- function(url) {
# con <- url(url)
# on.exit(try(close(con), silent = TRUE), add = TRUE)
# for (i in 1:5) {
# a <- try(suppressWarnings(readLines(con, n = 1)), silent = TRUE)
# try(close(con), silent = TRUE)
# ret <- if (is(a, "try-error")) FALSE else TRUE
# if (isTRUE(ret)) {
# break
# } else {
# Sys.sleep(0.1)
# }
# }
# ret
# }
#' @keywords internal
.checkSumsUpdate <- function(destinationPath, newFilesToCheck, checkSums,
checkSumFilePath = NULL, verbose = getOption("reproducible.verbose", 1)) {
if (!is.null(newFilesToCheck)) {
if (is.null(checkSumFilePath) || length(checkSumFilePath) == 0) {
checkSumFilePath <- identifyCHECKSUMStxtFile(destinationPath)
}
if (!file.exists(checkSumFilePath)) {
checkSums
} else {
checkSums2 <- suppressMessages(try(Checksums(
path = destinationPath, write = FALSE,
files = newFilesToCheck,
checksumFile = checkSumFilePath,
verbose = verbose
), silent = TRUE))
if (!is(checkSums2, "try-error")) {
checkSums <- rbindlist(list(checkSums, checkSums2))
data.table::setkey(checkSums, result)
checkSums <- unique(checkSums, fromLast = TRUE, by = "expectedFile")
checkSums <- rbindlist(list(
checkSums[compareNA("OK", result)],
checkSums[compareNA("FAIL", result)],
checkSums[is.na(result)]
))
} else {
stop("checkSumFilePath is not a CHECKSUMS.txt file")
}
}
}
checkSums
}
#' @keywords internal
.similarFilesInCheckSums <- function(file, checkSums, alsoExtract) {
if (NROW(checkSums)) {
if (!missing(alsoExtract)) {
file <- unique(c(file, alsoExtract))
}
anySimilarInCS <- vapply(filePathSansExt(file), function(fi) {
res <- checkSums[grepl(paste0(fi, "\\."), checkSums$expectedFile), ]$result
res <- na.omit(res)
if (length(res) == 0) res <- "NotOK"
isTRUE(all(compareNA("OK", res)))
}, FUN.VALUE = logical(1))
all(anySimilarInCS)
} else {
FALSE
}
}
#' @keywords internal
.checkForSimilar <- function(neededFiles, alsoExtract, archive, targetFile,
destinationPath, checkSums, checkSumFilePath,
url, verbose = getOption("reproducible.verbose", 1)) {
lookForSimilar <- FALSE
if (is.null(alsoExtract) || length(alsoExtract) == 0) {
messagePrepInputs("alsoExtract is unspecified; assuming that all files must be extracted",
verbose = verbose)
lookForSimilar <- "all"
} else {
if (!all(is.na(alsoExtract))) {
if ("similar" %in% basename2(alsoExtract)) {
lookForSimilar <- TRUE
}
}
}
if (isTRUE(lookForSimilar) || ("all" %in% lookForSimilar && !is.null(archive))) {
allFiles <- .listFilesInArchive(archive)
neededFiles <- checkRelative(neededFiles, destinationPath, allFiles)
if (is.null(targetFile)) {
messagePrepInputs("No targetFile supplied. ",
"Extracting all files from archive",
verbose = verbose
)
neededFiles <- allFiles
} else if ("all" %in% lookForSimilar) {
messagePrepInputs("Extracting all files from archive", verbose = verbose)
neededFiles <- allFiles
} else {
allOK <- .similarFilesInCheckSums(targetFile, checkSums, alsoExtract)
if (!allOK) {
filePatternToKeep <- gsub(basename2(targetFile),
pattern = fileExt(basename2(targetFile)), replacement = ""
)
filesToGet <- grep(allFiles, pattern = filePatternToKeep, value = TRUE)
neededFiles <- c(neededFiles, filesToGet)
}
}
rerunChecksums <- TRUE
if (exists("filesToGet", inherits = FALSE)) {
if (length(filesToGet) == 0) {
rerunChecksums <- FALSE
}
}
neededFiles <- unique(makeAbsolute(neededFiles, destinationPath))
if (!is.null(neededFiles) && rerunChecksums) {
checkSums <- .checkSumsUpdate(
destinationPath = destinationPath, newFilesToCheck = neededFiles,
checkSums = checkSums,
checkSumFilePath = checkSumFilePath, verbose = verbose
)
}
}
list(neededFiles = neededFiles, checkSums = checkSums)
}
#' @keywords internal
.checkLocalSources <- function(neededFiles, checkSumFilePath, checkSums, otherPaths, needChecksums,
destinationPath, verbose = getOption("reproducible.verbose", 1)) {
foundInInputPaths <- character()
successfulCheckSumFilePath <- character()
successfulDir <- character()
if (!is.null(neededFiles)) {
filesInHand <- checkSums[compareNA(checkSums$result, "OK"), ]$expectedFile
if (!all(neededFiles %in% filesInHand)) {
for (op in otherPaths) {
recursively <- if (!is.null(getOption("reproducible.inputPathsRecursive"))) {
getOption("reproducible.inputPathsRecursive")
} else {
FALSE
}
opFiles <- dir(op, recursive = recursively, full.names = TRUE)
neededFilesRel <- makeRelative(neededFiles, destinationPath)
if (any(neededFilesRel %in% basename2(opFiles))) {
isNeeded <- basename2(opFiles) %in% neededFilesRel
dirNameOPFiles <- dirname(opFiles[isNeeded])
# foundRecursively <- dirNameOPFiles != dirname(opFiles[isNeeded])
# foundRecursively <- basename2(opFiles[isNeeded][foundRecursively])