From 1172f0d802fcff696cbb9ff3f80ccd44228896f4 Mon Sep 17 00:00:00 2001 From: Shane Jordan Date: Sun, 29 Nov 2026 15:49:34 +0000 Subject: [PATCH 1/4] feat: show firmware version and git build in /logs and /api/version --- platformio.ini | 4 +- scripts/bake_git_commit.py | 70 ++++++++++++ src/FirmwareBuildInfo.cpp | 12 +++ src/FirmwareBuildInfo.h | 40 +++++++ src/WebServerManager.cpp | 21 +--- src/main.cpp | 8 ++ test/native/Makefile | 46 +++++++- test/native/test_bake_git_commit.py | 162 ++++++++++++++++++++++++++++ test/native/test_firmware_build.cpp | 83 ++++++++++++++ 9 files changed, 424 insertions(+), 22 deletions(-) create mode 100644 scripts/bake_git_commit.py create mode 100644 src/FirmwareBuildInfo.cpp create mode 100644 src/FirmwareBuildInfo.h create mode 100644 test/native/test_bake_git_commit.py create mode 100644 test/native/test_firmware_build.cpp diff --git a/platformio.ini b/platformio.ini index ab8f1265..abacdf4d 100644 --- a/platformio.ini +++ b/platformio.ini @@ -15,7 +15,9 @@ platform = https://github.com/pioarduino/platform-espressif32/releases/download/ framework = arduino build_type = release board_build.partitions = partitions.csv -extra_scripts = pre:scripts/gen_gzip_assets.py +extra_scripts = + pre:scripts/gen_gzip_assets.py + pre:scripts/bake_git_commit.py monitor_speed = 115200 monitor_filters = direct, printable build_flags = diff --git a/scripts/bake_git_commit.py b/scripts/bake_git_commit.py new file mode 100644 index 00000000..b86c9eba --- /dev/null +++ b/scripts/bake_git_commit.py @@ -0,0 +1,70 @@ +"""Bake the short git commit into src/gen/FirmwareBuildCommit.h. + +Runs as a PlatformIO `pre:` hook. Only src/FirmwareBuildInfo.cpp includes the +header, and it is rewritten only when the commit changes, so a new commit +recompiles that one file. Without git (source archive, missing binary, timeout) +the commit is "unknown" and the build continues. +""" + +import os +import re +import subprocess + +UNKNOWN = "unknown" +COMMIT_RE = re.compile(r"^[0-9a-f]{4,40}$") +HEADER_REL = os.path.join("src", "gen", "FirmwareBuildCommit.h") + + +def sanitize_commit(raw): + text = (raw or "").strip() + return text if COMMIT_RE.match(text) else UNKNOWN + + +def read_commit(project_dir, git="git", timeout=5): + try: + result = subprocess.run( + [git, "-C", project_dir, "rev-parse", "--short=7", "HEAD"], + capture_output=True, text=True, timeout=timeout, check=False) + except (OSError, subprocess.SubprocessError): + return UNKNOWN + if result.returncode != 0: + return UNKNOWN + return sanitize_commit(result.stdout) + + +def render_header(commit): + return ("#pragma once\n" + "// Generated by scripts/bake_git_commit.py. Do not edit.\n" + '#define FW_GIT_COMMIT "%s"\n' % commit) + + +def write_if_changed(path, content): + try: + with open(path, "r", encoding="utf-8") as fh: + if fh.read() == content: + return False + except OSError: + pass + os.makedirs(os.path.dirname(path), exist_ok=True) + tmp = path + ".tmp" + with open(tmp, "w", encoding="utf-8") as fh: + fh.write(content) + os.replace(tmp, path) + return True + + +def bake(project_dir, git="git"): + commit = read_commit(project_dir, git) + changed = write_if_changed(os.path.join(project_dir, HEADER_REL), + render_header(commit)) + print("git-commit: %s (%s)" % (commit, "regenerated" if changed else "unchanged")) + return commit + + +try: + Import("env") # noqa: F821 (PlatformIO SConscript context) +except NameError: + env = None + +if env is not None: + bake(env.subst("$PROJECT_DIR")) diff --git a/src/FirmwareBuildInfo.cpp b/src/FirmwareBuildInfo.cpp new file mode 100644 index 00000000..3986b4d6 --- /dev/null +++ b/src/FirmwareBuildInfo.cpp @@ -0,0 +1,12 @@ +#include "FirmwareBuildInfo.h" + +// Sole includer of the generated header, so a new commit rebuilds only this file. +#if __has_include("gen/FirmwareBuildCommit.h") +#include "gen/FirmwareBuildCommit.h" +#endif + +#ifndef FW_GIT_COMMIT +#define FW_GIT_COMMIT "unknown" +#endif + +const char* firmwareBuildCommit() { return FW_GIT_COMMIT; } diff --git a/src/FirmwareBuildInfo.h b/src/FirmwareBuildInfo.h new file mode 100644 index 00000000..4a171e05 --- /dev/null +++ b/src/FirmwareBuildInfo.h @@ -0,0 +1,40 @@ +#ifndef FIRMWARE_BUILD_INFO_H +#define FIRMWARE_BUILD_INFO_H + +#include +#include + +// Short git commit baked in at build time, or "unknown". +const char* firmwareBuildCommit(); + +// PlatformIO env name; the OTA page downloads spoolsense_scanner_.bin +// by this string. XIAO must precede BOARD_ESP32_C6: its env defines both. +inline const char* firmwareBoardName() { +#if defined(BOARD_SEEED_XIAO_ESP32_C6) + return "seeed_xiao_esp32c6"; +#elif defined(BOARD_ESP32_C6) + return "esp32c6"; +#elif defined(BOARD_ESP32_C5) + return "esp32c5"; +#elif defined(BOARD_ESP32_C3) + return "esp32c3"; +#elif defined(BOARD_S3_DEVKITC) + return "esp32s3devkitc"; +#elif defined(BOARD_ESP32_S3) + return "esp32s3zero"; +#else + return "esp32dev"; +#endif +} + +// Writes "SpoolSense () "; null or empty parts become +// "unknown". Returns snprintf's result, or 0 when out is null or size is 0. +inline int formatFirmwareLine(char* out, size_t size, const char* version, + const char* commit, const char* board) { + if (!out || size == 0) return 0; + auto part = [](const char* s) { return (s && *s) ? s : "unknown"; }; + return std::snprintf(out, size, "SpoolSense %s (%s) %s", + part(version), part(commit), part(board)); +} + +#endif // FIRMWARE_BUILD_INFO_H diff --git a/src/WebServerManager.cpp b/src/WebServerManager.cpp index a560573e..3f1ca0ce 100644 --- a/src/WebServerManager.cpp +++ b/src/WebServerManager.cpp @@ -22,6 +22,7 @@ #include "OpenTag3DLogo.h" #include "OpenSpoolLogo.h" #include "LogBuffer.h" +#include "FirmwareBuildInfo.h" #include "ConfigurationManager.h" #include "NFCManager.h" #include "U1Manager.h" @@ -1220,24 +1221,8 @@ void WebServerManager::handleApiPostConfig() { void WebServerManager::handleApiVersion() { JsonDocument doc; doc["version"] = FIRMWARE_VERSION; - // Matches the PlatformIO env / release-asset naming for each target. - // XIAO must precede BOARD_ESP32_C6 — its env defines both flags, and the - // OTA page downloads spoolsense_scanner_.bin by this string. -#if defined(BOARD_SEEED_XIAO_ESP32_C6) - doc["board"] = "seeed_xiao_esp32c6"; -#elif defined(BOARD_ESP32_C6) - doc["board"] = "esp32c6"; -#elif defined(BOARD_ESP32_C5) - doc["board"] = "esp32c5"; -#elif defined(BOARD_ESP32_C3) - doc["board"] = "esp32c3"; -#elif defined(BOARD_S3_DEVKITC) - doc["board"] = "esp32s3devkitc"; -#elif defined(BOARD_ESP32_S3) - doc["board"] = "esp32s3zero"; -#else - doc["board"] = "esp32dev"; -#endif + doc["board"] = firmwareBoardName(); + doc["build"] = firmwareBuildCommit(); String body; serializeJson(doc, body); _server.send(200, "application/json", body); diff --git a/src/main.cpp b/src/main.cpp index 13e586c4..75ff7d87 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -23,6 +23,8 @@ #include "HardwareNFCConnectionPN532.h" #include "HardwareNFCConnectionRC522.h" #include "BoardPins.h" +#include "FirmwareBuildInfo.h" +#include "LogBuffer.h" #include // main.cpp — ESP32 firmware entry point and hardware init. Manages WiFi, AP mode, NTP, display/LED/ @@ -267,6 +269,12 @@ void setup() { #endif delay(1000); Serial.println("=== Starting setup ==="); + { + char line[96]; + formatFirmwareLine(line, sizeof(line), FIRMWARE_VERSION, firmwareBuildCommit(), + firmwareBoardName()); + LogBuffer::getInstance().logPrintf("%s\n", line); + } // ConfigurationManager MUST init before any hardware — it reads NVS to gate feature initialization if (!ConfigurationManager::getInstance().begin()) { diff --git a/test/native/Makefile b/test/native/Makefile index 77369094..cd85ef63 100644 --- a/test/native/Makefile +++ b/test/native/Makefile @@ -7,9 +7,16 @@ CFLAGS = -std=c11 -DNATIVE_TEST -I../../lib/openprinttag -I../../lib/opentag3d OPT_OBJS = openprinttag_lib.o cbor_native.o OT3D_OBJS = opentag3d_lib.o +PYTHON ?= python3 +FWB_SRCS = test_firmware_build.cpp ../../src/FirmwareBuildInfo.cpp +FWB_DEPS = $(FWB_SRCS) ../../src/FirmwareBuildInfo.h +FWB_VARIANTS = test_firmware_build test_firmware_build_xiao test_firmware_build_c6 \ + test_firmware_build_c5 test_firmware_build_c3 \ + test_firmware_build_s3devkitc test_firmware_build_s3zero + .PHONY: all clean test test_deduction_manager_compile -all: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidecar test_printer_manager test_opt_ndef_bounds test_diagnostics test_tft_landscape_layout test_tigertag_parser test_bambutag_parser test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot +all: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidecar test_printer_manager test_opt_ndef_bounds test_diagnostics test_tft_landscape_layout test_tigertag_parser test_bambutag_parser test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot $(FWB_VARIANTS) openprinttag_lib.o: ../../lib/openprinttag/openprinttag_lib.c $(CC) $(CFLAGS) -c -o $@ $< @@ -65,7 +72,28 @@ test_raw_write_slot: test_raw_write_slot.cpp ../../src/RawWriteSlot.h ../../src/ test_ndef_mime_builder: test_ndef_mime_builder.cpp ../../src/NdefMimeBuilder.h $(CXX) $(CXXFLAGS) -o $@ test_ndef_mime_builder.cpp -test: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidecar test_printer_manager test_opt_ndef_bounds test_diagnostics test_tft_landscape_layout test_tigertag_parser test_bambutag_parser test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot +test_firmware_build: $(FWB_DEPS) + $(CXX) $(CXXFLAGS) -DEXPECT_BOARD=\"esp32dev\" -o $@ $(FWB_SRCS) + +test_firmware_build_xiao: $(FWB_DEPS) + $(CXX) $(CXXFLAGS) -DBOARD_ESP32_C6=1 -DBOARD_SEEED_XIAO_ESP32_C6=1 -DEXPECT_BOARD=\"seeed_xiao_esp32c6\" -o $@ $(FWB_SRCS) + +test_firmware_build_c6: $(FWB_DEPS) + $(CXX) $(CXXFLAGS) -DBOARD_ESP32_C6=1 -DEXPECT_BOARD=\"esp32c6\" -o $@ $(FWB_SRCS) + +test_firmware_build_c5: $(FWB_DEPS) + $(CXX) $(CXXFLAGS) -DBOARD_ESP32_C5=1 -DEXPECT_BOARD=\"esp32c5\" -o $@ $(FWB_SRCS) + +test_firmware_build_c3: $(FWB_DEPS) + $(CXX) $(CXXFLAGS) -DBOARD_ESP32_C3=1 -DEXPECT_BOARD=\"esp32c3\" -o $@ $(FWB_SRCS) + +test_firmware_build_s3devkitc: $(FWB_DEPS) + $(CXX) $(CXXFLAGS) -DBOARD_ESP32_S3=1 -DBOARD_S3_DEVKITC=1 -DEXPECT_BOARD=\"esp32s3devkitc\" -o $@ $(FWB_SRCS) + +test_firmware_build_s3zero: $(FWB_DEPS) + $(CXX) $(CXXFLAGS) -DBOARD_ESP32_S3=1 -DBOARD_S3_ZERO=1 -DEXPECT_BOARD=\"esp32s3zero\" -o $@ $(FWB_SRCS) + +test: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidecar test_printer_manager test_opt_ndef_bounds test_diagnostics test_tft_landscape_layout test_tigertag_parser test_bambutag_parser test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot $(FWB_VARIANTS) @echo "" @echo "=== Running PrinterManager tests ===" @./test_printer_manager @@ -109,8 +137,20 @@ test: test_deduction_tracker test_deduction_manager_compile test_raw_write_sidec @echo "=== Running raw write slot tests ===" @./test_raw_write_slot @echo "" + @echo "=== Running firmware build info tests ===" + @./test_firmware_build + @./test_firmware_build_xiao + @./test_firmware_build_c6 + @./test_firmware_build_c5 + @./test_firmware_build_c3 + @./test_firmware_build_s3devkitc + @./test_firmware_build_s3zero + @echo "" + @echo "=== Running git commit bake tests ===" + @$(PYTHON) -B test_bake_git_commit.py + @echo "" clean: rm -f test_printer_manager test_opt_ndef_bounds test_diagnostics \ test_tft_landscape_layout test_tigertag_parser test_bambutag_parser \ - test_deduction_tracker test_raw_write_sidecar test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot *.o + test_deduction_tracker test_raw_write_sidecar test_write_uid_guard test_cc_sizing test_spool_cache test_opentag3d_runner test_ndef_mime_builder test_raw_write_slot $(FWB_VARIANTS) *.o diff --git a/test/native/test_bake_git_commit.py b/test/native/test_bake_git_commit.py new file mode 100644 index 00000000..6da4f645 --- /dev/null +++ b/test/native/test_bake_git_commit.py @@ -0,0 +1,162 @@ +"""Tests for scripts/bake_git_commit.py, loaded by path without PlatformIO.""" + +import importlib.util +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +sys.dont_write_bytecode = True + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO_ROOT = os.path.abspath(os.path.join(HERE, "..", "..")) +SCRIPT_PATH = os.path.join(REPO_ROOT, "scripts", "bake_git_commit.py") + +_spec = importlib.util.spec_from_file_location("bake_git_commit", SCRIPT_PATH) +bake_git_commit = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(bake_git_commit) + +COMMIT_RE = bake_git_commit.COMMIT_RE + + +def git_available(): + return shutil.which("git") is not None + + +class SanitizeCommitTests(unittest.TestCase): + def test_strips_trailing_newline(self): + self.assertEqual(bake_git_commit.sanitize_commit("6a4252f\n"), "6a4252f") + + def test_full_length_hex_kept(self): + forty = "a" * 40 + self.assertEqual(bake_git_commit.sanitize_commit(forty), forty) + + def test_too_long_hex_rejected(self): + self.assertEqual(bake_git_commit.sanitize_commit("a" * 41), "unknown") + + def test_empty_and_none(self): + self.assertEqual(bake_git_commit.sanitize_commit(""), "unknown") + self.assertEqual(bake_git_commit.sanitize_commit(None), "unknown") + + def test_embedded_quote_rejected(self): + self.assertEqual(bake_git_commit.sanitize_commit('6a4"252f'), "unknown") + + def test_error_text_rejected(self): + self.assertEqual( + bake_git_commit.sanitize_commit("fatal: not a git repository"), "unknown") + + def test_uppercase_hex_rejected(self): + self.assertEqual(bake_git_commit.sanitize_commit("6A4252F"), "unknown") + + def test_too_short_rejected(self): + self.assertEqual(bake_git_commit.sanitize_commit("abc"), "unknown") + + +class ReadCommitTests(unittest.TestCase): + def test_missing_git_binary_returns_unknown(self): + self.assertEqual( + bake_git_commit.read_commit(HERE, git="spoolsense-no-such-git"), + "unknown") + + def test_temp_dir_outside_repo_returns_unknown(self): + if not git_available(): + self.skipTest("git is not installed") + with tempfile.TemporaryDirectory() as tmp: + probe = subprocess.run( + ["git", "-C", tmp, "rev-parse", "HEAD"], + capture_output=True, text=True, check=False) + if probe.returncode == 0: + self.skipTest("temp dir happens to sit inside a repo") + self.assertEqual(bake_git_commit.read_commit(tmp), "unknown") + + def test_repo_root_yields_valid_commit(self): + if not git_available(): + self.skipTest("git is not installed") + if not os.path.exists(os.path.join(REPO_ROOT, ".git")): + self.skipTest("no git HEAD available (not a checkout)") + commit = bake_git_commit.read_commit(REPO_ROOT) + self.assertRegex(commit, COMMIT_RE) + + +class RenderHeaderTests(unittest.TestCase): + def test_exact_header_text(self): + self.assertEqual( + bake_git_commit.render_header("6a4252f"), + '#pragma once\n' + '// Generated by scripts/bake_git_commit.py. Do not edit.\n' + '#define FW_GIT_COMMIT "6a4252f"\n') + + +class WriteIfChangedTests(unittest.TestCase): + def test_write_only_when_content_changes(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "Header.h") + content = bake_git_commit.render_header("6a4252f") + + self.assertTrue(bake_git_commit.write_if_changed(path, content)) + + old = 1000000 + os.utime(path, (old, old)) + mtime_before = os.stat(path).st_mtime_ns + self.assertFalse(bake_git_commit.write_if_changed(path, content)) + self.assertEqual(os.stat(path).st_mtime_ns, mtime_before) + + other = bake_git_commit.render_header("0000000") + self.assertTrue(bake_git_commit.write_if_changed(path, other)) + with open(path, "r", encoding="utf-8") as fh: + self.assertEqual(fh.read(), other) + self.assertFalse(os.path.exists(path + ".tmp")) + + +class BakeTests(unittest.TestCase): + def test_bake_without_git_writes_unknown(self): + with tempfile.TemporaryDirectory() as tmp: + commit = bake_git_commit.bake(tmp, git="spoolsense-no-such-git") + self.assertEqual(commit, "unknown") + header = os.path.join(tmp, "src", "gen", "FirmwareBuildCommit.h") + with open(header, "r", encoding="utf-8") as fh: + self.assertIn('#define FW_GIT_COMMIT "unknown"', fh.read()) + + +class SingleIncluderTests(unittest.TestCase): + def _scan_src(self): + src_root = os.path.join(REPO_ROOT, "src") + includers = [] + mentions = [] + for dirpath, dirnames, filenames in os.walk(src_root): + rel_dir = os.path.relpath(dirpath, REPO_ROOT) + if rel_dir == os.path.join("src", "gen"): + dirnames[:] = [] + continue + for name in filenames: + path = os.path.join(dirpath, name) + try: + with open(path, "r", encoding="utf-8", errors="ignore") as fh: + text = fh.read() + except OSError: + continue + rel = os.path.relpath(path, REPO_ROOT) + if "gen/FirmwareBuildCommit.h" in text: + includers.append(rel) + if "FW_GIT_COMMIT" in text: + mentions.append(rel) + return includers, mentions + + def test_exactly_one_includer_and_no_other_mentions(self): + includers, mentions = self._scan_src() + expected = os.path.join("src", "FirmwareBuildInfo.cpp") + self.assertEqual(includers, [expected]) + self.assertEqual(mentions, [expected]) + + def test_platformio_ini_has_hook_and_no_define(self): + with open(os.path.join(REPO_ROOT, "platformio.ini"), + "r", encoding="utf-8") as fh: + text = fh.read() + self.assertNotIn("FW_GIT_COMMIT", text) + self.assertIn("pre:scripts/bake_git_commit.py", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/native/test_firmware_build.cpp b/test/native/test_firmware_build.cpp new file mode 100644 index 00000000..c59ba7fd --- /dev/null +++ b/test/native/test_firmware_build.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +#include + +#include "FirmwareBuildInfo.h" + +#ifndef EXPECT_BOARD +#error "EXPECT_BOARD must be defined by the build (see test/native/Makefile)" +#endif + +static int failures = 0; +#define CHECK(c, name) do { if (c) std::printf(" PASS %s\n", name); else { std::printf(" FAIL %s\n", name); failures++; } } while (0) + +static bool commitIsUnknownOrHex(const char* s) { + if (!s) return false; + if (std::strcmp(s, "unknown") == 0) return true; + size_t n = std::strlen(s); + if (n < 4 || n > 40) return false; + for (size_t i = 0; i < n; i++) { + char c = s[i]; + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; + } + return true; +} + +int main() { + char buf[64]; + + int n = formatFirmwareLine(buf, sizeof(buf), "1.11.4", "6a4252f", "esp32c6"); + CHECK(n == 35, "case 1: returns 35"); + CHECK(std::strcmp(buf, "SpoolSense 1.11.4 (6a4252f) esp32c6") == 0, + "case 1: full identity line"); + + formatFirmwareLine(buf, sizeof(buf), "1.11.4", "", "esp32c6"); + CHECK(std::strcmp(buf, "SpoolSense 1.11.4 (unknown) esp32c6") == 0, + "case 2: empty commit becomes unknown"); + + formatFirmwareLine(buf, sizeof(buf), "1.11.4", nullptr, "esp32c6"); + CHECK(std::strcmp(buf, "SpoolSense 1.11.4 (unknown) esp32c6") == 0, + "case 3: null commit becomes unknown"); + + formatFirmwareLine(buf, sizeof(buf), nullptr, "6a4252f", nullptr); + CHECK(std::strcmp(buf, "SpoolSense unknown (6a4252f) unknown") == 0, + "case 4: null version and board become unknown"); + + char small[12]; + std::memset(small, 'X', sizeof(small)); + n = formatFirmwareLine(small, sizeof(small), "1.11.4", "6a4252f", "esp32c6"); + CHECK(n == 35, "case 5: truncation still reports full length"); + CHECK(std::strcmp(small, "SpoolSense ") == 0, + "case 5: truncated to 11 chars plus NUL"); + + buf[0] = 'Z'; + CHECK(formatFirmwareLine(buf, 0, "1.11.4", "6a4252f", "esp32c6") == 0, + "case 6: size 0 returns 0"); + CHECK(buf[0] == 'Z', "case 6: size 0 leaves the buffer untouched"); + + CHECK(formatFirmwareLine(nullptr, 64, "1.11.4", "6a4252f", "esp32c6") == 0, + "case 7: null out returns 0"); + + const char* commit = firmwareBuildCommit(); + CHECK(commit != nullptr, "case 8: build commit is non-null"); + CHECK(commitIsUnknownOrHex(commit), + "case 8: build commit is unknown or 4-40 lowercase hex"); + + CHECK(std::strcmp(firmwareBoardName(), EXPECT_BOARD) == 0, + "board name matches EXPECT_BOARD"); + + char line[96]; + formatFirmwareLine(line, sizeof(line), "1.11.4", firmwareBuildCommit(), + firmwareBoardName()); + std::string s(line); + CHECK(s.rfind("SpoolSense 1.11.4 (", 0) == 0, + "case 9: line starts with the version prefix"); + std::string suffix = std::string(") ") + EXPECT_BOARD; + CHECK(s.size() >= suffix.size() && + s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0, + "case 9: line ends with ) EXPECT_BOARD"); + + std::printf("%s: %d failure(s)\n", failures ? "FAILED" : "OK", failures); + return failures ? 1 : 0; +} From 601d65f2e02fb5106dc3fff05c6ca334a1e7a21f Mon Sep 17 00:00:00 2001 From: Shane Jordan Date: Sun, 29 Nov 2026 15:55:03 +0000 Subject: [PATCH 2/4] test: cover firmware identity line boundaries and bake idempotence --- test/native/test_bake_git_commit.py | 16 ++++++++++++++++ test/native/test_firmware_build.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/test/native/test_bake_git_commit.py b/test/native/test_bake_git_commit.py index 6da4f645..387a00d1 100644 --- a/test/native/test_bake_git_commit.py +++ b/test/native/test_bake_git_commit.py @@ -53,6 +53,9 @@ def test_uppercase_hex_rejected(self): def test_too_short_rejected(self): self.assertEqual(bake_git_commit.sanitize_commit("abc"), "unknown") + def test_four_char_hex_kept(self): + self.assertEqual(bake_git_commit.sanitize_commit("abcd"), "abcd") + class ReadCommitTests(unittest.TestCase): def test_missing_git_binary_returns_unknown(self): @@ -119,6 +122,19 @@ def test_bake_without_git_writes_unknown(self): with open(header, "r", encoding="utf-8") as fh: self.assertIn('#define FW_GIT_COMMIT "unknown"', fh.read()) + def test_bake_twice_leaves_header_untouched(self): + # The no-recompile contract end to end: a second bake with the same + # commit must not rewrite the generated header. + with tempfile.TemporaryDirectory() as tmp: + bake_git_commit.bake(tmp, git="spoolsense-no-such-git") + header = os.path.join(tmp, "src", "gen", "FirmwareBuildCommit.h") + mtime_before = os.stat(header).st_mtime_ns + self.assertEqual( + bake_git_commit.bake(tmp, git="spoolsense-no-such-git"), + "unknown") + self.assertEqual(os.stat(header).st_mtime_ns, mtime_before) + self.assertFalse(os.path.exists(header + ".tmp")) + class SingleIncluderTests(unittest.TestCase): def _scan_src(self): diff --git a/test/native/test_firmware_build.cpp b/test/native/test_firmware_build.cpp index c59ba7fd..328a86a5 100644 --- a/test/native/test_firmware_build.cpp +++ b/test/native/test_firmware_build.cpp @@ -59,6 +59,34 @@ int main() { CHECK(formatFirmwareLine(nullptr, 64, "1.11.4", "6a4252f", "esp32c6") == 0, "case 7: null out returns 0"); + formatFirmwareLine(buf, sizeof(buf), "", "6a4252f", ""); + CHECK(std::strcmp(buf, "SpoolSense unknown (6a4252f) unknown") == 0, + "case 4b: empty version and board become unknown"); + + char fit[36]; + std::memset(fit, 'Y', sizeof(fit)); + n = formatFirmwareLine(fit, sizeof(fit), "1.11.4", "6a4252f", "esp32c6"); + CHECK(n == 35 && std::strcmp(fit, "SpoolSense 1.11.4 (6a4252f) esp32c6") == 0, + "boundary: exact-size buffer holds the whole line"); + CHECK(fit[35] == '\0', "boundary: exact-size buffer is NUL-terminated"); + + char tight[35]; + std::memset(tight, 'Y', sizeof(tight)); + n = formatFirmwareLine(tight, sizeof(tight), "1.11.4", "6a4252f", "esp32c6"); + CHECK(n == 35, "boundary: one-short buffer still reports full length"); + CHECK(std::strlen(tight) == 34 && + std::memcmp(tight, "SpoolSense 1.11.4 (6a4252f) esp32c", 34) == 0, + "boundary: one-short buffer truncates to 34 chars plus NUL"); + + // The boot line buffer in main.cpp is char line[96]; the longest real case + // (40-char commit, longest board name) must fit without truncation. + char boot[96]; + n = formatFirmwareLine(boot, sizeof(boot), "1.11.4", + "0123456789abcdef0123456789abcdef01234567", + "seeed_xiao_esp32c6"); + CHECK(n == 79 && n < 96 && std::strlen(boot) == 79, + "boundary: worst-case boot line fits in 96"); + const char* commit = firmwareBuildCommit(); CHECK(commit != nullptr, "case 8: build commit is non-null"); CHECK(commitIsUnknownOrHex(commit), From a52c0fe04ba9f3b8fd9436e8c1a97105e03f2a6d Mon Sep 17 00:00:00 2001 From: Shane Jordan Date: Sun, 29 Nov 2026 17:02:44 +0000 Subject: [PATCH 3/4] fix: reject parent-checkout commits in bake hook and always prepend firmware identity in /logs --- scripts/bake_git_commit.py | 25 ++++++++- src/FirmwareBuildInfo.h | 28 ++++++++++ src/WebServerManager.cpp | 12 ++++- src/main.cpp | 4 +- test/native/test_bake_git_commit.py | 34 +++++++++++++ test/native/test_firmware_build.cpp | 79 +++++++++++++++++++++++++++++ 6 files changed, 177 insertions(+), 5 deletions(-) diff --git a/scripts/bake_git_commit.py b/scripts/bake_git_commit.py index b86c9eba..3c293186 100644 --- a/scripts/bake_git_commit.py +++ b/scripts/bake_git_commit.py @@ -20,6 +20,24 @@ def sanitize_commit(raw): return text if COMMIT_RE.match(text) else UNKNOWN +def toplevel_matches(project_dir, git="git", timeout=5): + """True only when project_dir is itself the git work-tree root. + + git searches parent directories, so an archive extracted inside another + checkout would otherwise bake that checkout's commit. + """ + try: + result = subprocess.run( + [git, "-C", project_dir, "rev-parse", "--show-toplevel"], + capture_output=True, text=True, timeout=timeout, check=False) + except (OSError, subprocess.SubprocessError): + return False + top = (result.stdout or "").strip() + if result.returncode != 0 or not top: + return False + return os.path.realpath(top) == os.path.realpath(project_dir) + + def read_commit(project_dir, git="git", timeout=5): try: result = subprocess.run( @@ -29,7 +47,12 @@ def read_commit(project_dir, git="git", timeout=5): return UNKNOWN if result.returncode != 0: return UNKNOWN - return sanitize_commit(result.stdout) + commit = sanitize_commit(result.stdout) + if commit == UNKNOWN: + return UNKNOWN + if not toplevel_matches(project_dir, git, timeout): + return UNKNOWN + return commit def render_header(commit): diff --git a/src/FirmwareBuildInfo.h b/src/FirmwareBuildInfo.h index 4a171e05..55b598af 100644 --- a/src/FirmwareBuildInfo.h +++ b/src/FirmwareBuildInfo.h @@ -3,6 +3,7 @@ #include #include +#include // Short git commit baked in at build time, or "unknown". const char* firmwareBuildCommit(); @@ -37,4 +38,31 @@ inline int formatFirmwareLine(char* out, size_t size, const char* version, part(version), part(commit), part(board)); } +// Writes "\n" into out (size bytes, NUL-terminated). +// Returns the number of characters written, or 0 when out is null or size is +// 0. The log is truncated to fit; log may overlap out. +inline int formatLogsWithIdentity(char* out, size_t size, const char* version, + const char* commit, const char* board, + const char* log) { + if (!out || size == 0) return 0; + int n = formatFirmwareLine(out, size, version, commit, board); + if (n < 0) return 0; + size_t pos = (static_cast(n) < size) ? static_cast(n) + : size - 1; + if (pos + 1 < size) { + out[pos] = '\n'; + pos++; + } + out[pos] = '\0'; + if (log) { + size_t room = size - pos - 1; + size_t len = std::strlen(log); + if (len > room) len = room; + std::memmove(out + pos, log, len); + pos += len; + out[pos] = '\0'; + } + return static_cast(pos); +} + #endif // FIRMWARE_BUILD_INFO_H diff --git a/src/WebServerManager.cpp b/src/WebServerManager.cpp index 3f1ca0ce..107b14dc 100644 --- a/src/WebServerManager.cpp +++ b/src/WebServerManager.cpp @@ -409,12 +409,20 @@ void WebServerManager::handleLogViewer() { } void WebServerManager::handleApiLogs() { - char* buf = (char*)malloc(4097); + // Identity line (fits in 96, same bound as the boot line) + '\n' + + // log (<= 4096) + NUL, so /logs always starts with the identity. + const size_t kIdentityMax = 96; + const size_t kLogMax = 4096; + const size_t total = kIdentityMax + 1 + kLogMax + 1; + char* buf = (char*)malloc(total); if (!buf) { _server.send(500, "text/plain", "out of memory"); return; } - LogBuffer::getInstance().getLog(buf, 4097); + char* logs = buf + kIdentityMax + 1; + LogBuffer::getInstance().getLog(logs, kLogMax + 1); + formatLogsWithIdentity(buf, total, FIRMWARE_VERSION, firmwareBuildCommit(), + firmwareBoardName(), logs); _server.send(200, "text/plain", buf); free(buf); } diff --git a/src/main.cpp b/src/main.cpp index 75ff7d87..d5aace3e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -24,7 +24,6 @@ #include "HardwareNFCConnectionRC522.h" #include "BoardPins.h" #include "FirmwareBuildInfo.h" -#include "LogBuffer.h" #include // main.cpp — ESP32 firmware entry point and hardware init. Manages WiFi, AP mode, NTP, display/LED/ @@ -273,7 +272,8 @@ void setup() { char line[96]; formatFirmwareLine(line, sizeof(line), FIRMWARE_VERSION, firmwareBuildCommit(), firmwareBoardName()); - LogBuffer::getInstance().logPrintf("%s\n", line); + // /logs prepends this line itself; keep it on serial only. + Serial.println(line); } // ConfigurationManager MUST init before any hardware — it reads NVS to gate feature initialization diff --git a/test/native/test_bake_git_commit.py b/test/native/test_bake_git_commit.py index 387a00d1..4bc7db0f 100644 --- a/test/native/test_bake_git_commit.py +++ b/test/native/test_bake_git_commit.py @@ -82,6 +82,40 @@ def test_repo_root_yields_valid_commit(self): commit = bake_git_commit.read_commit(REPO_ROOT) self.assertRegex(commit, COMMIT_RE) + def _make_temp_repo(self, parent): + repo = os.path.join(parent, "outer-repo") + os.makedirs(repo) + subprocess.run(["git", "-C", repo, "init", "-q"], check=True) + subprocess.run( + ["git", "-C", repo, "-c", "user.email=test@example.invalid", + "-c", "user.name=Test", "commit", "-q", "--allow-empty", + "-m", "seed"], check=True) + return repo + + def test_standalone_repo_yields_valid_commit(self): + if not git_available(): + self.skipTest("git is not installed") + with tempfile.TemporaryDirectory() as tmp: + repo = self._make_temp_repo(tmp) + self.assertRegex(bake_git_commit.read_commit(repo), COMMIT_RE) + + def test_nested_archive_inside_repo_returns_unknown(self): + # A source archive extracted inside another checkout: git searches + # parent directories, so the outer commit must be rejected. + if not git_available(): + self.skipTest("git is not installed") + with tempfile.TemporaryDirectory() as tmp: + repo = self._make_temp_repo(tmp) + archive = os.path.join(repo, "extracted-source") + os.makedirs(archive) + probe = subprocess.run( + ["git", "-C", archive, "rev-parse", "--short=7", "HEAD"], + capture_output=True, text=True, check=False) + if probe.returncode != 0: + self.skipTest("git does not search parent directories here") + self.assertRegex(probe.stdout.strip(), COMMIT_RE) + self.assertEqual(bake_git_commit.read_commit(archive), "unknown") + class RenderHeaderTests(unittest.TestCase): def test_exact_header_text(self): diff --git a/test/native/test_firmware_build.cpp b/test/native/test_firmware_build.cpp index 328a86a5..82ca56ce 100644 --- a/test/native/test_firmware_build.cpp +++ b/test/native/test_firmware_build.cpp @@ -87,6 +87,85 @@ int main() { CHECK(n == 79 && n < 96 && std::strlen(boot) == 79, "boundary: worst-case boot line fits in 96"); + // formatLogsWithIdentity: /logs must always start with the identity line. + { + char out[128]; + int n = formatLogsWithIdentity(out, sizeof(out), "1.11.4", "6a4252f", + "esp32c6", "hello\nworld"); + CHECK(n == 47 && + std::strcmp(out, + "SpoolSense 1.11.4 (6a4252f) esp32c6\n" + "hello\nworld") == 0, + "prepend: identity line, newline, then log"); + + n = formatLogsWithIdentity(out, sizeof(out), "1.11.4", "6a4252f", + "esp32c6", ""); + CHECK(n == 36 && + std::strcmp(out, "SpoolSense 1.11.4 (6a4252f) esp32c6\n") == 0, + "prepend: empty log still yields identity line plus newline"); + + n = formatLogsWithIdentity(out, sizeof(out), "1.11.4", "6a4252f", + "esp32c6", nullptr); + CHECK(n == 36 && + std::strcmp(out, "SpoolSense 1.11.4 (6a4252f) esp32c6\n") == 0, + "prepend: null log still yields identity line plus newline"); + + char tight2[40]; + n = formatLogsWithIdentity(tight2, sizeof(tight2), "1.11.4", "6a4252f", + "esp32c6", "hello"); + CHECK(n == 39 && + std::strcmp(tight2, + "SpoolSense 1.11.4 (6a4252f) esp32c6\nhel") == 0, + "prepend: log truncated to fit, NUL-terminated"); + + char exact36[36]; + n = formatLogsWithIdentity(exact36, sizeof(exact36), "1.11.4", + "6a4252f", "esp32c6", "hello"); + CHECK(n == 35 && + std::strcmp(exact36, "SpoolSense 1.11.4 (6a4252f) esp32c6") == 0, + "boundary: size 36 keeps identity only, no room for newline"); + + char exact37[37]; + n = formatLogsWithIdentity(exact37, sizeof(exact37), "1.11.4", + "6a4252f", "esp32c6", "hello"); + CHECK(n == 36 && + std::strcmp(exact37, + "SpoolSense 1.11.4 (6a4252f) esp32c6\n") == 0, + "boundary: size 37 fits identity plus newline, no log"); + + // handleApiLogs passes log text living inside out at offset 97. + char combined[4194]; + char* logs = combined + 97; + std::strcpy(logs, "log text"); + n = formatLogsWithIdentity(combined, sizeof(combined), "1.11.4", + "6a4252f", "esp32c6", logs); + CHECK(n == 44 && + std::strcmp(combined, + "SpoolSense 1.11.4 (6a4252f) esp32c6\n" + "log text") == 0, + "prepend: overlapping in-buffer log is moved safely"); + + char worst[4194]; + char biglog[4097]; + std::memset(biglog, 'x', sizeof(biglog) - 1); + biglog[sizeof(biglog) - 1] = '\0'; + n = formatLogsWithIdentity(worst, sizeof(worst), "1.11.4", + "0123456789abcdef0123456789abcdef01234567", + "seeed_xiao_esp32c6", biglog); + CHECK(n == 79 + 1 + 4096 && std::strlen(worst) == 79 + 1 + 4096, + "boundary: worst-case identity plus full 4096 log fits in 4194"); + + char guard[4]; + guard[0] = 'Z'; + CHECK(formatLogsWithIdentity(nullptr, 64, "1.11.4", "6a4252f", + "esp32c6", "x") == 0, + "prepend: null out returns 0"); + CHECK(formatLogsWithIdentity(guard, 0, "1.11.4", "6a4252f", "esp32c6", + "x") == 0 && + guard[0] == 'Z', + "prepend: size 0 returns 0 and leaves the buffer untouched"); + } + const char* commit = firmwareBuildCommit(); CHECK(commit != nullptr, "case 8: build commit is non-null"); CHECK(commitIsUnknownOrHex(commit), From 6af747d8571b94cb69001776197a92f5a79e9542 Mon Sep 17 00:00:00 2001 From: Shane Jordan Date: Sun, 29 Nov 2026 18:17:46 +0000 Subject: [PATCH 4/4] fix: ignore inherited git directory overrides in the build-commit bake hook and its tests --- scripts/bake_git_commit.py | 17 +++++- test/native/test_bake_git_commit.py | 88 +++++++++++++++++++++++++++-- 2 files changed, 99 insertions(+), 6 deletions(-) diff --git a/scripts/bake_git_commit.py b/scripts/bake_git_commit.py index 3c293186..7f4aeeb6 100644 --- a/scripts/bake_git_commit.py +++ b/scripts/bake_git_commit.py @@ -13,6 +13,17 @@ UNKNOWN = "unknown" COMMIT_RE = re.compile(r"^[0-9a-f]{4,40}$") HEADER_REL = os.path.join("src", "gen", "FirmwareBuildCommit.h") +GIT_ENV_DROP = ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY") + + +def git_env(): + """The caller's environment without the overrides that redirect HEAD. + + An exported GIT_DIR makes git read another checkout's HEAD while + --show-toplevel still reports project_dir, which would defeat the + nested-archive guard. + """ + return {k: v for k, v in os.environ.items() if k not in GIT_ENV_DROP} def sanitize_commit(raw): @@ -29,7 +40,8 @@ def toplevel_matches(project_dir, git="git", timeout=5): try: result = subprocess.run( [git, "-C", project_dir, "rev-parse", "--show-toplevel"], - capture_output=True, text=True, timeout=timeout, check=False) + capture_output=True, text=True, timeout=timeout, check=False, + env=git_env()) except (OSError, subprocess.SubprocessError): return False top = (result.stdout or "").strip() @@ -42,7 +54,8 @@ def read_commit(project_dir, git="git", timeout=5): try: result = subprocess.run( [git, "-C", project_dir, "rev-parse", "--short=7", "HEAD"], - capture_output=True, text=True, timeout=timeout, check=False) + capture_output=True, text=True, timeout=timeout, check=False, + env=git_env()) except (OSError, subprocess.SubprocessError): return UNKNOWN if result.returncode != 0: diff --git a/test/native/test_bake_git_commit.py b/test/native/test_bake_git_commit.py index 4bc7db0f..70649581 100644 --- a/test/native/test_bake_git_commit.py +++ b/test/native/test_bake_git_commit.py @@ -1,5 +1,6 @@ """Tests for scripts/bake_git_commit.py, loaded by path without PlatformIO.""" +import hashlib import importlib.util import os import shutil @@ -7,6 +8,7 @@ import sys import tempfile import unittest +from unittest import mock sys.dont_write_bytecode = True @@ -25,6 +27,18 @@ def git_available(): return shutil.which("git") is not None +def clean_git_env(**overrides): + """Environment for fixture git commands, ignoring any inherited GIT_* var.""" + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + env.update(overrides) + return env + + +def file_digest(path): + with open(path, "rb") as fh: + return hashlib.sha256(fh.read()).hexdigest() + + class SanitizeCommitTests(unittest.TestCase): def test_strips_trailing_newline(self): self.assertEqual(bake_git_commit.sanitize_commit("6a4252f\n"), "6a4252f") @@ -63,6 +77,19 @@ def test_missing_git_binary_returns_unknown(self): bake_git_commit.read_commit(HERE, git="spoolsense-no-such-git"), "unknown") + def test_git_env_drops_only_the_redirect_overrides(self): + overrides = {name: os.sep + "elsewhere" for name in + ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", + "GIT_OBJECT_DIRECTORY")} + overrides["GIT_MARKER_KEPT"] = "kept" + with mock.patch.dict(os.environ, overrides): + env = bake_git_commit.git_env() + for name in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", + "GIT_OBJECT_DIRECTORY"): + self.assertNotIn(name, env) + self.assertEqual(env.get("GIT_MARKER_KEPT"), "kept") + self.assertEqual(env.get("PATH"), os.environ.get("PATH")) + def test_temp_dir_outside_repo_returns_unknown(self): if not git_available(): self.skipTest("git is not installed") @@ -82,14 +109,20 @@ def test_repo_root_yields_valid_commit(self): commit = bake_git_commit.read_commit(REPO_ROOT) self.assertRegex(commit, COMMIT_RE) - def _make_temp_repo(self, parent): - repo = os.path.join(parent, "outer-repo") + def _git(self, repo, *args): + return subprocess.run( + ["git", "-C", repo] + list(args), capture_output=True, text=True, + check=True, env=clean_git_env()).stdout.strip() + + def _make_temp_repo(self, parent, name="outer-repo", message="seed"): + repo = os.path.join(parent, name) os.makedirs(repo) - subprocess.run(["git", "-C", repo, "init", "-q"], check=True) + subprocess.run(["git", "-C", repo, "init", "-q"], check=True, + env=clean_git_env()) subprocess.run( ["git", "-C", repo, "-c", "user.email=test@example.invalid", "-c", "user.name=Test", "commit", "-q", "--allow-empty", - "-m", "seed"], check=True) + "-m", message], check=True, env=clean_git_env()) return repo def test_standalone_repo_yields_valid_commit(self): @@ -99,6 +132,53 @@ def test_standalone_repo_yields_valid_commit(self): repo = self._make_temp_repo(tmp) self.assertRegex(bake_git_commit.read_commit(repo), COMMIT_RE) + def test_read_commit_ignores_inherited_git_dir(self): + if not git_available(): + self.skipTest("git is not installed") + with tempfile.TemporaryDirectory() as tmp: + other = self._make_temp_repo(tmp, name="other-repo", message="alpha") + repo = self._make_temp_repo(tmp, name="own-repo", message="beta") + other_head = self._git(other, "rev-parse", "HEAD") + own_commit = bake_git_commit.read_commit(repo) + self.assertRegex(own_commit, COMMIT_RE) + self.assertNotIn(own_commit, other_head) + with mock.patch.dict(os.environ, + {"GIT_DIR": os.path.join(other, ".git")}): + probe = subprocess.run( + ["git", "-C", repo, "rev-parse", "--short=7", "HEAD"], + capture_output=True, text=True, check=False) + if probe.stdout.strip() == own_commit: + self.skipTest("git does not honour an inherited GIT_DIR here") + baked = bake_git_commit.read_commit(repo) + self.assertEqual(baked, own_commit) + + def test_fixture_ignores_inherited_git_dir(self): + # A fixture command must never touch a repository named by GIT_DIR. + if not git_available(): + self.skipTest("git is not installed") + with tempfile.TemporaryDirectory() as tmp: + target = self._make_temp_repo(tmp, name="existing-repo", + message="alpha") + with open(os.path.join(target, "staged.txt"), "w", + encoding="utf-8") as fh: + fh.write("staged\n") + self._git(target, "add", "staged.txt") + head_before = self._git(target, "rev-parse", "HEAD") + staged_before = self._git(target, "ls-files", "--stage") + index_before = file_digest(os.path.join(target, ".git", "index")) + with mock.patch.dict(os.environ, + {"GIT_DIR": os.path.join(target, ".git")}): + fresh = self._make_temp_repo(tmp, name="fresh-repo", + message="beta") + self.assertEqual(self._git(target, "rev-parse", "HEAD"), head_before) + self.assertEqual(self._git(target, "ls-files", "--stage"), + staged_before) + self.assertEqual( + file_digest(os.path.join(target, ".git", "index")), + index_before) + self.assertRegex(self._git(fresh, "rev-parse", "HEAD"), r"^[0-9a-f]{40}$") + self.assertRegex(bake_git_commit.read_commit(fresh), COMMIT_RE) + def test_nested_archive_inside_repo_returns_unknown(self): # A source archive extracted inside another checkout: git searches # parent directories, so the outer commit must be rejected.