aboutsummaryrefslogtreecommitdiff
path: root/check
blob: 08b709167bf1cb39b39bb768508c6e93a34620f5 (plain)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#! /usr/bin/env bash

# Check git repository for various things:
#
# master    - check the current branch is master
# clean     - check for untracked files/uncommitted changes
# synced    - check that local and origin are in sync (push/pull)
# submodule - check submodules are synced
#
# Usage: check [--master] [--clean] [--synced] [--submodule] [<dir>]
#
usage="usage: $0 [--master] [--clean] [--synced] [--submodule] [<dir>]"

trap 'exit 1' ERR

function info () { echo "$*" 1>&2; }
function error () { info "$*"; exit 1; }

dir=.
master=n
submod=n
clean=n
synced=n

while [ $# -gt 0 ]; do
  case $1 in
    --master)
      master=y
      shift
      ;;
    --submodule)
      submod=y
      shift
      ;;
    --clean)
      clean=y
      shift
      ;;
    --synced)
      synced=y
      shift
      ;;
    *)
      dir=$1
      break
      ;;
  esac
done

function branch () # <dir>
{
  git -C $1 rev-parse --symbolic-full-name --abbrev-ref HEAD
}

function synced () # <dir> <branch>
{
  git -C $1 fetch

  local r=`git -C $1 rev-parse --verify $2`
  local or=`git -C $1 rev-parse --verify origin/$2`

  if [ "$r" != "$or" ]; then
    return 1
  fi
}

r=0

if [ "$master" = "y" ]; then
  br=`branch $dir`

  if [ "$br" != "master" ]; then
    info "current branch in $dir is $br, not master"
    r=1
  fi
fi

function submod () # <dir>
{
  # The --recursive option doesn't produce the complete path so we will
  # have to recurse ourselves.
  #
  local sms=`git -C $1 submodule foreach --quiet 'echo -n "$path "'`

  #info "checking '$sms' in $1..."

  local sm=
  for sm in $sms; do
    local smd=$1/$sm

    #info "sumbodule '$sm' in '$smd'"

    local br=`branch $smd`

    if ! synced $smd $br; then
      info "submodule $smd is not updated"
      return 1
    fi

    if ! submod $smd; then
      return 1
    fi
  done
}

if [ "$submod" = "y" ]; then
  if ! submod $dir; then
    r=1
  fi
fi

if [ "$clean" = "y" ]; then
  if git -C $dir status --porcelain | grep -q "^?? "; then
    info "untracked files in $dir"
    r=1
  fi

  if git -C $dir status --porcelain | grep -q "^ M "; then
    info "unstaged changes in $dir"
    r=1
  fi

  if git -C $dir status --porcelain | grep -q "^M "; then
    info "staged changes in $dir"
    r=1
  fi
fi

if [ "$synced" = "y" ]; then
  br=`branch $dir`

  if ! synced $dir $br; then
    info "$br and origin/$br in $dir differ, not synced"
    r=1
  fi
fi

exit $r