I'm trying to setup a local pre-commit hook. It should check if any edited files are styled according to the tidyverse styleguide (using styler). Because my company does not allow for direct access to github, I cannot use precommit, and have to setup the hook by editing the .git/hooks/pre-commit file.
Setup
This is what I tried: My .git/hooks/pre-commit
#!/bin/bash
set -eo pipefail
CHANGED_FILES=$(git diff --name-only --cached --diff-filter=ACMR)
get_pattern_files() {
pattern=$(echo "$*" | sed "s/ /\$\\\|/g")
echo "$CHANGED_FILES" | { grep "$pattern$" || true; }
}
R_FILES=$(get_pattern_files .R)
# if R_FILES is not empty, run Rscript
if [[ -n "$R_FILES" ]]
then
Rscript ./style.R $R_FILES
fi
# exit with 1, if Rscript failed
if [ $? -eq 0 ]; then
exit 0
else
exit 1
fi
and my ./style.R
#!/usr/bin/env Rscript
args <- commandArgs(trailingOnly = TRUE)
output <- styler::style_file(path = args)
if (any(output$changed) == TRUE) {quit(status = 1)}
Problem
When I edit a file, I can see it in the diff.
user@machine:~/r_template$ git diff
diff --git a/src/main.R b/src/main.R
index 8d2f097..dd1272d 100644
--- a/src/main.R
+++ b/src/main.R
@@ -1 +1 @@
-1 + 1
+1 +1 <-- this is what I have changed in the file
I add it with git add -u and then git commit. The hook gets called, and aborts the commit (because the Rscript exits with status 1) as expected.
user@machine:~/r_template$ git commit
Styling 1 files:
src/main.R ℹ
────────────────────────────────────────
Status Count Legend
✓ 0 File unchanged.
ℹ 1 File changed.
x 0 Styling threw an error.
────────────────────────────────────────
Please review the changes carefully!
and can see an (expected) edited file
user@machine:~/r_template$ git status
On branch feature/precommit-hooks
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: src/main.R
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: src/main.R
with the intended changes done by styler::style_file()
user@machine:~/r_template$ git diff
diff --git a/src/main.R b/src/main.R
index dd1272d..8d2f097 100644
--- a/src/main.R
+++ b/src/main.R
@@ -1 +1 @@
-1 +1
+1 + 1 <-- this is done by styler::style_file()
Ok, so next I want to stage this edit, so I git add -u. But then something happens I cannot understand
utxkanal@vlx00950:~/r_template$ git status
On branch feature/precommit-hooks
nothing added to commit but untracked files present (use "git add" to track)
The staging area is completely empty. And still, the change in src/main.R is in effect.
What is happening here?