Ver código fonte

Add `version-compare` and use this for git setup

Weiyi Lou 10 anos atrás
pai
commit
407874e8bd
2 arquivos alterados com 36 adições e 29 exclusões
  1. 32 0
      bin/version-compare
  2. 4 29
      zsh/custom/git.zsh

+ 32 - 0
bin/version-compare

@@ -0,0 +1,32 @@
+#!/bin/bash
+set -euo pipefail
+
+# Compare 2 version strings.
+#
+# Requires 2 parameters. Version strings are compared numerically, left to
+# right, field by field.
+#
+# Prints 0 if versions are equal.
+# Prints 1 if first > second.
+# Prints -1 if first < second.
+
+# Split strings on '.'.
+IFS=.
+ver1=(${1:?Usage: version-compare ver1 ver2})
+ver2=(${2:?Usage: version-compare ver1 ver2})
+declare i fields
+
+# Number of version fields to be compared = highest array count.
+[[ ${#ver1[@]} > ${#ver2[@]} ]] && fields=${#ver1[@]} || fields=${#ver2[@]}
+
+# Compare fields until a winner is found.
+for (( i=0; i < $fields; i++ )); do
+  # Use zero for missing fields e.g. when 1.2.3 vs 1.2, one more field needed.
+  (( $i >= ${#ver1[@]} )) && ver1[i]=0
+  (( $i >= ${#ver2[@]} )) && ver2[i]=0
+  # Stop whenever a field value is larger than the other. Compared in base 10.
+  (( 10#${ver1[i]} > 10#${ver2[i]} )) && echo "1" && exit
+  (( 10#${ver1[i]} < 10#${ver2[i]} )) && echo "-1" && exit
+done
+# All fields are equivalent.
+echo "0"

+ 4 - 29
zsh/custom/git.zsh

@@ -1,36 +1,11 @@
-# Check the installed git against a given version number
-#
-# Prints 1 if installed > input.
-# Prints -1 if installed < input.
-# Prints 0 if they are the same.
-function git_compare_version() {
-  # Sanitise input. Remove dots, right-pad 0's to 3 digits.
-  INPUT=${1//./}
-  INPUT=$(echo $INPUT | sed -e '
-    :again
-    s/^.\{1,2\}$/&0/
-    t again'
-  )
-  # Sanitise installed version to 3 digits as well.
-  # The raw version string takes the form 'git version 1.2.3...'
-  INSTALLED=$(git --version 2> /dev/null)
-  INSTALLED=${INSTALLED:12:5}
-  INSTALLED=${INSTALLED//./}
-
-  if [[ $INSTALLED -gt $INPUT ]]; then
-    echo 1
-  elif [[ $INSTALLED -lt $INPUT ]]; then
-    echo -1
-  else
-    echo 0
-  fi
-  return 0
-}
+# Git version string
+GIT_VERSION=$(git --version 2> /dev/null)
+GIT_VERSION=${GIT_VERSION:12}
 
 # Prepare compact git log (`gl`) format
 #
 # Log displays train tracks, decorations, users and dates.
-if [[ $(git_compare_version "1.8.3") -ge 0 ]]; then
+if [[ $(version-compare $GIT_VERSION "1.8.3") -ge 0 ]]; then
   DECO_COLOUR='%C(auto)'
 else
   DECO_COLOUR='%Cgreen'