R/diff.R

Defines functions diff

Documented in diff

#' extract
#'
#' Extracts parts from the file(s) based on their extension, writes them to disk and process further based on th eoptions given.
#' \code{extract} uses \code{extract.XXX} to extract the parts from a file based on the file extension \code{XXX}. 
#' \code{option.YYY} is used to process the file written to disk further.
#' 
#' Currently are supported:
#' \describe{
#' \item{\code{extract.tex}}{extraction from tex files}
#' \item{\code{option.R}}{further processing of \code{R} files}
#' }
#' You may provide further \code{extract.XXX} or \code{option.YYY} functions. 
#' 
#' @param files character: a vector with file name(s)
#' @param quiet logical: should be info messages suppressed? (default: \code{FALSE})
#' @param ... named parameters: the parameter {.XXX} should contain a regular expression to extract
#'
#' @return invisibly a list of files written to disk
#' @importFrom stringr str_extract str_split
#' @export
#'
#' @examples
#' file  <- system.file("example.tex", package="extpro")
#' d <- diff(file)
#' d
diff <- function(files, quiet=FALSE, ...) {
  extfile <- list()
  args    <- list(...)
  for (file in files) {
    extfile[[file]] <- character(0)
    dir    <- dirname(file)
    base   <- basename(file)
    ext    <- str_extract(base, "\\.[^\\.]+$")
    if (is.na(ext)) {
       warning(sprintf("File %s has no extension", file))
    } else {
      extfun <- match.fun(paste0('extract', ext))
      extdf  <- extfun(paste0(suppressWarnings(readLines(file)), collapse="\n"), args[[ext]])
      if (anyDuplicated(extdf$file)) warning("duplicate file names found")
      if (nrow(extdf)) {
        if (!quiet) cat(file, "\n") 
        naopt <- is.na(extdf$option)
        extfile[[file]] <- list()
        if (sum(naopt)) extdf$option[naopt] <- "default"
        for (i in 1:nrow(extdf)) {
          outfile     <- paste0(dir, '/', extdf$file[i])
          outcontents <- readLines(outfile)
          fcontents   <- str_split(extdf$contents[i], "\n")[[1]]
          extfile[[file]][[outfile]] <- diffLines(fcontents, outcontents)
          if (!quiet) {
            same <- all(extfile[[file]][[outfile]]$diff=="=")
            cat(" ", outfile, if(same) " identical" else "diffent", "\n")
          }
        }
      }
    }
  }
  invisible(extfile)
}
sigbertklinke/extpro documentation built on Dec. 31, 2020, 7:26 a.m.