Git中代码预检查

版权声明:本文系作者原创。未经许可,不得转载。

                                
    在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




参考资料:
  1. http://gitbook.liuhui998.com/5_8.html

  2. http://cppcheck.sourceforge.net/manual.pdf

  3. http://www.douban.com/note/245204752/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值