前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在git提交引入一些代码规范工作

在git提交引入一些代码规范工作

原创
作者头像
mariolu
发布2021-08-30 20:53:35
1.4K0
发布2021-08-30 20:53:35
举报

一、clang-format缩进

格式化程序使用clang-format,代码风格除了预定义的LLVM, GNU, Google, Chromium, Microsoft, Mozilla规则,还可以用file定义的风格。

这里我们基于谷歌的规则进行一些修改成我们项目自己风格。

代码语言:javascript
复制
clang-format --style=Google --dump-config > .clang-format

.clang-format包含了规则。比如谷歌风格缩进是2个空格,我们改成熟悉的4个文件

编辑.clang-format,IndentWidth:的变量设置为4。AccessModifierOffset把-1设置为-3,这个主要是设置cpp的public,private,pretected相对于函数的向左相隔距离。

二、git提交自动格式化

根据git提交特性,可以设置commit前的钩子脚本,这个钩子脚本完成对代码的格式化,

首先可以设置git config hooks.clangformatstyle file。这样规则文件使用工程内的.clang-format文件

我们使用github有大婶开源的hook脚本。

代码语言:javascript
复制
git clone https://github.com/andrewseidl/githook-clang-format.git
cp githook-clang-format/clang-format.hook {你的工程文件夹}/.git/hooks/pre-commit

代码语言:javascript
复制
#钩子函数的逻辑就是去读取本次代提交的差异所在的文件,然后对文件进行clang-format操作。

#!/bin/bash

STYLE=$(git config --get hooks.clangformat.style)
if [ -n "${STYLE}" ] ; then
  STYLEARG="-style=${STYLE}"
else
  STYLEARG=""
fi

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

case "${1}" in
  --about )
    echo "Runs clang-format on source files"
    ;;
  * )
    for file in `git diff-index --cached --name-only HEAD | grep -iE '\.(cpp|cc|h|hpp)$' ` ; do
      format_file "${file}"
    done
    ;;
esac

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、clang-format缩进
  • 二、git提交自动格式化
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com