cmd: infer version from version.json; add version flag

Signed-off-by: NotAShelf <raf@notashelf.dev>
Change-Id: I0f429ef3345444c0c4bedbc80ee3d5e06a6a6964
This commit is contained in:
raf 2026-03-07 08:48:29 +03:00
commit 9efabc8f76
Signed by: NotAShelf
GPG key ID: 29D95B64378DB4BF
3 changed files with 53 additions and 4 deletions

View file

@ -1,6 +1,7 @@
package watchdog
import (
"encoding/json"
"fmt"
"os"
"strings"
@ -18,10 +19,53 @@ var (
buildDate string
)
type versionInfo struct {
Version string `json:"version"`
Commit string `json:"commit"`
BuildDate string `json:"buildDate"`
}
func getVersion() string {
if version != "" {
return version
}
data, err := os.ReadFile("version.json")
if err != nil {
return "dev"
}
var v versionInfo
if err := json.Unmarshal(data, &v); err != nil {
return "dev"
}
if v.Version != "" {
return v.Version
}
return "dev"
}
func getCommit() string {
if commit != "" {
return commit
}
data, err := os.ReadFile("version.json")
if err != nil {
return "none"
}
var v versionInfo
if err := json.Unmarshal(data, &v); err != nil {
return "none"
}
if v.Commit != "" {
return v.Commit
}
return "none"
}
var rootCmd = &cobra.Command{
Use: "watchdog",
Short: "Privacy-first web analytics with Prometheus metrics",
Long: `Watchdog is a lightweight, privacy-first analytics system that aggregates web traffic data.`,
Use: "watchdog",
Short: "Privacy-first web analytics with Prometheus metrics",
Long: `Watchdog is a lightweight, privacy-first analytics system that aggregates web traffic data.`,
Version: getVersion() + "\ncommit: " + getCommit(),
RunE: func(cmd *cobra.Command, args []string) error {
return Run(cfg)
},

View file

@ -57,7 +57,7 @@ func Run(cfg *config.Config) error {
promRegistry.MustRegister(blockedRequests)
// Register health and runtime metrics
healthCollector := health.NewCollector(version, commit, buildDate)
healthCollector := health.NewCollector(getVersion(), getCommit(), buildDate)
if err := healthCollector.Register(promRegistry); err != nil {
return fmt.Errorf("failed to register health metrics: %w", err)
}

5
version.json Normal file
View file

@ -0,0 +1,5 @@
{
"version": "0.1.0",
"commit": "",
"buildDate": ""
}