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?
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.
First thing that comes in mind is using a git pre-commit hook to solve the problem. This would be easy for pure git repos:
- Lock remote branches (update hook): Is there a way to lock a branch in GIT
- Lock local branches (pre-commit hook): Locking a branch, so that it cannot be staged/committed into? (Only merged/etc)
But as discussed in Hooks for git-svn, this isn't fully working. VonC came up with an (accepted) answer where he utilizes an intermediate bare repo that acts like kind of a proxy between git ans SVN.
Maybe this could help you too.
In case anyone else needs this for 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"
来源:https://stackoverflow.com/questions/9226528/how-can-i-avoid-an-accidental-dcommit-from-a-local-branch