R/write.R

Defines functions write_xml write_multiple_files create_ordered_file_names create_xml_filename create_temp_subdir

Documented in create_ordered_file_names create_temp_subdir write_multiple_files write_xml

#' Create a subdirectory in the temporary directory
#'
#' Creates a subdirectory in the temporary directory and returns its path
#'
#' @param tempdir the temporary directory to be used
#' @param time the time indicator
#'
#' @return the path of the subdirectory
#' 
create_temp_subdir <- function(tempdir, time){
  strtime <- paste0("subdir", time)
  path <- file.path(tempdir, strtime)
  dir.create(path)
  return(path)
}


create_xml_filename <- function(time){
  paste0("questions", time)
}

#' Generate file names
#'
#' @param N The number.
#' @param extention Character.
#'
#' @return A vector of length \code{N}.
#'
#' @examples
#' quizin:::create_ordered_file_names(11, ".txt")
#' 
create_ordered_file_names <- function(N, extention = ""){
  chr <- str_pad(seq_len(N), width = nchar(N), pad = 0)
  paste0("file", chr, extention)
}

#' Write ordered files from character vector
#'
#' @param vec A vector of characters. 
#' @param dir The directory to write files.
#'
#' @return The paths of the written files
#' 
#' @importFrom purrr walk2
#' @importFrom readr write_lines
#' 
write_multiple_files <- function(vec, dir){
  names <- create_ordered_file_names(length(vec), extention = ".Rmd")
  paths <- file.path(dir, names)
  walk2(vec, paths, write_lines)
  return(paths)
}


#' Generate the xml file
#'
#' @param subdir the temporary subdirectory where the files are.
#' @param time the time for the file name.
#'
#' @return the path of the xml (which is in the parent directory 
#' of the subdirectory)
#' 
#' @importFrom exams exams2moodle
write_xml <- function(subdir, time){
  list <- list.files(subdir, full.names = TRUE)
  cat("Fichiers découpés :", unlist(list), sep = "\n")
  # dir <- file.path(subdir, "..") # dir is the same as tempdir()
  # dir <- str_remove(subdir, "/[^/]*$") # dir is the same as tempdir()
  dir <- dirname(subdir)
  cat("subdir/.. = tempdir : ", dir, "\n")
  name <- create_xml_filename(time)
  safe_exams(file = list, dir = dir, name = name)
}
MarieEtienne/quizin documentation built on Dec. 17, 2021, 3:11 a.m.