R/clean_source.R

Defines functions clean_source

Documented in clean_source

#' Clean the source text from a cell.
#'
#' @param cell_source The code source as a list of lines of text.
#' @param cell_type The type of cell the source came from.
#' @param keep_comments Should comments (# ...) be kept in code cells?
#'
#' @return A character vector of length 1, where the cleaned text has been
#'   collapsed into a single string (lines delimited by `\n`).
#' @export
clean_source <- function(
  cell_source = list(),
  cell_type = c('code', 'markdown'),
  keep_comments = TRUE
) {
  vctrs::vec_assert(cell_source, ptype = list())
  cell_type <- rlang::arg_match(cell_type)
  vctrs::vec_assert(keep_comments, ptype = logical(), size = 1)

  collapse_lines <- function(x) {
    purrr::map_chr(x, ~stringr::str_c(.x, collapse = '\n'))
  }
  strip_empty_lines <- function(x) {
    x[stringr::str_detect(x, "")]
  }
  strip_comments <- function(x, perform) {
    if (perform) stringr::str_split_fixed(x, "#|;", 2)[, 1] else x
  }
  clean_code <- function(x) {
    purrr::map(x, function(src) {
      tryCatch(
        utils::capture.output(styler::style_text(src)),
        error = function(e) src
      )
    })
  }

  code_cells <- stringr::str_detect(cell_type, '^code$')
  cell_source[code_cells] <- cell_source[code_cells] %>%
    clean_code() %>%
    collapse_lines() %>%
    strip_comments(!keep_comments) %>%
    strip_empty_lines()

  cell_source[!code_cells] <- cell_source[!code_cells] %>%
    collapse_lines() %>% collapse_lines()

  as.character(cell_source)
}
adamblake/nbsimplegrader_companion documentation built on April 19, 2020, 6:05 p.m.