GIT预提交钩子,该钩子在已修改/添加的文件中搜索非UTF-8编码(如果找到,则拒绝提交) [英] GIT pre-commit hook which searches non-UTF-8 encodings among modified/added files (and rejects commit if it finds any)

查看:114
本文介绍了GIT预提交钩子,该钩子在已修改/添加的文件中搜索非UTF-8编码(如果找到,则拒绝提交)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Windows的Git(和TortoiseGit).

I'm using Git for Windows (and TortoiseGit).

我的目标是防止在修改/添加中至少包含一个非UTF-8文件的提交.

My goal is to prevent commits which have at least one non-UTF-8 file among modified/added.

  • 枚举修改/添加的文件:我找到了以下代码

{ git diff --name-only ; git diff --name-only --staged ; }

这是最好的(正确和最简洁的)方法吗?

Is this the best (correct and most concise) approach?

搜索非UTF-8文件:我找到了以下代码

{ git diff --name-only ; git diff --name-only --staged ; } | xargs -I {} bash -c "iconv -f utf-8 -t utf-16 {} &>/dev/null || echo {} - is non-UTF8!"

如果我在我的存储库根文件夹中启动Git Bash,它将起作用(显示每个非UTF-8文件).因此,我已将.git/hooks/pre-commit.sample重命名为.git/hooks/pre-commit并复制粘贴了上面的代码.提交更改后,TortoiseGit提交gui窗口内没有任何特殊显示.因此,似乎预提交的钩子无法正常工作.

If I start Git Bash at my repository root folder - it works (each non-UTF-8 file is displayed). So I've renamed .git/hooks/pre-commit.sample to .git/hooks/pre-commit and copy-pasted the code above. After committing changes nothing special displays inside TortoiseGit commit gui window. So looks like pre-commit hook is not working correctly.

如果存在任何非UTF-8文件,则拒绝提交:显示所有非UTP-8文件后,应拒绝提交.但是我不知道如何执行此操作(显示一些退出代码-但如何?).

Rejecting commit if there is any non-UTF-8 file: After displaying all non-UTP-8 files commit should be rejected. But I have no idea how to do this (show some exit code - but how?).

因此,感谢您的帮助.

推荐答案

所以答案是( phd torek 非常有用):

    git diff --name-only --staged --diff-filter d | xargs -I {} bash -c 
 "iconv -f utf-8 -t utf-16 {} &>/dev/null || { echo {} - is non-UTF8!; exit 1; }"

此代码遍历提交中更改的所有文件(删除的文件除外-即添加,修改,复制和重命名的文件),并检查是否存在任何非UTF8文件.列出所有找到的文件,并且提交被中止.

This code iterates through all files, that changed in commit (except for deleted - i.e. added, modified, copied and renamed) and checks if there is any non-UTF8 file. All found files are listed and commit is aborted.

这篇关于GIT预提交钩子,该钩子在已修改/添加的文件中搜索非UTF-8编码(如果找到,则拒绝提交)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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