R/sysr.R

Defines functions get_os get_ram url_size file_size construct_temp_file_name remove_tmp_files

# library(RCurl)
# library(pryr)

get_os <- function(){
  sysinf <- Sys.info()
  if (!is.null(sysinf)){
    os <- sysinf['sysname']
    if (os == 'Darwin')
      os <- "osx"
  } else { ## mystery machine
    os <- .Platform$OS.type
    if (grepl("^darwin", R.version$os))
      os <- "osx"
    if (grepl("linux-gnu", R.version$os))
      os <- "linux"
  }
  tolower(os)
}

get_ram <- function(){
  op_sys <- get_os()
  if (tolower(op_sys) == 'windows') {
    return(memory.limit() - memory.size())
  }
}

url_size <- function(url) {
  res <- RCurl::url.exists(url, .header=TRUE)
  as.numeric(res['Content-Length'])/(10^6)
}

file_size <- function(path) {
  file.info(path)$size/(10^6)
}

construct_temp_file_name <- function(dir = getwd(), ext='.tmp') {
  files <- sapply(list.files(dir), function(x) tools::file_path_sans_ext(x))
  file_name <- 'tmp'
  while (paste0(file_name) %in% files) {
    file_name<- paste0(file_name, "_tmp")
  }
  file_name <- paste0(file_name, ext)

  file_name
}


remove_tmp_files <- function(dir=getwd(), pattern="tmp.|temp_", force=F, ...) {
  files <- list.files(dir)
  files <- files[grepl(pattern = pattern, x = files)]

  if (force ==T) {
    unlink(files, ...)
  }

  if (length(files) >0 & force == F) {
    out <- utils::askYesNo(paste0('About to remove files: ', paste0(files, collapse = "\n")), default = TRUE,
                           prompts = getOption("askYesNo", gettext(c("Yes", "No"))))
    if (out == T) {
      unlink(files, ...)
    }
  } else {
    warning('No files to remove')
  }

}
JTT94/rtoolbox documentation built on May 14, 2019, 12:08 p.m.