# This will only build on unix is_unix <- .Platform$OS.type == "unix" knitr::opts_chunk$set(eval = is_unix)
knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
library(cmdfun) library(magrittr)
out <- processx::run("cut", "--help", error_on_status = FALSE) out$stdout %>% cmd_help_parse_flags(split_newline = TRUE)
Methods to get help lines into R. Examples with processx and system2 (I suggest processx
because it's handling is better, although it needs more steps)
# with processx o <- processx::run("tar", "--help", error_on_status = FALSE) fn_flags <- cmd_help_parse_flags(o$stdout, split_newline = TRUE) # with system2 lines <- system2("tar", "--help", stdout = T) fn_flags <- cmd_help_parse_flags(lines) fn_flags %>% head(10) gsub(", -", "\n-", .) %>% gsub(",", "", .) %>% gsub("=.+", "", .) %>% gsub("\\[", "", .) %>% unique # Custom function to clean up final parsed flags parse_tar_help <- function(lines){ lines %>% gsub(", -", "\n-", .) %>% gsub(",", "", .) %>% gsub("=.+", "", .) %>% gsub("\\[", "", .) %>% unique }
tar <- function(...){ cmd_args_dots() %>% cmd_list_to_flags() } tar_withCheck <- function(...){ tarHelp <- system2("tar", "--help", stdout = T) tarflags <- tarHelp %>% cmd_help_parse_flags() %>% parse_tar_help() inputFlags <- cmd_args_dots() %>% cmd_list_interp() #purrr::set_names(~{gsub("_", "-", .)}) # check that inputs are valid cmd_help_flags_similar(tarflags, names(inputFlags), ~{gsub("-", "_", .)}) %>% cmd_help_flags_suggest() } tar_withCheck(utz = "value", exclude_caces = TRUE) tar_withCheck(c = T, concatenate = T)
help checking is expensive (relative to not doing it), so it makes sense to only do it if there's an error.
We can write a simple function to check
check_tar_flags <- function(flags){ flag_names <- names(flags) tarhelp_out <- processx::run("tar", "--help", error_on_status = F) tarhelp_out$stdout %>% cmd_help_parse_flags(split_newline = TRUE) %>% cmd_help_flags_similar(flag_names, ~{ gsub("-", "_", .) %>% gsub(",", "", .) }) %>% cmd_help_flags_suggest() }
check_tar_flags(list("utd" = 1, "verzion" = 2))
This is where processx
shines, but error checking can be done using system2
as well. We catch errors by checking the exit status, where non-zero exit status
is considered an error.
tar_withCheck <- function(file, ...){ inputFlags <- cmd_args_dots() %>% cmd_list_interp() %>% purrr::set_names(~{gsub("_", "-", .)}) flags <- inputFlags %>% cmd_list_to_flags() flags <- c(flags, file) ps_out <- processx::run("tar", flags, error_on_status = F) if (ps_out$status != 0){ # Print stdout & stderr to user message(ps_out$stdout) message(ps_out$stderror) # Suggest flags check_tar_flags(inputFlags) } }
tar_withCheck("test.txt", uts = "value")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.