File: git-sync

package info (click to toggle)
git-extras 7.4.0-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 2,120 kB
  • sloc: sh: 4,312; python: 994; makefile: 146
file content (101 lines) | stat: -rwxr-xr-x 2,393 bytes parent folder | download | duplicates (2)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env bash

function _usage()
{
  local command="git sync"
  cat << EOS
Usage:
  ${command} [<remote> <branch>]
  ${command} -h | --help
  ${command} -s | --soft
  ${command} -f | --force

Sync local branch with <remote>/<branch>.
When <remote> and <branch> are not specified on the command line, upstream of local branch will be used by default.
All changes and untracked files and directories will be removed unless you add -s(--soft).

Examples:
  Sync with upstream of local branch:
    ${command}

  Sync with origin/master:
    ${command} origin master

  Sync without cleaning untracked files:
    ${command} -s

  Sync without interaction:
    ${command} -f
EOS
}

function main()
{
  while [ "$1" != "" ]; do
    case $1 in
      -h | --help)
        _usage
        exit
        ;;
      -s | --soft)
        local soft="true"
        ;;
      -f | --force)
        local force="YES"
        ;;
      * )
        if [ "${remote}" = "" ]; then
          local remote="$1"
        elif [ "${branch}" = "" ]; then
          local branch="$1"
        else
          echo -e "Error: too many arguments.\n"
          _usage
          exit 1
        fi
        ;;
    esac
    shift
  done

  local remote_branch
  if [ -z "${remote}" ]; then
    if ! remote_branch="$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null)"; then
      echo "There is no upstream information of local branch."
      exit 1
    fi
    local branch="$(git rev-parse --abbrev-ref --symbolic-full-name @)"
    local remote=$(git config "branch.${branch}.remote")
  elif [ -z "${branch}" ]; then
    echo -e "Error: too few arguments.\n"
    _usage
    exit 1
  else
    remote_branch="${remote}/${branch}"
  fi

  if [ "${force}" != "YES" ]; then
    if [ "${soft}" = "true" ]; then
      echo -n "Are you sure you want to sync with '${remote_branch}'? [y/N]: "
    else
      echo -n "Are you sure you want to clean all changes & sync with '${remote_branch}'? [y/N]: "
    fi
    local force
    read -r force
  fi
  case "${force}" in
    "Y" | "y" | "yes" | "Yes" | "YES" )
      if [ "${soft}" = "true" ]; then
        git fetch "${remote}" "${branch}" && git reset --hard "${remote_branch}"
      else
        git fetch "${remote}" "${branch}" && git reset --hard "${remote_branch}" && git clean -d -f -x
      fi
      ;;
    * )
      echo "Canceled."
      ;;
  esac
}

main "$@"