scripts/getver.sh: try to get branch/upstream automatically
[lede.git] / scripts / getver.sh
1 #!/usr/bin/env bash
2 export LANG=C
3 export LC_ALL=C
4 [ -n "$TOPDIR" ] && cd $TOPDIR
5
6 GET_REV=$1
7
8 try_version() {
9         [ -f version ] || return 1
10         REV="$(cat version)"
11         [ -n "$REV" ]
12 }
13
14 try_git() {
15         git rev-parse --git-dir >/dev/null 2>&1 || return 1
16
17         [ -n "$GET_REV" ] || GET_REV="HEAD"
18
19         case "$GET_REV" in
20         r*)
21                 GET_REV="$(echo $GET_REV | tr -d 'r')"
22                 BASE_REV="$(git rev-list reboot..HEAD | wc -l)"
23                 REV="$(git rev-parse HEAD~$((BASE_REV - GET_REV)))"
24                 ;;
25         *)
26                 BRANCH="$(git rev-parse --abbrev-ref HEAD)"
27                 ORIGIN="$(git rev-parse --symbolic-full-name ${BRANCH}@{u} 2>/dev/null)"
28                 [ -n "$ORIGIN" ] || ORIGIN="$(git rev-parse --symbolic-full-name master@{u} 2>/dev/null)"
29                 REV="$(git rev-list reboot..$GET_REV | wc -l | awk '{print $1}')"
30
31                 if [ -n "$ORIGIN" ]; then
32                         UPSTREAM_BASE="$(git merge-base $GET_REV $ORIGIN)"
33                         UPSTREAM_REV="$(git rev-list reboot..$UPSTREAM_BASE | wc -l | awk '{print $1}')"
34                 else
35                         UPSTREAM_REV=$REV
36                 fi
37
38                 if [ "$REV" -gt "$UPSTREAM_REV" ]; then
39                         REV="${UPSTREAM_REV}+$((REV - UPSTREAM_REV))"
40                 fi
41
42                 REV="${REV:+r$REV}"
43                 ;;
44         esac
45
46         [ -n "$REV" ]
47 }
48
49 try_hg() {
50         [ -d .hg ] || return 1
51         REV="$(hg log -r-1 --template '{desc}' | awk '{print $2}' | sed 's/\].*//')"
52         REV="${REV:+r$REV}"
53         [ -n "$REV" ]
54 }
55
56 try_version || try_git || try_hg || REV="unknown"
57 echo "$REV"