Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

git - How can I avoid an accidental dcommit from a local branch

Sometimes, I create local branches in git, and I'd like to get a warning message when I try to dcommit from them.

How can I prevent myself from accidentally dcommiting from a local branch?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An alternative to pre-commit hooks, if you're using Linux (or Git bash or Cygwin or similar), is to wrap git in a shell helper function. Add the below to your ~/.bashrc (for bash, Git bash) or ~/.zshrc (for zsh) file, or whatever the equivalent is for your 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 "$@"
}

(I've tested this with bash and zsh on Red Hat, and bash on Cygwin)

Whenever you call git, you'll now be calling this function rather than the normal binary. The function will run git normally, unless you're calling git svn dcommit while attached to a branch that's not master. In that case, it'll prompt you to confirm before doing the commit. You can override the function by specifying the path to git explicitly (that's what the $real_git is doing).

Remember that after updating ~/.bashrc or equivalent, you'll need to reload it, either by starting a new shell session (logging out and logging in again) or by running source ~/.bashrc.

Edit: As an enhancement, you can remove the first line, starting real_git=, and replace the other instances of $real_git with command git, which achieves the same thing but in the preferred way. I've not updated the script itself as I've not been able to test the change on zsh.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...