about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAlan Pearce2024-05-14 21:16:23 +0200
committerAlan Pearce2024-05-14 21:45:02 +0200
commit1a5c82e2d08accb6330c4164ab987b87157b10ed (patch)
tree48d6a913809e60b1a0cc28a8b67413ffaf979f97
parentf08094f23aa4dc7d63a7c98b4429d88005fe3a2d (diff)
downloadsearchix-1a5c82e2d08accb6330c4164ab987b87157b10ed.tar.lz
searchix-1a5c82e2d08accb6330c4164ab987b87157b10ed.tar.zst
searchix-1a5c82e2d08accb6330c4164ab987b87157b10ed.zip
build: bake git hash into build for headers and --version
-rw-r--r--flake.nix7
-rw-r--r--internal/config/config.go5
-rw-r--r--internal/importer/http.go3
-rw-r--r--internal/server/headers.go1
-rw-r--r--internal/server/mux.go14
-rw-r--r--nix/package.nix14
-rw-r--r--searchix.go8
7 files changed, 49 insertions, 3 deletions
diff --git a/flake.nix b/flake.nix
index 48697c5..c0df6bf 100644
--- a/flake.nix
+++ b/flake.nix
@@ -41,11 +41,11 @@
           # This has no effect on other platforms.
           callPackage = pkgs.darwin.apple_sdk_11_0.callPackage or pkgs.callPackage;
         in
-        {
+        rec {
           packages.default = callPackage ./nix/package.nix {
             inherit (gomod2nix.legacyPackages.${system}) buildGoApplication;
-            css = simple-css;
             inherit self;
+            css = simple-css;
           };
           devShells.default = callPackage ./nix/dev-shell.nix {
             pre-commit-check = {
@@ -61,6 +61,9 @@
                 inherit pkgs;
               }
             );
+            buildVersion = pkgs.testers.testVersion {
+              package = packages.default;
+            };
           };
         })
     );
diff --git a/internal/config/config.go b/internal/config/config.go
index 75f18d6..add4e67 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -12,6 +12,11 @@ import (
 	"github.com/pkg/errors"
 )
 
+var (
+	CommitSHA string
+	ShortSHA  string
+)
+
 type URL struct {
 	*url.URL
 }
diff --git a/internal/importer/http.go b/internal/importer/http.go
index 6d60c44..b496177 100644
--- a/internal/importer/http.go
+++ b/internal/importer/http.go
@@ -6,6 +6,7 @@ import (
 	"log/slog"
 	"net/http"
 	"os"
+	"searchix/internal/config"
 	"searchix/internal/file"
 	"strings"
 	"time"
@@ -29,6 +30,8 @@ func fetchFileIfNeeded(ctx context.Context, path string, url string) (needed boo
 		return false, errors.WithMessagef(err, "could not create HTTP request for %s", url)
 	}
 
+	req.Header.Set("User-Agent", fmt.Sprintf("Searchix %s", config.ShortSHA))
+
 	if mtime != "" {
 		req.Header.Set("If-Modified-Since", mtime)
 	}
diff --git a/internal/server/headers.go b/internal/server/headers.go
index 4fb9efd..562fccc 100644
--- a/internal/server/headers.go
+++ b/internal/server/headers.go
@@ -11,6 +11,7 @@ func AddHeadersMiddleware(next http.Handler, config *cfg.Config) http.Handler {
 			w.Header().Add(h, v)
 		}
 		w.Header().Add("Content-Security-Policy", config.Web.ContentSecurityPolicy.String())
+		w.Header().Add("Server", "searchix/"+cfg.ShortSHA)
 
 		next.ServeHTTP(w, r)
 	})
