Skip to content
6 changes: 6 additions & 0 deletions .pre-commit-hooks.yaml
Original file line number Diff line number Diff line change
@@ -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]$'
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
```
31 changes: 31 additions & 0 deletions scripts/pre-commit-formatR.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/env Rscript

library(docopt)
library(formatR)

doc <- "
Usage:
pre-commit-formatR.R [options] <files>...

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

}