illwieckz

git-describe-always

Feb 21st, 2022 (edited)
328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.40 KB | None | 0 0
  1. #! /usr/bin/env bash
  2.  
  3. # Author:  Thomas DEBESSE <dev@illwieckz.net>
  4. # License: MIT
  5.  
  6. set -e
  7. set -u
  8.  
  9. delta='false'
  10. case "${1:-}" in
  11.     '-d'|'--delta')
  12.         delta='true'
  13.         shift
  14.         ;;
  15. esac
  16.  
  17. ref="${1:-HEAD}"
  18.  
  19. version="$(git describe --tags --match 'v[0-9]*' "${ref}" 2>/dev/null || true)"
  20.  
  21. if [ -n "${version}" ]
  22. then
  23.     if "${delta}"
  24.     then
  25.         tag="$(git describe --tags --abbrev=0 --match 'v[0-9]*')"
  26.  
  27.         if [ "${tag}" = "${version}" ]
  28.         then
  29.             version="$(git tag --contains "${ref}" 2>/dev/null | egrep '^v[0-9].*' | head -n1)"
  30.         fi
  31.     fi
  32. else
  33.     echo 'warning: no tag found' >&2
  34.     tag='0'
  35.  
  36.     count="$(git rev-list --count "${ref}" 2>/dev/null || true)"
  37.     count="${count:-0}"
  38.  
  39.     id="$(git rev-list --abbrev-commit --abbrev=9 -n1 "${ref}" 2>/dev/null || true)"
  40.     if [ -n "${id}" ]
  41.     then
  42.         id="g${id}"
  43.     else
  44.         echo 'warning: no commit found' >&2
  45.         id="$(date --utc '+%Y%m%d-%H%M%S')"
  46.     fi
  47.  
  48.     version="${tag}-${count}-${id}"
  49. fi
  50.  
  51. if ! git status >/dev/null 2>&1
  52. then
  53.     if [ "${ref}" != 'HEAD' ]
  54.     then
  55.         echo 'error: not a git repository' >&2
  56.         exit 1
  57.     fi
  58.  
  59.     echo 'warning: not a git repository' >&2
  60.     version+='0'
  61. elif ! git diff --quiet 2>/dev/null
  62. then
  63.     echo 'warning: uncommited changes' >&2
  64.     version+='-dirty'
  65. elif ! git ls-files --other --directory --exclude-standard 2>/dev/null | sed q1 >/dev/null
  66. then
  67.     echo 'warning: untracked files' >&2
  68.     version+='-dirty'
  69. fi
  70.  
  71. echo "${version}"
  72.  
Add Comment
Please, Sign In to add comment