Files
meshcore-tth/tools/build_version.py
T

170 lines
7.8 KiB
Python

# SPDX-License-Identifier: MIT
# CUSTOM (TeTeHacko): real version and build timestamp for the `ver` command.
#
# WIRE THIS INTO EVERY ENV WE FLASH. Without it the node reports the fallback
# literal from examples/*/MyMesh.h -- "v1.16.0", "6 Jun 2026" -- which is the
# same in every build ever made, so `ver` cannot tell one flash from another.
# That is not a cosmetic problem: after a 14-minute BLE DFU onto the T1000-E,
# every field the node reported back was byte-for-byte what it said beforehand,
# and the only evidence the image had landed was a line in a scrollback buffer.
#
# extra_scripts = ${nrf52_base.extra_scripts}
# pre:tools/build_version.py
#
# Injects FIRMWARE_VERSION (<upstream tag>-tth<git sha>, '+' = dirty tree),
# FIRMWARE_BUILD_DATE, FIRMWARE_BUILD_EPOCH and FW_OTA_TARGET into project
# sources only (not libraries or framework, so ccache hits direct mode across
# commits and variants). Clean trees stamp the HEAD commit timestamp in UTC
# (or SOURCE_DATE_EPOCH if set) for byte-reproducible builds; dirty trees stamp
# the current UTC time.
#
# SCons script, not a module: `Import` and `env` are SCons builtins and
# Import("env") has to come first, hence the file-wide ruff exemption.
# ruff: noqa: F821, E402
# mypy: disable-error-code="name-defined"
if __name__ == "__main__": # run by hand (--help): the header above, nothing else
with open(__file__) as _f:
for _ln in _f:
if not _ln.startswith("#"):
break
if "SPDX-License-Identifier" not in _ln:
print(_ln[2:].rstrip() if _ln.startswith("# ") else "")
raise SystemExit(0)
Import("env")
import os
import re
import subprocess
from datetime import datetime, timezone
def git(cwd, *args):
return subprocess.check_output(("git",) + args, cwd=cwd,
stderr=subprocess.DEVNULL).decode().strip()
cwd = env.subst("$PROJECT_DIR")
# The base version follows the newest upstream release tag that HEAD descends
# from, rather than being written here as a literal -- a literal would keep
# claiming v1.16.0 long after upstream moved on, which is exactly the kind of
# stale-by-construction string this script exists to get rid of.
# Upstream tags them per-example ("companion-v1.16.0", "repeater-v1.16.0"), so
# match anything carrying a v<digit> and strip the prefix. Our own release tags
# (`...+tth.<timestamp>`) are excluded so they cannot shadow the upstream base.
# So are backup/* tags: `backup/feat-ble-diag-pre-v117-merge` matched *v[0-9]*
# and, being the newest tag, won -- so the T1000-E flashed on 10. 8. 2026 reports
# a base of "v117-merge". A pre-flight safety tag must never end up in the
# version string of the thing it was protecting.
base = "nover"
try:
tag = git(cwd, "describe", "--tags", "--abbrev=0",
"--match", "*v[0-9]*", "--exclude", "*+tth*",
"--exclude", "backup/*")
# Cut at the 'v' that STARTS THE VERSION, not at the first 'v' in the tag:
# "room-server-v1.17.0" has one in "server", and find("v") turned the base
# into "ver-v1.17.0". Every earlier upstream tag we saw (companion-, repeater-)
# happened to have no 'v' in its prefix, so this hid until v1.17.0.
m = re.search(r"v[0-9]", tag)
base = tag[m.start():] if m else tag
except Exception:
pass
sha, dirty = "nogit", ""
try:
sha = git(cwd, "rev-parse", "--short=7", "HEAD")
# against HEAD: staged changes count too (a plain `git diff` sees only
# unstaged ones, so a build from a staged tree came out as a clean commit)
if subprocess.call(["git", "diff", "--quiet", "HEAD"], cwd=cwd) != 0:
dirty = "+"
except Exception:
pass
# Both strings have to survive the companion protocol's fixed-width fields
# (RESP_CODE_DEVICE_INFO in companion_radio/MyMesh.cpp): 20 B for the version
# and 12 B for the build date, NUL included, so 19 and 11 usable characters.
# Anything longer is silently truncated on the wire -- which first showed up as
# a node reporting "v1.16.0-tth-956238c" for SHA 956238c3, and a build date of
# "04 Aug 2026 " with the time cut clean off. The repeater's text console has no
# such limit, but one format everywhere beats two.
VER_LIMIT, DATE_LIMIT = 19, 11
# Budget: base and the dirty marker are never sacrificed -- a lost '+' would
# turn an uncommitted build into something that looks reproducible. The SHA
# gives up characters instead; git needs 7 for uniqueness in a repo this size,
# so this only bites if upstream's version string grows unusually long.
marker = "-tth"
room = VER_LIMIT - len(base) - len(marker) - len(dirty)
version = "%s%s%s%s" % (base, marker, sha[:max(4, room)], dirty)
if len(version) > VER_LIMIT:
print("build_version.py: WARNING: %r is %d chars, will truncate to %d on "
"the companion protocol" % (version, len(version), VER_LIMIT))
# yymmdd hhmm = exactly 11. Not pretty, but complete and sortable; the readable
# "%d %b %Y %H:%M" is 17 and lost its time to the 12-byte field.
#
# Reproducible builds: honor SOURCE_DATE_EPOCH when set; otherwise use the HEAD
# commit timestamp (UTC) for clean trees so two builds of the same commit
# produce identical bytes regardless of wall clock or host timezone. Dirty
# trees still stamp the current UTC time so bench iterations stay distinct.
sde = os.environ.get("SOURCE_DATE_EPOCH", "").strip()
if sde:
build_epoch = int(sde)
elif not dirty and sha != "nogit":
try:
build_epoch = int(git(cwd, "log", "-1", "--format=%ct", "HEAD"))
except Exception:
build_epoch = int(datetime.now(timezone.utc).timestamp())
else:
build_epoch = int(datetime.now(timezone.utc).timestamp())
now = datetime.fromtimestamp(build_epoch, timezone.utc)
build_date = now.strftime("%y%m%d %H%M")[:DATE_LIMIT]
# Propagate SOURCE_DATE_EPOCH into every compiler/tool subprocess so GCC also
# evaluates any __DATE__/__TIME__ macros inside third-party libraries or the
# Arduino framework deterministically (and ccache gets 100% hits).
os.environ["SOURCE_DATE_EPOCH"] = str(build_epoch)
env["ENV"]["SOURCE_DATE_EPOCH"] = str(build_epoch)
# src/helpers/FwUpdate refuses a package built for another target: the env,
# plus the image variant when one env is released as several
# (FW_OTA_VARIANT=observer-ota -> "SenseCap_Solar_repeater-observer-ota"), or a
# full package would silently swap a node's variant.
ota_variant = os.environ.get("FW_OTA_VARIANT", "").strip()
ota_target = env["PIOENV"] + ("-" + ota_variant if ota_variant else "")
if len(ota_target) > 47: # Manifest.target[48] in FwUpdate.cpp, NUL-terminated
raise SystemExit("build_version.py: OTA target %r longer than 47 chars" % ota_target)
# Scope the volatile version/timestamp/target defines to project sources only
# (src/, examples/, variants/, test/) rather than global env CPPDEFINES.
# Libraries and the Arduino framework never reference them, and keeping those
# flags off their compiler command lines lets ccache hit direct mode across
# commits, timestamps and OTA variants.
_stamp_defines = [
("FIRMWARE_VERSION", env.StringifyMacro(version)),
("FIRMWARE_BUILD_DATE", env.StringifyMacro(build_date)),
("FIRMWARE_BUILD_EPOCH", str(build_epoch)),
("FW_OTA_TARGET", env.StringifyMacro(ota_target)),
]
_proj_root = os.path.realpath(cwd)
_libdeps_root = os.path.realpath(env.subst("$PROJECT_LIBDEPS_DIR"))
_lib_root = os.path.realpath(os.path.join(cwd, "lib"))
_stamped_envs = set()
def _stamp_project(e, node):
if id(e) not in _stamped_envs:
src = os.path.realpath(node.srcnode().get_abspath())
if src.startswith(_proj_root + os.sep) and not (
src.startswith(_libdeps_root + os.sep)
or src.startswith(_lib_root + os.sep)
):
_stamped_envs.add(id(e))
e.Append(CPPDEFINES=_stamp_defines)
return node
env.AddBuildMiddleware(_stamp_project)
print("build_version.py: %s (Build: %s, epoch %d)" % (version, build_date, build_epoch))