团队代码规范/格式化工具clang-format三git commit自动格式化代码

前置条件

假设已经安装有clang-format,及配置出了.clang-format配置文件
.clang-format放在源码项目中的最上层目录

创建git hook

目的是在git 中commit时,自动格式化提交改变的文件
git管理的项目中新建
.git/hooks/pre-commit

#!/bin/bash

STYLE=$(git config --get hooks.clangformat.style)
if [ -n "${STYLE}" ] ; then
    STYLEARG="-style=${STYLE}"
else
    # try source root dir
    STYLE=$(git rev-parse --show-toplevel)/.clang-format
    if [ -n "${STYLE}" ] ; then
        STYLEARG="-style=file"
    else
        STYLEARG=""
    fi
fi

format_file() {
    file="${1}"
    if [ ! -z "${STYLEARG}" ]; then
        #echo "format ${file}"
        clang-format -i ${STYLEARG} ${1}
        git add ${1}
    fi
}

# 注意这里对格式化的文件做了限制,test文件目录下的文件不格式化,另外非.cpp/.h的文件不格式化,可自行修改
is_need_format() {
    need=1
    file=$1

    // ignore /test/*
    if [[ "${file}" == */test/* ]]; then
        need=0
    fi

    if [[ $need -eq 1 ]]; then
        # only c/c++ source file
        if [ x"${file##*.}" != x"cpp" -a x"${file##*.}" != x"h" ]; then
            #echo "not cpp source"
            need=0
        fi
    fi

    return $need
}

case "${1}" in
    --about )
        echo "Runs clang-format on source files"
        ;;
    * )
        for file in `git diff-index --cached --name-only HEAD` ; do
            is_need_format ${file}
            if [[ $? -eq 1 ]]; then
                format_file "${file}"
            fi
        done
        ;;
esac

使用

在你修改源码后,然后调用commit时,会自动调用clang-format对你修改的c++源码文件进行格式化, 如果是整个团队要用的话,可以.clang-format放在项目顶层目录中,然后写个脚本,
自动在每个用户的.git/hooks/中创建pre-commit文件,因为.git中的东西无法更新到远程项目中,所以需要显式地创建它。这样就能保证所有成员提交的代码格式是一致的。
团队代码规范/格式化工具clang-format一
团队代码规范/格式化工具clang-format二
团队代码规范/格式化工具clang-format三
作者:帅得不敢出门

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值