Last active
June 28, 2023 01:01
-
-
Save jmbarbone/aca1eeeb88dc1ba8d748ea15cd227a25 to your computer and use it in GitHub Desktop.
readr wrapper that also checks md5 sums
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
readr_write <- function(x, file, ..., .fun = "csv", .check = TRUE) { | |
if (is.function(.fun)) { | |
.fun <- match.fun(fun) | |
} else { | |
if (requireNamespace("readr", quietly = TRUE)) { | |
.fun <- paste0("write_", .fun) | |
.fun <- getFromNamespace(.fun, asNamespace("readr")) | |
} else { | |
.fun <- switch( | |
tolower(.fun), | |
csv = utils::write.csv, | |
csv2 = utils::write.csv2, | |
delim = utils::write.table, | |
table = utils::write.table, | |
rds = function(x, file, ...) saveRDS(object = x, file = file, ...), | |
tsv = function(x, file, sep = "\t", ...) utils::write.table(x = x, file = file, sep = sep, ...), | |
lines = function(x, file, ...) writeLines(text = x, con = file, ...) | |
) | |
} | |
} | |
if (!fs::file_exists(file) || !.check) { | |
# if file does not exist or we don't need to check | |
return(.fun(x, file = file, ...)) | |
} | |
tmp <- fs::file_temp() | |
on.exit(fs::file_delete(tmp)) | |
.fun(x, file = tmp, ...) | |
if (tools::md5sum(tmp) == tools::md5sum(file)) { | |
message("md5sums are the same") | |
return(invisible(x)) | |
} | |
message("md5sums are different") | |
fs::file_copy(tmp, file, overwrite = TRUE) | |
return(invisible(x)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment