build: add a small standalone utility for calculating md5/sha256 hash
[openwrt/openwrt.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 REBOOT=ee53a240ac902dc83209008a2671e7fdcf55957a
16 git rev-parse --git-dir >/dev/null 2>&1 || return 1
17
18 [ -n "$GET_REV" ] || GET_REV="HEAD"
19
20 case "$GET_REV" in
21 r*)
22 GET_REV="$(echo $GET_REV | tr -d 'r')"
23 BASE_REV="$(git rev-list ${REBOOT}..HEAD | wc -l | awk '{print $1}')"
24 REV="$(git rev-parse HEAD~$((BASE_REV - GET_REV)))"
25 ;;
26 *)
27 BRANCH="$(git rev-parse --abbrev-ref HEAD)"
28 ORIGIN="$(git rev-parse --verify --symbolic-full-name ${BRANCH}@{u} 2>/dev/null)"
29 [ -n "$ORIGIN" ] || ORIGIN="$(git rev-parse --verify --symbolic-full-name master@{u} 2>/dev/null)"
30 REV="$(git rev-list ${REBOOT}..$GET_REV | wc -l | awk '{print $1}')"
31
32 if [ -n "$ORIGIN" ]; then
33 UPSTREAM_BASE="$(git merge-base $GET_REV $ORIGIN)"
34 UPSTREAM_REV="$(git rev-list ${REBOOT}..$UPSTREAM_BASE | wc -l | awk '{print $1}')"
35 else
36 UPSTREAM_REV=0
37 fi
38
39 if [ "$REV" -gt "$UPSTREAM_REV" ]; then
40 REV="${UPSTREAM_REV}+$((REV - UPSTREAM_REV))"
41 fi
42
43 REV="${REV:+r$REV-$(git log --format="%h" -1)}"
44 ;;
45 esac
46
47 [ -n "$REV" ]
48 }
49
50 try_hg() {
51 [ -d .hg ] || return 1
52 REV="$(hg log -r-1 --template '{desc}' | awk '{print $2}' | sed 's/\].*//')"
53 REV="${REV:+r$REV}"
54 [ -n "$REV" ]
55 }
56
57 try_version || try_git || try_hg || REV="unknown"
58 echo "$REV"