Skip to content

Instantly share code, notes, and snippets.

@timtreis
Last active July 8, 2021 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timtreis/06935400580779c5a2cc731c6db0aaae to your computer and use it in GitHub Desktop.
Save timtreis/06935400580779c5a2cc731c6db0aaae to your computer and use it in GitHub Desktop.
visR - specifications helper
#!/usr/bin/env Rscript
args = commandArgs(trailingOnly = TRUE)
get_all_tests = function(file_path) {
txt = base::paste(base::readLines(file_path, warn = FALSE), collapse = "\n")
matches = base::gregexpr("testthat::test_that\\(\\\"(.+?)\"", txt)
return(matches)
}
get_all_contexts = function(file_path) {
txt = base::paste(base::readLines(file_path, warn = FALSE), collapse = "\n")
matches = base::gregexpr("context\\(\\\"(.+?)\"", txt)
return(matches)
}
get_contexts_and_tests = function(file_path) {
txt = base::paste(base::readLines(file_path, warn = FALSE), collapse = "\n")
contexts = get_all_contexts(file_path)
context_df = data.frame("pos" = base::unlist(contexts))
context_df["match.length"] = attributes(contexts[[1]])$match.length
context_df["index.type"] = attributes(contexts[[1]])$index.type
context_df["useBytes"] = attributes(contexts[[1]])$useBytes
context_df["type"] = "context"
context_df["content"] = base::regmatches(txt, contexts)
for (i in 1:length(context_df$content)) {
context_df$content[[i]] = base::gsub(pattern = "context\\(\"(.+?)T",
replacement = "T",
x = context_df$content[[i]])
context_df$content[[i]] = base::gsub(pattern = "\"",
replacement = "",
x = context_df$content[[i]])
}
tests = get_all_tests(file_path)
test_df = data.frame("pos" = base::unlist(tests))
test_df["match.length"] = attributes(tests[[1]])$match.length
test_df["index.type"] = attributes(tests[[1]])$index.type
test_df["useBytes"] = attributes(tests[[1]])$useBytes
test_df["type"] = "test"
test_df["content"] = base::regmatches(txt, tests)
for (i in 1:length(test_df$content)) {
test_df$content[[i]] = base::gsub(pattern = "testthat::test_that\\(\\\"T",
replacement = "T",
x = test_df$content[[i]])
test_df$content[[i]] = base::gsub(pattern = "\"",
replacement = "",
x = test_df$content[[i]])
}
matches = rbind(context_df, test_df)
matches = matches[base::order(matches$pos),]
for (line in matches$content) {
base::cat(paste0("#' ", line))
base::cat("\n")
}
}
if (length(args) == 0) {
stop("You need to specify an input file.", call. = FALSE)
} else if (length(args) == 1) {
file_path = args
get_contexts_and_tests(file_path)
} else {
cat(paste0("Please provide only one input file."))
base::stop()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment