From b8b3e2abbb8d1ea51254204000b454dd7871543b Mon Sep 17 00:00:00 2001
From: Jelte Fennema <jelte.fennema@microsoft.com>
Date: Mon, 23 Jan 2023 11:14:09 +0100
Subject: [PATCH v2 2/2] Add pgindent pre-commit hook

It's easy to forget to run pgindent before doing a commit, eventhough
most of the time you will want to do it. This adds an (optional)
pre-commit hook that can run pgindent automatically for you whenever you
commit.
---
 src/tools/pgindent/README     | 16 ++++++++++++++++
 src/tools/pgindent/pre-commit | 15 +++++++++++++++
 2 files changed, 31 insertions(+)
 create mode 100755 src/tools/pgindent/pre-commit

diff --git a/src/tools/pgindent/README b/src/tools/pgindent/README
index 103970c1042..9f256505a1a 100644
--- a/src/tools/pgindent/README
+++ b/src/tools/pgindent/README
@@ -157,3 +157,19 @@ may need to be updated to match.
 The perltidy run processes all *.pl and *.pm files, plus a few
 executable Perl scripts that are not named that way.  See the "find"
 rules in pgperltidy for details.
+
+---------------------------------------------------------------------------
+
+Automation
+----------
+
+You can install the pre-commit hook by running:
+
+	cp src/tools/pgindent/pre-commit .git/hooks/pre-commit
+
+This hook will automatically run pgindent on all of the files you are
+commiting. It will abort the commit if it made any changes, so that you can add
+those changes to your commit. If you did not indent this commit on purpose,
+simply run git commit again and it will succeed. If before committing you
+already know you don't want to run pgindent at all you can use the --no-verify
+flag of git commit to skip the hook.
diff --git a/src/tools/pgindent/pre-commit b/src/tools/pgindent/pre-commit
new file mode 100755
index 00000000000..7a61a770719
--- /dev/null
+++ b/src/tools/pgindent/pre-commit
@@ -0,0 +1,15 @@
+#!/bin/sh
+set -eu
+
+files=$(git diff --cached --name-only --diff-filter=ACMR | { grep '\.[ch]$' || true ; })
+if [ "$files" = '' ]; then
+    exit 0
+fi
+
+git diff --cached --name-only --diff-filter=ACMR | grep '\.[ch]$' |\
+    xargs src/tools/pgindent/pgindent --silent-diff \
+    || {
+        echo ERROR: Aborting commit because pgindent was not run
+        git diff --cached --name-only --diff-filter=ACMR | grep '\.[ch]$' | xargs src/tools/pgindent/pgindent
+        exit 1
+    }
-- 
2.34.1

