git预提交钩子代码格式与部分提交? [英] git pre-commit hook code formatting with partial commit?

查看:868
本文介绍了git预提交钩子代码格式与部分提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来预先提交钩子自动格式化的代码(对于
例如 astyle ),但不是 / em>销毁部分提交?



工作流程:

 #编辑一个file.txt 
git add -p file.txt
#添加一个块,但不是另一个

git commit -m'一条消息'
[PRE_COMMIT_HOOK ]格式化源代码

git status
#另一个块尚未添加

我的问题是,如果你在脚本格式化之前需要
的pre-commit钩子内执行 git add 源代码,也添加了另一个块,
。但是我不希望那样。

有没有办法实现这个目的?

解决方案

我会用低级别的plumbing命令来做这件事,我的第一次尝试是沿着

  git ls-files --stage \ * .c |同时读取模式对象的舞台路径; 



$ b $ format $ = $ g $ show $ object |缩进| git hash-object -w --stdin`
git update-index --cacheinfo $ mode $ formatted$ path
;;
esac
完成

为避免冗余处理,请从 git diff-index --name-only --diff-filter = AM 输出为@torek建议。


is there a way to have a pre-commit hook which auto-formats the code (for example with astyle) but does not destroy a partial commit?

Workflow:

# edit a file.txt
git add -p file.txt
# add one chunk, but not another

git commit -m 'a message'
[PRE_COMMIT_HOOK] Formatting source code

git status
# the "another" chunk is still not added

My problem is, that if you do a git add inside the pre-commit hook, which is required after the script formatted the source code, adds the "another" chunk, too. But I don't want that.

Is there a way to achieve this?

解决方案

I'd do this by doing the work with the low-level "plumbing" commands, my first attempt would be something along the lines of

git ls-files --stage \*.c | while read mode object stage path; do
case $mode in
10*)
      formatted=`git show $object | indent | git hash-object -w --stdin`
      git update-index --cacheinfo $mode $formatted "$path"
;;
esac
done

To avoid redundant processing, start from git diff-index --name-only --diff-filter=AM output as @torek suggests.

这篇关于git预提交钩子代码格式与部分提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