R/write.provenance.R

#' Write data provenance to a file
#'
#' Data provenance from the \code{provenance} element of the input list will be
#' written to file in \href{https://www.markdownguide.org/getting-started/}{markdown} format.
#' The \code{output.filename} may be specified, or by default it will be the input object name with the
#' addition of \code{provenance.YYMMDD.md}, where \code{YYMMDD} is the date.
#'
#' @source   Dave Angelini \email{david.r.angelini@@gmail.com} [aut, cre]
#'
#' @param x A list of data provenance elements, or an object containing a list element called \code{provenance}.
#' @param output.filename The file name to export. If done is supplied, defaults to
#'     \code{data.provenance.YYMMDD.md}, where \code{YYMMDD} is the date.
#' @param title An optional title for the data provenance report.
#'
#' @export
#'
#' @examples
#'
#' write.provenance(
#'   shapes.gpa,
#'   output.filename = "shapes.provenance.md",
#'   title = "Shapes data provenance"
#' )
#'

write.provenance <- function (x, output.filename = NULL, title = NULL )
{
  provenance <- NULL
  # Vet the input
  if ("provenance" %in% names(x)) {
    provenance <- x$provenance
  } else {
    if ((class(x)[1] %in% c("gpagen","list"))) {
      provenance <- x
    } else {
      stop("Error: Input is not a recognized type. (See the help entry: '?write.provenace'.)")
    }
  }

  # Vet the output.filename
  cat.output.filename.for.user <- FALSE
  if (is.null(output.filename)) {
    cat.output.filename.for.user <- TRUE
    x.name <- deparse(substitute(x))
    if (is.null(x.name)) { x.name <- "data" }
    output.filename <- paste(x.name,'provenance',format(Sys.time(), "%y%m%d"),'md',sep='.')
  }
  if (!grepl(".md$",output.filename[[1]])) {
    output.filename <- paste0(output.filename[[1]],".md")
  }

  # Header
  header <- ifelse(
    is.null(title),
    paste0("# Data provenance report\n\n"),
    paste0("# ",title,"\n\n")
  )

  # Last entry
  footer <- c("## Data provenance report\n",
    paste0("Generated by user `",(Sys.getenv("LOGNAME")),"` with `borealis::write.provenance` version ",packageVersion("borealis")," on ",format(Sys.time(), "%A, %d %B %Y, %X"),"\n")
  )
  cat(footer)
  footer <- paste0(footer, "\n", collapse = "\n")

  # Combine everything
  output <- paste(header,paste0(unlist(provenance), collapse = "\n"),footer, collapse = "")

  if (cat.output.filename.for.user) {
    message(paste0("Written to file '",output.filename,"'.\n"))
  }

  write.table(output, file = output.filename, sep="\n", quote = FALSE, row.names = FALSE, col.names = FALSE )

} # End of function
aphanotus/borealis documentation built on Nov. 4, 2022, 8:44 p.m.