Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Last active June 28, 2023 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmbarbone/aca1eeeb88dc1ba8d748ea15cd227a25 to your computer and use it in GitHub Desktop.
Save jmbarbone/aca1eeeb88dc1ba8d748ea15cd227a25 to your computer and use it in GitHub Desktop.
readr wrapper that also checks md5 sums
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