gadenbuie/garrickadenbuie-com

[Post] knitr hook for adding explainshell links to bash commands

gadenbuie opened this issue · 0 comments

Decorate bash chunks with a special comment next to lines you want to explain, e.g.

ssh -T git@github.com # explain

and it links the command on that line to https://explainshell.com, e.g.

Source Hook
source_hook_og <- knitr::knit_hooks$get("source")
knitr::knit_hooks$set(source = function(x, options) {
  is_bash <- identical(options$engine, "bash")
  rgx_explain <- "\\s*#\\s*explain\\s*$"
  needs_explained <- any(grepl(rgx_explain, x))
  if (!is_bash || !needs_explained) {
    return(source_hook_og(x, options))
  }
  if (length(x) == 1 && grepl("\n", x)) {
    x <- strsplit(x, "\n")[[1]]
  }
  idx_explain <- grep(rgx_explain, x)
  cmds <- sub(rgx_explain, "", x[idx_explain])
  cmds_explain <- sprintf("https://explainshell.com/explain?cmd=%s", utils::URLencode(cmds))
  x[idx_explain] <- sprintf(
    '<a href="%s" target="_blank">%s</a>',
    cmds_explain,
    cmds
  )
  sprintf(
    '\n\n<pre class="sourceCode bash"><code class="sourceCode bash">%s</code></pre>\n\n',
    paste(x, collapse = "\n")
  )
})