add file comment generation and hashing for reproducible output in proto_generator

This commit is contained in:
adman
2026-05-29 01:14:56 +02:00
parent 624e8ad4de
commit efeb5ecda6
6 changed files with 95 additions and 7 deletions
+48 -2
View File
@@ -1,12 +1,14 @@
package main
import (
"crypto/sha256"
"errors"
"fmt"
"go/ast"
"go/token"
"io"
"os"
"runtime/debug"
"slices"
"strconv"
"strings"
@@ -319,7 +321,34 @@ func (g *Generator) GenerateProtocol(protocol Protocol, version string) (err err
return
}
func Generate(version string, w io.Writer) (packetInfos []PacketInfo, err error) {
func ToolVersion() string {
info, ok := debug.ReadBuildInfo()
if !ok {
return "devel"
}
return info.Main.Version
}
func GoVersion() string {
info, ok := debug.ReadBuildInfo()
if !ok {
return "unknown"
}
return info.GoVersion
}
func HashFile(path string) (string, error) {
// Read from embedded filesystem since minecraft-data is embedded via go:embed
b, err := data.MinecraftData.ReadFile(path)
if err != nil {
return "", err
}
h := sha256.New()
h.Write(b)
return fmt.Sprintf("sha256:%x", h.Sum(nil)), nil
}
func Generate(version string, w io.Writer, sourceHash string) (packetInfos []PacketInfo, err error) {
protocol := Protocol{}
err = data.LoadVersionedJson(version, "protocol", &protocol)
if err != nil {
@@ -329,6 +358,15 @@ func Generate(version string, w io.Writer) (packetInfos []PacketInfo, err error)
g := &Generator{Protocol: protocol}
g.File = NewFile("v" + strings.ReplaceAll(version, ".", "_"))
// Add file header comment for IDE recognition and reproducibility
sourcePath := "minecraft-data/" + data.Paths.Data[version]["protocol"] + "/protocol.json"
toolVersion := ToolVersion()
goVersion := GoVersion()
comment := fmt.Sprintf("Code generated by strom. DO NOT EDIT.\nsource: %s (%s)\nversion: %s (%s)",
sourcePath, sourceHash, toolVersion, goVersion)
AddFileComment(g.File, comment)
AppendDecl(g.File, Import("encoding/binary", "io", "github.com/admin-else/strom/proto_base", "github.com/admin-else/strom/nbt", "github.com/google/uuid"))
g.RegisterNatives()
g.RegisterDecoderNatives()
@@ -354,7 +392,15 @@ func generateVersion(v string) (packetInfos []PacketInfo, err error) {
return
}
defer f.Close()
packetInfos, err = Generate(v, f)
// Compute hash of source protocol.json for reproducibility
sourcePath := "minecraft-data/" + data.Paths.Data[v]["protocol"] + "/protocol.json"
sourceHash, err := HashFile(sourcePath)
if err != nil {
return
}
packetInfos, err = Generate(v, f, sourceHash)
if err != nil {
return
}