Add syntax check before pushing code
[dmaap/datarouter.git] / ci_scripts / pre-commit.sh
1 #!/usr/bin/env bash
2 #
3 # ============LICENSE_START=======================================================
4 #  Copyright (C) 2019 Nordix Foundation.
5 # ================================================================================
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 #      http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # SPDX-License-Identifier: Apache-2.0
19 # ============LICENSE_END=========================================================
20 #
21 # Pre-commit hook for running checkstyle on changed Java sources
22 #
23 # To use this you need:
24 # 1. Checkstyle's jar file downloaded *version is important checkstyle-8.13-all.jar
25 # 2. To configure git:
26 #   * git config --add checkstyle.jar <location_of_jar>
27 # 3. Copy this file to your .git/hooks directory as pre-commit
28 #
29 # Now, when you commit, you will be disallowed from doing so
30 # until you pass your checkstyle checks.
31
32 changed_files=" "
33 for file in $(git diff --cached --name-status | grep -E '\.(java)$' | grep -vE '^D' | awk '{print $2}')
34 do
35   changed_files+="$file "
36 done
37
38 printf "Using checkstyle sheet "
39 checkstlye_jar_command='git config --get checkstyle.jar'
40
41 if ! ($checkstlye_jar_command)
42 then
43   printf "You must configure checkstyle in your git config"
44   exit 1
45 fi
46
47 checkstyle_warnings=$(java -jar $($checkstlye_jar_command) -c ci_scripts/onap-style-java.xml $changed_files | grep WARN)
48 if [ $? == 0 ]
49 then
50   printf "\nWarnings found\n\n"
51   echo "$checkstyle_warnings"
52   printf "\n###############################################################\n\nFix warnings before committing\n\n"
53   exit 1
54 else
55   printf "\nCode checkstyle passed.\n"
56 fi