前置条件
假设已经安装有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三
clang-format
clang-format是一个由 Clang 项目提供的工具,主要用于格式化 C、C++、Objective-C、Java 等编程语言的代码。它能依据预设规则自动调整代码的格式,让代码风格统一、可读性增强。
主要特点
- 支持多种代码风格:clang-format支持多种常见的代码风格,像 Google、LLVM、Chromium、Mozilla 等。你也可以自定义代码风格,以契合项目的特定需求。
- 集成性良好:它能和多种集成开发环境(IDE)与文本编辑器集成,例如 Visual Studio Code、CLion、Vim、Emacs 等,方便开发者在日常开发中使用。
- 可定制性强:可以通过配置文件对代码格式规则进行细致的调整,涵盖缩进、空格、换行、注释等各个方面。
作者:帅得不敢出门