diff --git a/internal/server/mux.go b/internal/server/mux.go
index 582d154..0f32507 100644
--- a/internal/server/mux.go
+++ b/internal/server/mux.go
@@ -35,6 +35,11 @@ type HTTPError struct {
 
 const jsSnippet = template.HTML(livereload.JsSnippet) // #nosec G203
 
+type VersionInfo struct {
+	ShortSHA  string
+	CommitSHA string
+}
+
 type TemplateData struct {
 	Sources       map[string]*config.Source
 	Source        config.Source
@@ -42,6 +47,7 @@ type TemplateData struct {
 	Results       bool
 	SourceResult  *bleve.SearchResult
 	ExtraBodyHTML template.HTML
+	Version       VersionInfo
 }
 
 type ResultData[T options.NixOption] struct {
@@ -53,6 +59,11 @@ type ResultData[T options.NixOption] struct {
 	Next           string
 }
 
+var versionInfo = &VersionInfo{
+	ShortSHA:  config.ShortSHA,
+	CommitSHA: config.CommitSHA,
+}
+
 func applyDevModeOverrides(config *config.Config) {
 	if len(config.Web.ContentSecurityPolicy.ScriptSrc) == 0 {
 		config.Web.ContentSecurityPolicy.ScriptSrc = config.Web.ContentSecurityPolicy.DefaultSrc
@@ -93,6 +104,7 @@ func NewMux(
 		indexData := TemplateData{
 			ExtraBodyHTML: config.Web.ExtraBodyHTML,
 			Sources:       config.Importer.Sources,
+			Version:       *versionInfo,
 		}
 		err := templates["index"].ExecuteTemplate(w, "index.gotmpl", indexData)
 		if err != nil {
@@ -140,6 +152,7 @@ func NewMux(
 					ExtraBodyHTML: config.Web.ExtraBodyHTML,
 					Source:        *source,
 					Sources:       config.Importer.Sources,
+					Version:       *versionInfo,
 				},
 				ResultsPerPage: search.ResultsPerPage,
 				Query:          qs,
@@ -200,6 +213,7 @@ func NewMux(
 				Sources:       config.Importer.Sources,
 				Source:        *source,
 				SourceResult:  sourceResult,
+				Version:       *versionInfo,
 			})
 			if err != nil {
 				http.Error(w, err.Error(), http.StatusInternalServerError)
diff --git a/nix/package.nix b/nix/package.nix
index 5e47c9b..d311505 100644
--- a/nix/package.nix
+++ b/nix/package.nix
@@ -12,11 +12,12 @@
 , buildGoApplication ? pkgs.buildGoApplication
 , css
 , self
+, testers
 }:
 let
   inherit (builtins) concatStringsSep match;
 
-  version = concatStringsSep "-" (match
+  version = "0-unstable-" + concatStringsSep "-" (match
     "([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2}).*"
     self.lastModifiedDate
   );
@@ -42,5 +43,16 @@ buildGoApplication {
     cp ${css} frontend/static/base.css
   '';
   tags = [ "embed" ];
+  ldflags = [
+    "-s"
+    "-w"
+    "-X"
+    "searchix/internal/config.CommitSHA=${self.rev or self.dirtyRev}"
+    "-X"
+    "searchix/internal/config.ShortSHA=${self.shortRev or self.dirtyShortRev}"
+    "-X"
+    "main.buildVersion=${version}"
+  ];
+
   modules = ../gomod2nix.toml;
 }
diff --git a/searchix.go b/searchix.go
index 217dc1a..79940e9 100644
--- a/searchix.go
+++ b/searchix.go
@@ -2,6 +2,7 @@ package main
 
 import (
 	"flag"
+	"fmt"
 	"log"
 	"log/slog"
 	"os"
@@ -17,10 +18,13 @@ import (
 	"github.com/pelletier/go-toml/v2"
 )
 
+var buildVersion string
+
 var (
 	configFile = flag.String("config", "config.toml", "config `file` to use")
 	liveReload = flag.Bool("live", false, "whether to enable live reloading (development)")
 	replace    = flag.Bool("replace", false, "whether to replace existing database, if it exists")
+	version    = flag.Bool("version", false, "print version information")
 )
 
 func nextOccurrenceOfLocalTime(t toml.LocalTime) time.Time {
@@ -45,6 +49,10 @@ func nextOccurrenceOfLocalTime(t toml.LocalTime) time.Time {
 
 func main() {
 	flag.Parse()
+	if *version {
+		fmt.Fprintln(os.Stderr, "searchix", buildVersion, config.CommitSHA)
+		os.Exit(0)
+	}
 
 	conf, err := config.GetConfig(*configFile)
 	if err != nil {