R/fakeTextFile.R

Defines functions fakeTextFile

Documented in fakeTextFile

#' Create a dummy text file in a directory.
#'
#' Creates a dummy string of text, saves a text file in \code{\link[base:tempfile]{base::tempdir}}.
#'
#' @param file_extension Character value. File extension, default value is '.R'
#' @param dir_path A character vector with the path to the folder where to save the text file.
#' Default value is NULL and uses \code{\link[base:tempfile]{base::tempdir}}.
#' @param file_path A character vector with the path, file name and extension of the created random file.
#' @param txt An optional string (one line) or list of strings (multiple lines)
#' to save in the text file. Randomly generated by default
#' @param n_lines Positive none zero integer value. If `txt` is not provided, `n_lines` is the number of lines of text in the file.
#'
#' @return A list with two elements:
#'  - tmp_path: the path to the fake text file
#'  - txt: the dummy text string or list of strings
#'
#' @details If not working inside an R project, dir_path has to be complete from root.
#'    To create an empty file, use `txt = ""`.
#' @seealso For more flexibility in random string generation, see \code{NCmisc::fakeLines}.
#'    For more automated paragraph generation, see \code{stringi::stri_rand_lipsum}.
#'
#' @examples \dontrun{fakeTextFile()}
#' @author Alban Sagouis
#' @export


fakeTextFile <- function(file_extension = '.R', dir_path = NULL, file_path = NULL, txt = NULL, n_lines = 1) {
   assertthat::assert_that(assertthat::is.string(file_extension))
   assertthat::assert_that(assertthat::is.number(n_lines))
   assertthat::assert_that(n_lines > 0)

   if(is.null(txt)) {
      if(n_lines == 1) {
         txt <- paste(sample(c(rep(" ", 10), letters), 100, replace = TRUE), collapse = "")
      } else {
         txt <- lapply(1:n_lines, function(x) paste(sample(c(rep(" ", 10), letters), 100, replace = TRUE), collapse = ""))
      }
   } else {
      if(is.list(txt)) lapply(txt, function(line) assertthat::assert_that(assertthat::is.string(line))) else assertthat::assert_that(assertthat::is.string(txt))
   }

   if(is.null(dir_path) & is.null(file_path)) {
      tmp_path <- tempfile(fileext = file_extension)
   } else if(!is.null(dir_path) &  is.null(file_path)) {
      assertthat::assert_that(assertthat::is.writeable(dir_path))
      tmp_path <- tempfile(fileext = file_extension, tmpdir = dir_path)
   } else tmp_path <- file_path

   cat(unlist(txt), file = tmp_path, fill = TRUE)   # , sep = '\n'

   return(list(tmp_path = tmp_path, txt = txt))
}
AlbanSagouis/myToolbox documentation built on Feb. 1, 2021, 1:08 p.m.