【转载】一种git commit前自动格式化的方式

查看原文

简介

这个系列为了解决一个问题:自动化的去管理代码风格和格式

前提:Linux,C语言,Clang

如何在每次commit的时候,将代码风格自动格式化后再提交commit,且格式化的内容必须是本次commit中的内容。

这个需求看似很简单实现,但是做到后来我发现,要把这个需求做完美并没有这么容易

我将一步步的去尝试实现最完美的状态:

  • 自动格式化代码
  • 只格式化staged changes
  • 完整保留changes not staged现场
  • 漂亮的输出Clang干了啥

这里会大量的使用关于Bash脚本和Git的相关知识点

最终版使用方法

目录结构

我会提供一个cpt(c programing tools)的目录,这个目录会放入所有脚本及其依赖的工具,以及一个test工程

~/cpt
├── clang
├── .git_template
│   └── hooks
│       └── pre-commit
└── test_clang
    ├── .clang-format
    └── hello
        ├── main.c
        ├── test_math.c
        └── test_math.h
  • clang 使用的版本是 clang+llvm-9.0.0-x86_64-linux-gnu-ubuntu-16.04
  • .git_template git模版及相关脚本目录
  • test_clang 测试工程

使用方法

集成包:cpt-1.00.tar.gz

#首先将工具解压缩
tar zxvf cpt-1.00.tar.gz
#移动到用户根目录
mv cpt ~
#配置git
git config --global init.templatedir ~/cpt/.git_template
#开始测试使用
cd ~/cpt/test_clang/hello
git init
git add .
git commit -m "init"
#故意将代码格式改错
git add .
git commit -m "test"

注意:如果你的项目已经用git管理,在完成上述步骤后,你只需要将~/cpt/.git_template/hooks/pre-commit文件复制到你对应项目中的.git/hooks目录中即可

cp ~/cpt/.git_template/hooks/pre-commit .git/hooks

猜你喜欢

转载自blog.csdn.net/zhengshifeng123/article/details/106504703