Skip to content

Commit b762658

Browse files
authored
Merge pull request mybatis#3381 from epochcoder/feat/add-pre-commit-hook
feat: ensure code is formatted and imports are sorted before commit
2 parents a7c4102 + d38acff commit b762658

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

hooks/pre-commit.sh

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/env bash
2+
#
3+
# Copyright 2009-2025 the original author or authors.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# https://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
#
17+
set -eo pipefail
18+
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
25+
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

pom.xml

+19
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@
7878
<mockito.version>5.15.2</mockito.version>
7979
<mssql-jdbc.version>12.8.1.jre11</mssql-jdbc.version>
8080
<testcontainers.version>1.20.4</testcontainers.version>
81+
<git-build-hook.version>3.5.0</git-build-hook.version>
8182

8283
<!-- Add slow test groups here and annotate classes similar to @Tag('groupName'). -->
8384
<!-- Excluded groups are ran on github ci, to force here, pass -d"excludedGroups=" -->
@@ -431,6 +432,24 @@
431432
</rules>
432433
</configuration>
433434
</plugin>
435+
436+
<plugin>
437+
<groupId>com.rudikershaw.gitbuildhook</groupId>
438+
<artifactId>git-build-hook-maven-plugin</artifactId>
439+
<version>${git-build-hook.version}</version>
440+
<configuration>
441+
<installHooks>
442+
<pre-commit>hooks/pre-commit.sh</pre-commit>
443+
</installHooks>
444+
</configuration>
445+
<executions>
446+
<execution>
447+
<goals>
448+
<goal>install</goal>
449+
</goals>
450+
</execution>
451+
</executions>
452+
</plugin>
434453
</plugins>
435454
</build>
436455

0 commit comments

Comments
 (0)