9

有时,我在 git 中创建本地分支,当我尝试从它们 dcommit 时,我想收到一条警告消息。

如何防止自己从本地分支意外提交?

4

3 回答 3

8

如果您使用的是 Linux(或 Git bash 或 Cygwin 或类似工具),则预提交挂钩的替代方法是包装git在 shell 辅助函数中。将以下内容添加到您的~/.bashrc(for bash, Git bash) 或~/.zshrc(for zsh) 文件,或任何与您的 shell 等效的文件:

real_git=$(which git)
function git {
    if [[ ($1 == svn) && ($2 == dcommit) ]]
    then
        curr_branch=$($real_git branch | sed -n 's/\* //p')
        if [[ ($curr_branch != master) && ($curr_branch != '(no branch)') ]]
        then
            echo "Committing from $curr_branch; are you sure? [y/N]"
            read resp
            if [[ ($resp != y) && ($resp != Y) ]]
            then
                return 2
            fi
        fi
    fi
    $real_git "$@"
}

(我在 Red Hat 上用 bash 和 zsh 测试过,在 Cygwin 上用 bash 测试过)

每当您调用git时,您现在将调用此函数而不是普通的二进制文件。该函数将正常运行 git,除非您在git svn dcommit附加到非主分支时调用。在这种情况下,它会在提交之前提示您确认。您可以通过显式指定路径来覆盖该函数git(这就是$real_git正在做的事情)。

请记住,在更新~/.bashrc或等效之后,您需要重新加载它,方法是启动一个新的 shell 会话(注销并再次登录)或运行source ~/.bashrc.

编辑:作为一项改进,您可以删除第一行,开始real_git=,并替换其他实例$real_gitwith command git,这实现了同样的事情,但以首选方式。我没有更新脚本本身,因为我无法在 zsh 上测试更改。

于 2012-02-17T14:52:34.430 回答
2

首先想到的是使用 git pre-commit 钩子来解决问题。这对于纯 git repos 来说很容易:

但是正如Hooks for git-svn中所讨论的,这并没有完全起作用。VonC提出了一个(已接受的)答案,他利用中间的裸仓库,其作用类似于 git 和 SVN 之间的代理。

也许这也可以帮助你。

于 2012-02-13T14:43:32.777 回答
0

如果其他人需要此 Windows Powershell:

    function CallGit
    { 
        if (($args[0] -eq "svn") -And ($args[1] -eq "dcommit")) {
            $curr_branch = &{git branch};
            $curr_branch = [regex]::Match($curr_branch, '\* (\w*)').captures.groups[1].value
            if ($curr_branch -ne "master") {
                Write-Warning "Committing from branch $curr_branch";
                $choice = ""
                while ($choice -notmatch "[y|n]"){
                    $choice = read-host "Do you want to continue? (Y/N)"
                }
                if ($choice -ne "y"){
                    return
                }
            }
        }
        &"git.exe" @args
    }
    Set-Alias -Name git -Value CallGit -Description "Avoid an accidental git svn dcommit on a local branch"
于 2016-09-01T11:05:51.593 回答