diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml new file mode 100644 index 0000000..1406bda --- /dev/null +++ b/.pre-commit-hooks.yaml @@ -0,0 +1,6 @@ +- id: formatr + name: formatR + description: Uses formatR to format R files + entry: scripts/pre-commit-formatR.R + language: script + files: '.*\.[rR]$' diff --git a/README.md b/README.md index 14bcc1d..af71f82 100644 --- a/README.md +++ b/README.md @@ -14,3 +14,22 @@ to [![R source code after reformatting](https://db.yihui.org/imgur/TBZm0B8.png)](https://yihui.shinyapps.io/formatR/) + +## Pre-commit Hook + +formatR is available as a pre-commit hook. Note that, to use this, `formatR` and `docopt` must be installed in the system R library; the hook does not install anything itself. + +The following arguments are available: + +``` +Options: + --no-comments Remove comments. + --no-blanks Remove blank lines. + --arrow If given, arrows will not be substituted for = signs. + --pipe If given, pipes will not be changed. + --brace-newline If given, braces will not be put on new lines. + --indent=INDENT Number of indents. [default: 4] + --no-wrap Skip wrapping the text. + --width-cutoff=WIDTH Text width cutoff. [default: 80] + --args-newline If TRUE, arguments are started on a new line after a function call. [default: FALSE] +``` diff --git a/scripts/pre-commit-formatR.R b/scripts/pre-commit-formatR.R new file mode 100755 index 0000000..fb733dc --- /dev/null +++ b/scripts/pre-commit-formatR.R @@ -0,0 +1,31 @@ +#!/usr/bin/env Rscript + +library(docopt) +library(formatR) + +doc <- " +Usage: + pre-commit-formatR.R [options] ... + +Options: + --no-comments Remove comments. [default: FALSE] + --no-blanks Remove blank lines. [default: FALSE] + --arrow If FALSE, arrows will not be substituted for = signs. [default: FALSE] + --pipe If FALSE, pipes will not be changed. [default: FALSE] + --brace-newline If FALSE, braces will not be put on new lines. [default: FALSE] + --indent=INDENT Number of indents. [default: 4] + --no-wrap Skip wrapping the text. [default: TRUE] + --width-cutoff=WIDTH Text width cutoff. [default: 80] + --args-newline If TRUE, arguments are started on a new line after a function call. [default: FALSE] +" + +args <- docopt(doc) + +for (source_file in args[["files"]]) { + formatR::tidy_source(source = source_file, file = source_file, comment = !args[["--no-comments"]], + blank = !args[["--no-blanks"]], arrow = args[["--arrow"]], pipe = args[["--pipe"]], + brace.newline = args[["--brace-newline"]], indent = as.integer(args[["--indent"]]), + wrap = !args[["--no-wrap"]], width.cutoff = as.integer(args[["--width-cutoff"]]), + args.newline = args[["--args-newline"]])$text + +}