如何防止使用git hook提交文件(.json)? [英] How can I prevent a file (.json) to be commited with a git hook?

查看:174
本文介绍了如何防止使用git hook提交文件(.json)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止使用git hook提交文件(.json)?

我在服务器上有一个.json.所以我不能使用gitignore.但是现在我不想允许任何人更改(提交)此文件,因为它会破坏某些内容.我想使用本地钩子.

I have a .json which is on the server yet. So I can not use an gitignore. But now I do not want to allow anyone to change this file (commit it) because it would break something. I want to use a local hook.

我什至如何在提交中获取特殊文件?

How can I even get the special file in the commit ?

能否请您给我说明如何实现这一目标?

Could you please give me an instruction how to achieve this ?

感谢您的帮助.

推荐答案

一个pre-commit示例:

#!/bin/bash

ipath="foo/bar.json"
git diff --cached --name-only | if grep -qE "^$ipath$";then
    git reset HEAD -- "$ipath"
    echo "Warning: $ipath is removed from the index. It's not allowed to be committed."
fi

git diff --cached --name-only列出了将要提交的所有已更改文件.如果在列表中找到foo/bar.json,则git reset HEAD -- foo/bar.json会将其从索引中删除,以便不提交而是留在工作树中.

git diff --cached --name-only lists all the changed files that are going to be committed. If foo/bar.json is found in the list, then git reset HEAD -- foo/bar.json removes it from the index so that it's not committed but left in the working tree.

对您来说很好.但是,您不能确保它对其他人有用.例如,其他贡献者可以将其从其本地存储库中删除.您需要的是中央存储库中的pre-receive钩子,即服务器端的钩子.如果传入的提交触摸foo/bar.json,它将拒绝任何推送.

It works fine for you. However you can't ensure it does for others. For example, other contributors may delete it from their local repositories. What you need is a pre-receive hook in the central repository, the one on the server side. It rejects any push if the incoming commits touch foo/bar.json.

一个pre-receive样本:

#!/bin/bash

ipath="foo/bar.json"
zero="0000000000000000000000000000000000000000"

while read old new name;do
    if [ "$zero" == "$old" ];then
        #creating new ref, do something here
        continue
    fi

    if [ "$zero" == "$new" ];then
        #deleting a ref, do something here
        continue
    fi

    #updating a ref, check if the incoming commits touch `foo/bar.json`
    git diff $old..$new --name-only | if grep -qE "^$ipath$";then
        c=$(git log $old..$new --pretty=%H -- $ipath)
        echo "Error: $ipath is changed in:"
        echo $c
        echo "Error: $ipath is not allowed to be committed and pushed."
        exit 1
    fi
done

贡献者在git push之后收到错误消息.他们必须修改提交并删除foo/bar.json的更改,然后再尝试.在pre-receive中,如果需要,您需要处理deleting a refcreating a ref.

The contributors receive the error message after git push. They must amend their commits and remove the changes of foo/bar.json before another try. In pre-receive, you need to deal with deleting a ref and creating a ref if necessary.

这篇关于如何防止使用git hook提交文件(.json)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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