使用 Spotbug 进行代码审查的预提交脚本

pre commit script for code review using spotbug

提问人:Hitesh Kumar 提问时间:10/11/2023 更新时间:10/25/2023 访问量:52

问:

我正在尝试使用预提交钩子编写代码审查脚本。我正在寻找一个可以在每次提交时运行并使用 SpotBugs 或类似工具执行代码审查的脚本。我已经尝试过 SpotBugs 命令行。我的项目是 Java 8,我使用的是 Windows。谢谢。spotbugs-4.7.3\lib\spotbugs.jar

使用 spotBug 进行代码审查的预提交脚本:

#!/bin/bash
# Run SpotBugs on Java files to check for issues before committing.
# SpotBugs executable location
SPOTBUGS_PATH=/spotbug/path

# your project's source code location
PROJECT_PATH=/your/project
    
echo "SPOTBUGS_PATH: $SPOTBUGS_PATH"
echo "PROJECT_PATH: $PROJECT_PATH"

#Run SpotBugs
$SPOTBUGS_PATH -textui -effort:max -xml=outReport.xml $PROJECT_PATH


# Check for any issues
if [ $? -eq 0 ]; then

  echo "No bugs found."

  exit 0

else

  echo "Bugs found . Commit aborted."

  exit 1

fi

运行此文件后,我得到一个空文件。如果我手动尝试,它会显示大约 600 个错误。寻找正确的脚本来审查和生成 Outfile。

提交文件时出错:

/spotbugs.jar: line 1: $'PK\003\004': command not found
/spotbugs.jar: line 2: $'\b\bA\002': command not found
/spotbugs.jar: line 3: syntax error near unexpected token `)'
/spotbugs.jar: line 3: `A���META-INF/MANIFEST.MFmRۮ�0|����+�};!�D����&�|�|A��ٸ  ͑x�gdz3#�ɪ�~I���C�UY�IY��)��A    �P�*;\��+%+��y�n������,^��|*u�۲�2��t:P0 �1�8b�7�KQ�7Y��ڳ��` z)���EH��*_oB�,b]���m�:��X���fh3�=2��V�k�c-��:�Awg��'�Y�^܍�28�[z�k���@��h�qZI{�1+=�}�n@��e�ce�]\��gʃ1����&�;+I�96�ڍ,'��K��VP�m�s���O�c��b��&?�aj��f�    ?1�,ewXջY)��A���~�0�m@�Y��  g�j|W/):�y�ݐ�{}##O�,�*N�[5�eQPK'
SpotBugs found issues. Commit aborted.
java githooks pre-commit-hook pre-commit spotbugs

评论

0赞 Jorn 10/11/2023
这是你旧问题的副本,但这次写得更好。好!
0赞 Jorn 10/11/2023
您可以尝试使用您的构建系统(可能是 Gradle)运行 Spotbugs 吗?然后,您只需检查进程退出代码即可确定成功。
0赞 Hitesh Kumar 10/11/2023
谢谢@Jorn,我从构建中尝试过,它显示错误,但需要按照要求在提交时进行。
0赞 Jorn 10/11/2023
是的。我的建议是从提交钩子脚本内部运行 Gradle 任务。
0赞 Hitesh Kumar 10/11/2023
是的,我会尝试的谢谢。运行上面的单个命令很简单。知道为什么我收到该错误。

答:

0赞 Hitesh Kumar 10/25/2023 #1

#Run SpotBugs

**java -jar** $SPOTBUGS_PATH -textui -effort:max -xml=outReport.xml $PROJECT_PATH

我们必须使用 java -jar 来执行 spotbug jar 文件。

@knittl您是对的,我们必须使用 java -jar,这需要时间,因为它第一次生成大约 31 MB 的文件。

为了减少下面的文件使用,它减少到 200 kb。

-嵌套:假

整个工作脚本:

#!/bin/sh

# Define the location of your project's source code
PROJECT_PATH=/project/location

# Define the location of the SpotBugs executable
SPOTBUGS_PATH=/spotbug/path

#current Date
NOW=$(date +"%m%d%Y%H%M%S")

echo "SPOTBUGS_PATH: $SPOTBUGS_PATH"
echo "PROJECT_PATH: $PROJECT_PATH"
echo "Current_Date: $NOW"

#Run SpotBugs
java -jar $SPOTBUGS_PATH -textui -effort:max -xml=bugReport_$NOW.xml -nested:false $PROJECT_PATH


# Check if SpotBugs found any issues
if [ $? -eq 0 ]; then

  echo "No SpotBugs issues found."

  exit 0

else

  echo "Found issues"

  exit 1

fi