Page MenuHomePhabricator

git-clang-format: Add new --staged option.
AcceptedPublic

Authored by lodato on Dec 12 2017, 5:41 PM.

Details

Summary

This new mode, which requires --diff, operates very similarly to the two <commit> mode, except that the stage is formatted instead of the second commit.

The main intent of this feature is to use in pre-commit hooks so that you can ensure that all commits are properly formatted. Without this, the commit hook would have to format the working directory which is not necessarily what will be committed.

This mode requires --diff because otherwise there would be no place for the update to be written to: writing to the index would blow away changes, and writing to the working directory would be incorrect in case the working directory differs from the index.

Note: this patch was forked from D15465.

Testing of all three modes:

# setup
$ mkdir tmp
$ cd tmp
$ git init
$ cat > foo.cc
int main() {
  int x =  1;
  return 0;
}
EOF
$ git add foo.cc
$ git commit -m 'initial commit'
$ rm foo.cc
$ cat > foo.cc
int main() {
  int x =  1;
  int y =  2;
  int z =  3;
  return 0;
}
EOF
$ git add foo.cc
$ git commit -m 'commit 2'
$ sed -i -e 's/1;/10;/' foo.cc
$ git add foo.cc
$ sed -i -e 's/10;/1;/' foo.cc
$ sed -i -e 's/3;/30;/' foo.cc

$ git-clang-format --diff
diff --git a/foo.cc b/foo.cc
index cb2dbc9..2e1b0e1 100644
--- a/foo.cc
+++ b/foo.cc
@@ -1,6 +1,6 @@
 int main() {
   int x =  1;
   int y =  2;
-  int z =  30;
+  int z = 30;
   return 0;
 }
$ git-clang-format --diff --staged
diff --git a/foo.cc b/foo.cc
index 3ea8c6c..7da0033 100644
--- a/foo.cc
+++ b/foo.cc
@@ -1,5 +1,5 @@
 int main() {
-  int x =  10;
+  int x = 10;
   int y =  2;
   int z =  3;
   return 0;
$ git-clang-format --diff HEAD~ HEAD
diff --git a/foo.cc b/foo.cc
index 7bfdb83..ce6f65e 100644
--- a/foo.cc
+++ b/foo.cc
@@ -1,6 +1,6 @@
 int main() {
   int x =  1;
-  int y =  2;
-  int z =  3;
+  int y = 2;
+  int z = 3;
   return 0;
 }

Diff Detail