Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make "git pull" ask for confirmation when pulling different branch

Tags:

git

linux

When working with many projects and branches at the same time, I occasionally do stupid mistake like pulling into the wrong branch. For example being on branch master I did git pull origin dangerous_code and didn't notice that for quite some time. This small mistake caused a lot of mess.

Is there any way to make git ask for confirmation when I attempt to pull a branch other than branch that is currently checked out? Basically I want it to ask for confirmation if the branch name doesn't match (checked out and the one being pulled).

like image 562
SiliconMind Avatar asked Aug 29 '14 09:08

SiliconMind


Video Answer


1 Answers

For now, I'll focus on how to prompt the user for confirmation before any pull is carried out.

Unfortunately, because there is no such thing as a pre-pull hook, I don't think you can get the actual pull command to directly do that for you. As I see it, you have two options:

1 - Use fetch then merge (instead of pull)

Instead of running git pull, run git fetch, then git merge or git rebase; breaking down pull into the two steps it naturally consists of will force you to double-check what you're about to merge/rebase into what.

2 - Define an alias that asks for confirmation before a pull

Define and use a pull wrapper (as a Git alias) that prompts you for confirmation if you attempt to pull from a remote branch whose name is different from the current local branch.

Write the following lines to a script file called git-cpull.sh (for confirm, then pull) in ~/bin/:

#!/bin/sh

# git-cpull.sh

if [ "$2" != "$(git symbolic-ref --short HEAD)" ]
then
    while true; do
        read -p "Are you sure about this pull?" yn
        case "$yn" in
            [Yy]*)
                git pull $@;
                break
                ;;
            [Nn]*)
                exit
                ;;
            *)
                printf %s\\n "Please answer yes or no."
        esac
    done
else
    git pull $@
fi

Then define the alias:

git config --global alias.cpull '!sh git-cpull.sh'

After that, if, for example, you run

git cpull origin master

but the current branch is not master, you'll be asked for confirmation before any pull is actually carried out.

Example

$ git branch
* master
$ git cpull origin foobar
Are you sure about this pull?n
$ git cpull origin master
From https://github.com/git/git
 * branch            master     -> FETCH_HEAD
Already up-to-date.
like image 140
jub0bs Avatar answered Oct 17 '22 14:10

jub0bs