diff --git a/components/st3m/host-tools/version.py b/components/st3m/host-tools/version.py
index 8cb4992aa9f16bcc4376c7710c272feb8bf6a56a..3ce39f77a3fb44bf7708e7e1fd4ba92c71ed03a6 100644
--- a/components/st3m/host-tools/version.py
+++ b/components/st3m/host-tools/version.py
@@ -10,6 +10,7 @@ and the release process.
 
 import subprocess
 import sys
+import os
 
 
 class Tag:
@@ -50,7 +51,7 @@ def tags_for_commit(release, commit):
     return res
 
 
-def get_version():
+def get_git_based_version():
     commit = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip()
     branches = (
         subprocess.check_output(
@@ -118,7 +119,15 @@ if len(sys.argv) > 1:
     if sys.argv[1] == "-c":
         fmt = "C"
 
-v = get_version()
+v = None
+if os.environ.get('CI') is not None:
+    tag = os.environ.get('CI_COMMIT_TAG')
+    if tag is not None:
+        # If we're building a tag, just use that as a version.
+        v = tag
+if v is None:
+    v = get_git_based_version()
+
 if fmt == "C":
     print('const char *st3m_version = "' + v + '";')
 else:
diff --git a/tools/dist.sh b/tools/dist.sh
index 14c19c12ae5584f9bc44d5131f8e3bdc03d032da..37ea64c58a1739bc7ef58c0795123e59bc9e9ce9 100755
--- a/tools/dist.sh
+++ b/tools/dist.sh
@@ -11,21 +11,12 @@ if [ ! -f sdkconfig.defaults ] || [ ! -f recovery/sdkconfig.defaults ]; then
     exit 1
 fi
 
-if [ ! -z "${CI}" ]; then
-    if [ ! -z "${CI_COMMIT_TAG}" ]; then
-        # If we're building a tag, just use that as a version.
-        version="${CI_COMMIT_TAG}"
-    else
-        # Otherwise, let normal version machinery run, but fetch all changes
-        # and check out the correct branch. Otherwise we'll get weird version
-        # strings.
-        git fetch --unshallow origin "$CI_COMMIT_REF_NAME"
-        git checkout "$CI_COMMIT_REF_NAME"
-        version="$(python3 components/st3m/host-tools/version.py)"
-    fi
-else
-    version="$(python3 components/st3m/host-tools/version.py)"
+# Always fetch full history on Gitlab when not building a tag, otherwise we get bogus results.
+if [ ! -z "${CI}" && -z "${CI_COMMIT_TAG}" ]; then
+    git fetch --unshallow origin "$CI_COMMIT_REF_NAME"
+    git checkout "$CI_COMMIT_REF_NAME"
 fi
+version="$(python3 components/st3m/host-tools/version.py)"
 
 rm -rf sdkconfig build
 rm -rf recovery/sdkconfig recovery/build