/
git-up
executable file
·76 lines (65 loc) · 2.19 KB
/
git-up
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#! /usr/bin/env bash
# Objective:
# rebase a git repository to the remote.
# Requirement:
# It should work even if there are any uncommitted changes in the local repository.
# If the repository needs a push or if it has diverged, then inform about it but
# do not update the local repository.
#
# This script is adapted from the code snippet in
# https://stackoverflow.com/a/3278427/6305733 .
# Check the link to understand how it works.
# set -x
function do_pull()
{
# --autostash is available only if git version is >= 2.6
local git_version=`git --version | cut -f3 -d' '`
local major_version=`echo $git_version | cut -f1 -d.`
local minor_version=`echo $git_version | cut -f2 -d.`
if (( $major_version >= 2 )) && (( $minor_version >= 6 )); then
local use_autostash=1
else
local use_autostash=0
fi
if [ $use_autostash == 1 ]; then
# In git 2.23.0, the command
# git pull --rebase --autostash -v origin
# is throwing a warning such as
# You are in 'detached HEAD' state. ...
# This warning does not show up if we use git 2.20.1. So it must have
# been added some time after that.
# I am using '-c advice.detachedHead=false' to suppress the warning.
git -c advice.detachedHead=false pull --rebase --autostash -v origin
else
git stash
git pull --rebase -v origin
git stash pop
fi
}
git rev-parse @ > /dev/null 2>&1
if [[ $? == 128 ]]; then
echo "Not a git repository. Exiting."
exit 1
fi
git remote update
UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
if [ $LOCAL = $REMOTE ]; then
echo "Up-to-date"
elif [ -z $BASE ] || [ $LOCAL = $BASE ]; then
# The "-z $BASE" checks if the BASE variable is empty. If it is empty then
# pull the latest version. This happens, for example, when trying to
# update a local copy of <https://github.com/stamparm/ipsum>.
echo "Need to pull"
do_pull
NEWLOCAL=$(git rev-parse @)
if [ $NEWLOCAL = $REMOTE ]; then
echo "Pull successful"
fi
elif [ $REMOTE = $BASE ]; then
echo "Need to push"
else
echo "Diverged"
fi