From 2eb06122c02ab9d67d682ff627647d92b9c6373d Mon Sep 17 00:00:00 2001 From: Ian Lyttle Date: Sat, 6 Jan 2024 13:29:33 -0600 Subject: [PATCH] refactor in favor of withr::local_tempfile() --- R/boxr_read.R | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/R/boxr_read.R b/R/boxr_read.R index 78d01fb..fd0fdf3 100644 --- a/R/boxr_read.R +++ b/R/boxr_read.R @@ -60,7 +60,7 @@ box_read <- function(file_id, type = NULL, version_id = NULL, req <- boxGet(file_id, local_file = temp_file, version_id = version_id, version_no = version_no, download = TRUE) - # Extract the filename + # Extract the filename and extension filename <- gsub( 'filename=\"|\"', '', stringr::str_extract( @@ -68,15 +68,15 @@ box_read <- function(file_id, type = NULL, version_id = NULL, 'filename=\"(.*?)\"' ) ) + file_ext <- glue::glue(".{fs::path_ext(filename)}") - # Give the file it's original name back, so that you can preserve the file - # extension - new_name <- paste0(tempdir(), "/", filename) - file.rename(temp_file, new_name) + # Give the file its original file-extension back + temp_file_new <- withr::local_tempfile(fileext = file_ext) + file.rename(temp_file, temp_file_new) # If the file doesn't have an obvious file extension, try and do the right # thing by considering the mime-type from the request - if (!grepl("\\.[[:alnum:]]+$", new_name)) { + if (!grepl("\\.[[:alnum:]]+$", temp_file_new)) { message("Cannot read file extension from name.\n", "Inferring from mime-type...\n") mime <- req$headers$`content-type` @@ -88,13 +88,13 @@ box_read <- function(file_id, type = NULL, version_id = NULL, # Supply the file format to read_fun, if it seems to accept them (the # default, rio::import, does) if ("format" %in% names(formals(read_fun))) { - cont <- read_fun(new_name, format = ext, ...) + cont <- read_fun(temp_file_new, format = ext, ...) } else { # Otherwise, just try and read it with a user-supplied function - cont <- read_fun(new_name, ...) + cont <- read_fun(temp_file_new, ...) } } else { - cont <- read_fun(new_name, ...) + cont <- read_fun(temp_file_new, ...) } # this code comment is old (i think) and maybe worth revisiting was rio goes to CRAN (NCD 2019-11-01) @@ -107,7 +107,7 @@ box_read <- function(file_id, type = NULL, version_id = NULL, } message( - "Remote file '", new_name, "' read into memory as an object of class ", + "Remote file '", filename, "' read into memory as an object of class ", paste(class(cont), collapse = ", "), "\n" )