This repository was archived by the owner on Oct 14, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathutils.R
More file actions
91 lines (83 loc) · 2.71 KB
/
utils.R
File metadata and controls
91 lines (83 loc) · 2.71 KB
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
# Utility scripts that are used internally by the package at runtime
#' Gets the file size of a number of remote files
#' @param urls A character vector containing URLs
#' @return The file size of each of the files pointed to by the provided URL,
#' in gigabytes, as double vector
#' @importFrom purrr map_dbl
#' @importFrom httr HEAD
#' @keywords internal
url_file_size <- function(urls){
map_dbl(urls, function(url){
as.integer(
HEAD(url)$headers$`content-length`
) / 10^9
})
}
#' Prints a message indicating the size of a download
#' @inheritParams url_file_size
#' @importFrom cli cli_alert_info
#' @keywords internal
#' @return `NULL`, invisibly
report_file_sizes <- function(urls){
total_size <- url_file_size(urls) |>
sum() |>
round(digits=2)
"Downloading {length(urls)} file{?s}, totalling {total_size} GB" |>
cli_alert_info()
invisible(NULL)
}
#' Formats a multi-line string as it it were on one line
#' @param text Any character vector
#' @return The same character vector, with newlines and subsequent whitespace
#' removed
#' @keywords internal
#' @importFrom stringr str_remove_all
single_line_str <- function(text){
str_remove_all(text, r"(\n\s*)")
}
#' Returns the default cache directory
#' @return A length one character vector.
#' @importFrom tools R_user_dir
#' @importFrom utils packageName
#' @keywords internal
get_default_cache_dir <- function() {
packageName() |>
R_user_dir(
"cache"
) |>
normalizePath() |>
suppressWarnings()
}
#' Synchronises a single remote file with a local path
#' @importFrom httr write_disk GET stop_for_status
#' @importFrom cli cli_abort cli_alert_info
#' @importFrom rlang is_interactive
#' @return `NULL`, invisibly
#' @keywords internal
sync_remote_file <- function(full_url, output_file, ...) {
user_over <- NA
if (file.exists(output_file)) {
if (is_interactive()) {
user_over <- menu(c("Yes", "No"), title = "Cached file alread exists. Overwrite?")
} else {
user_over <- 1
}
}
if (!file.exists(output_file) || user_over == 1) {
output_dir <- dirname(output_file)
dir.create(output_dir,
recursive = TRUE,
showWarnings = FALSE
)
cli_alert_info("Downloading {full_url} to {output_file}")
tryCatch(
GET(full_url, write_disk(output_file, overwrite = TRUE), ...) |> stop_for_status(),
error = function(e) {
# Clean up if we had an error
file.remove(output_file)
cli_abort("File {full_url} could not be downloaded. {e}")
}
)
}
invisible(NULL)
}