build: do simple content-based hashing of webui builds

This dramatically speeds up no-op rebuilds.

It does a full rebuild for any changes whatsoever
in the webui directory.

Co-Authored-By: sketch <hello@sketch.dev>
Change-ID: sa46a41c964391e31k
diff --git a/build/webui.sh b/build/webui.sh
index 0dfc2ed..ec7c62a 100755
--- a/build/webui.sh
+++ b/build/webui.sh
@@ -1,5 +1,32 @@
 #!/bin/bash
 set -e
 
-rm -rf embedded/webui-dist
-unset GOOS GOARCH && go run ./cmd/genwebui -- embedded/webui-dist
+# Use a content-based hash of the webui dir to avoid unnecessary rebuilds.
+OUTPUT_DIR="embedded/webui-dist"
+# go:embed ignores files that start with a '.'
+HASH_FILE="$OUTPUT_DIR/.input_hash"
+
+calculate_input_hash() {
+    local tmp=$(mktemp)
+    (
+        export GIT_INDEX_FILE="$tmp"
+        git read-tree --empty
+        git add webui/
+        git write-tree
+    )
+    rm -f "$tmp"
+}
+
+CURRENT_HASH=$(calculate_input_hash)
+
+if [ -f "$HASH_FILE" ] && [ -d "$OUTPUT_DIR" ]; then
+    STORED_HASH=$(cat "$HASH_FILE")
+    if [ "$CURRENT_HASH" = "$STORED_HASH" ]; then
+        # No changes, skip rebuild
+        exit 0
+    fi
+fi
+
+rm -rf "$OUTPUT_DIR"
+unset GOOS GOARCH && go run ./cmd/genwebui -- "$OUTPUT_DIR"
+echo "$CURRENT_HASH" >"$HASH_FILE"