前置條件
假設已經安裝有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三
作者:帥得不敢出門