使用clang-format实现自动化格式代码

对于我这种代码风格写的比较随意的coder来说,弄一个自动化格式代码的工具很有必要。

本文使用clang-format 以及git 的hook脚本自动实现格式化。

1 我们需要在提交代码前运行格式化脚本

  将下面内容保存到你的工程的.git/hooks/pre-commit 文件中,记得chmod +x pre-commit

#!/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}
    echo "clang-format  ${STYLEARG} -i ${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 '\.(c|cpp|cc|h|hpp)$' ` ; do
      format_file "${file}"
    done
    ;;
esac

2 设置代码风格

你可以使用内置风格:

 git config hooks.clangformat.style LLVM 

也可以按如下方法使用自定义风格:

clang-format --style=WebKit --dump-config > .clang-format
#根据自己需要,编辑 .clang-format
git config hooks.clangformat.style file

注意上面的file 不是个变量,填写的就是file,不用替换成.clang-format 或者其他路径......clang-format 会自动搜索当前路径下的.clang-format 或者_clang-format文件

3 正常的git add git commit 就行了.

  

posted @ 2023-02-16 11:19  光谷中心城打工人  阅读(386)  评论(0)    收藏  举报