Skip to content

Commit d38acff

Browse files
committed
First check if there would be any failures before we format and sort
If there are, automatically sort and format and fail the commit as we cannot reliably tell which files to add back to staging
1 parent d2aa051 commit d38acff

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

hooks/pre-commit.sh

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,22 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616
#
17+
set -eo pipefail
1718

18-
set -e
19+
function format_and_sort() {
20+
# Run the validate and import check commands, suppressing all output and errors
21+
if ! mvn formatter:validate impsort:check > /dev/null 2>&1; then
22+
# If validation failed, fix it by ensuring code is formatted correctly
23+
# and that imports are sorted as some IDEs automatically change it on save
24+
mvn formatter:format impsort:sort
1925

20-
# ensure code is formatted correctly and that imports are sorted as some IDE's automatically change it before commit
21-
mvn formatter:format impsort:sort
26+
# Fail the commit, so the author can re-select what to commit
27+
echo "Formatting and/or import sorting were required. Please check and make another commit."
28+
exit 1
29+
fi
30+
31+
# If no error occurred, print a success message
32+
echo "All files are properly formatted and imports are sorted."
33+
}
34+
35+
format_and_sort

0 commit comments

Comments
 (0)