版权声明:本文系作者原创。未经许可,不得转载。
在git中,有一个脚本pre-commit可以在git comit之前,进行一些操作,比如对代码进行预检查等。
本脚本,利用ubuntu自带的cppcheck对代码进行提交前预检查。检查有误,则不能提交。
使用方式如下:
1、安装cppcheck
sudo apt-get install cppcheck
2、将附件复制到项目中.git/hooks目录下并修改权限。 以cmos-qmlplugin-multimedia-photos为例,执行:
cp cmos-pre-commit 目录/cmos-qmlplugin-multimedia-photos/.git/hooks/
chmod 755 目录/cmos-qmlplugin-multimedia-photos/.git/hooks/cmos-pre-commit
3、将git自带的pre-commit.sample复制一份,并添加一行代码:
cp目录/cmos-qmlplugin-multimedia-photos/.git/hooks/pre-commit.sample 目录/cmos-qmlplugin-multimedia-photos/.git/hooks/pre-commit
echo "./cmos-pre-commit" >>目录/cmos-qmlplugin-multimedia-photos/.git/hooks/pre-commit
cmos-pre-commit的源码如下:
#
# This file is part of cmos git
#
# Copyright (C) 2014 Beijing Yuan Xin Technology Co.,Ltd. All rights reserved.
#
# Authors:
# Peng Huaping <penghuaping@syberos.com>
#
# This software, including documentation, is protected by copyright controlled
# by Beijing Yuan Xin Technology Co.,Ltd. All rights are reserved.
#
#!/bin/sh
DATE=/bin/date
GIT=/usr/bin/git
SED=/bin/sed
AWK=/usr/bin/awk
TOUCH=/usr/bin/touch
CPPCHECK=/usr/bin/cppcheck
CAT=/bin/cat
ECHO=/bin/echo
RM=/bin/rm
WC=/usr/bin/wc
current_date=`$DATE +%Y%m%d%H%M%S`
commit_file=/tmp/file_$current_date.tmp
check_file=/tmp/fliter_file_$current_date.tmp
check_log_file=/tmp/precheck_$current_date.log
$TOUCH $commit_file
$GIT status -s | $SED -n '/^[M,A]/p' | $AWK '{print $2}' > $commit_file
$TOUCH $check_file
#只对扩展名为cpp、h、cc、hpp、c进行检查
$SED -n '/\<cpp\>$/p' $commit_file >> $check_file
$SED -n '/\<c\>$/p' $commit_file >> $check_file
$SED -n '/\<cc\>$/p' $commit_file >> $check_file
$SED -n '/\<h\>$/p' $commit_file >> $check_file
$SED -n '/\<hpp\>$/p' $commit_file >> $check_file
check_count=`$CAT $check_file | $WC -l`
if [ $check_count != 0 ]; then
$TOUCH $check_log_file
for file in `$CAT $check_file`
do
$CPPCHECK --enable=style,performance,portability,unusedFunction --quiet --template=gcc $file 2>> $check_log_file
done
precheck_count=`$CAT $check_log_file | $WC -l`
if [ $precheck_count = 0 ]; then
$ECHO "代码检查通过!"
else
$ECHO "代码检查没有通过!"
$ECHO "原因如下:"
$CAT $check_log_file
exit 1
fi
fi
$RM -f $commit_file
$RM -f $check_file
$RM -f $check_log_file
参考资料:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。