package main import ( "fmt" "io" "os" "go.wit.com/log" ) func marshal(names map[string]string) { if argv.DryRun { for k, v := range names { log.Info(k, "=", v) } os.Exit(0) } w, _ := os.OpenFile(names["protobase"]+".marshal.pb.go", os.O_WRONLY|os.O_CREATE, 0600) fmt.Fprintln(w, "package "+names["package"]) headerComment(w) fmt.Fprintln(w, "import (") fmt.Fprintln(w, " \"google.golang.org/protobuf/encoding/protojson\"") fmt.Fprintln(w, " \"google.golang.org/protobuf/encoding/prototext\"") fmt.Fprintln(w, " \"google.golang.org/protobuf/proto\"") fmt.Fprintln(w, ")") fmt.Fprintln(w, "") if len(argv.Marshal) == 0 { marshalThing(w, names["Base"]) marshalThing(w, names["Bases"]) } else { for _, v := range argv.Marshal { marshalThing(w, v) } } } func marshalThing(w io.Writer, thing string) { fmt.Fprintln(w, "// human readable JSON") fmt.Fprintln(w, "func (v *"+thing+") FormatJSON() string {") fmt.Fprintln(w, " return protojson.Format(v)") fmt.Fprintln(w, "}") fmt.Fprintln(w, "") fmt.Fprintln(w, "// marshal json") fmt.Fprintln(w, "func (v *"+thing+") MarshalJSON() ([]byte, error) {") fmt.Fprintln(w, " return protojson.Marshal(v)") fmt.Fprintln(w, "}") fmt.Fprintln(w, "") fmt.Fprintln(w, "// unmarshal json") fmt.Fprintln(w, "func (v *"+thing+") UnmarshalJSON(data []byte) error {") fmt.Fprintln(w, " return protojson.Unmarshal(data, v)") fmt.Fprintln(w, "}") fmt.Fprintln(w, "") fmt.Fprintln(w, "// apparently this isn't stable, but it's awesomely better") fmt.Fprintln(w, "// https://protobuf.dev/reference/go/faq/#unstable-text") fmt.Fprintln(w, "// it's so great for config files, I'm using it by default to try to fix the problems with it") fmt.Fprintln(w, "func (v *"+thing+") FormatTEXT() string {") fmt.Fprintln(w, " return prototext.Format(v)") fmt.Fprintln(w, "}") fmt.Fprintln(w, "") fmt.Fprintln(w, "// unmarshalTEXT. This reads the .text config file back in after the user edits it") fmt.Fprintln(w, "func (v *"+thing+") UnmarshalTEXT(data []byte) error {") fmt.Fprintln(w, " return prototext.Unmarshal(data, v)") fmt.Fprintln(w, "}") fmt.Fprintln(w, "") fmt.Fprintln(w, "// marshal to wire. This is called winning.") fmt.Fprintln(w, "func (v *"+thing+") Marshal() ([]byte, error) {") fmt.Fprintln(w, " return proto.Marshal(v)") fmt.Fprintln(w, "}") fmt.Fprintln(w, "") fmt.Fprintln(w, "// unmarshal from wire. You have won.") fmt.Fprintln(w, "func (v *"+thing+") Unmarshal(data []byte) error {") fmt.Fprintln(w, " return proto.Unmarshal(data, v)") fmt.Fprintln(w, "}") fmt.Fprintln(w, "") }