Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
greg0ire Avatar asked Feb 10 '12 10:02

greg0ire


1 Answers

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.

like image 120
me_and Avatar answered Sep 26 '22 01:09

me_and