未知数据源 2024年11月26日
Avoid committing junk
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍了一种使用 Git Hooks 过滤敏感信息的简单方法。开发过程中,我们经常会编写一些不希望提交到远程服务器的代码,例如调试打印语句。作者提出了一种通过在代码中添加特定字符序列(例如 'xxx')来标记这些临时代码,并利用 Git 的 pre-commit hook 拦截包含这些字符序列的提交。该方法通过正则表达式匹配,在提交前检查代码是否包含这些标记,如果发现则阻止提交,并提示用户移除这些标记。这种方法简单易用,可以有效防止敏感信息被意外提交到远程仓库。

🤔 **使用特殊字符标记敏感信息:** 作者建议在不希望提交的代码行中添加特定字符序列(例如 'xxx'),例如调试打印语句、临时变量或函数等。

🔨 **利用 Git Hooks 拦截提交:** 通过创建 .git/hooks/pre-commit 文件,并编写脚本,使用 git diff --staged 获取即将提交的代码变化,并使用正则表达式匹配是否包含敏感字符序列。

🚫 **阻止包含敏感字符的提交:** 如果脚本检测到代码中包含敏感字符序列,则会退出并返回错误码,阻止提交操作,并提示用户移除这些标记,从而避免敏感信息被意外提交。

🔄 **强制提交选项:** 如果需要提交包含敏感字符序列的文件(例如二进制文件),可以使用 `git commit -n` 强制绕过 pre-commit hook 进行提交。

In the development process every developer writes stuff he doesn't intend to commit and push to the remote server,e.g. debug prints. It happens to all of us every now and then: we forget to remove this temporary stuff before committing...

I solved this somewhat embarrassing situation using a simple approach: to every line I don't want to accidentally commitI add the magic characters sequence xxx. This sequence can be in any part of the line: inside a comment, as a variable name,as a function name, you name it. A few usage examples:

The way I implemented it is using git hooks, which is git's mechanism to fire off custom scripts when certain important actions occur.I used the pre-commit hook for validating the commit's content.

Just create a file with the name .git/hooks/pre-commit with the following content:

#!/bin/shmarks=xxx,aaa,asdmarksRegex=`echo "($marks)" | sed -r 's/,/|/g'`marksMessage=`echo "$marks" | sed -r 's/,/ or /g'`if git diff --staged | egrep -q "^\+.*$marksRegex"; then        echo "You forgot to remove a line containing $marksMessage. You can forecully commit using \"commit -n\""        exit 1fi
    marks contains the characters sequences which are not allowed to be committed.git diff --staged shows the changes which will be committed. The changes pass through a regular expression that searches for any forbidden mark (using egrep).If a forbidden mark is found, the script exits with an error code, causing the commit to fail.

If you want to bypass the hook (e.g. you want to commit a binary file such as an image, which may contain a forbidden mark), you can commit -n.

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Git Hooks 代码提交 敏感信息过滤 pre-commit 正则表达式
相关文章