2024-11-29 11:56:57 -06:00
|
|
|
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"])
|
2024-11-29 12:00:19 -06:00
|
|
|
headerComment(w)
|
2024-11-29 11:56:57 -06:00
|
|
|
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, "")
|
|
|
|
|
|
|
|
marshalThing(w, names["Base"])
|
|
|
|
marshalThing(w, names["Bases"])
|
|
|
|
}
|
|
|
|
|
|
|
|
func marshalThing(w io.Writer, thing string) {
|
|
|
|
fmt.Fprintln(w, "// human readable JSON")
|
|
|
|
fmt.Fprintln(w, "func (r *"+thing+") FormatJSON() string {")
|
|
|
|
fmt.Fprintln(w, " return protojson.Format(r)")
|
|
|
|
fmt.Fprintln(w, "}")
|
|
|
|
fmt.Fprintln(w, "")
|
2024-11-29 12:03:35 -06:00
|
|
|
fmt.Fprintln(w, "// apparently this isn't stable")
|
2024-11-29 11:56:57 -06:00
|
|
|
fmt.Fprintln(w, "// https://protobuf.dev/reference/go/faq/#unstable-text")
|
2024-11-29 12:03:35 -06:00
|
|
|
fmt.Fprintln(w, "// but it's so awesome I'm using it by default to try to fix the problems with it")
|
2024-11-29 11:56:57 -06:00
|
|
|
fmt.Fprintln(w, "func (r *"+thing+") FormatTEXT() string {")
|
|
|
|
fmt.Fprintln(w, " return prototext.Format(r)")
|
|
|
|
fmt.Fprintln(w, "}")
|
|
|
|
fmt.Fprintln(w, "")
|
|
|
|
fmt.Fprintln(w, "// marshal json")
|
|
|
|
fmt.Fprintln(w, "func (r *"+thing+") MarshalJSON() ([]byte, error) {")
|
|
|
|
fmt.Fprintln(w, " return protojson.Marshal(r)")
|
|
|
|
fmt.Fprintln(w, "}")
|
|
|
|
fmt.Fprintln(w, "")
|
|
|
|
fmt.Fprintln(w, "// unmarshal")
|
|
|
|
fmt.Fprintln(w, "func (r *"+thing+") UnmarshalJSON(data []byte) error {")
|
|
|
|
fmt.Fprintln(w, " return protojson.Unmarshal(data, r)")
|
|
|
|
fmt.Fprintln(w, "}")
|
|
|
|
fmt.Fprintln(w, "")
|
|
|
|
fmt.Fprintln(w, "// marshal to wire")
|
|
|
|
fmt.Fprintln(w, "func (r *"+thing+") Marshal() ([]byte, error) {")
|
|
|
|
fmt.Fprintln(w, " return proto.Marshal(r)")
|
|
|
|
fmt.Fprintln(w, "}")
|
|
|
|
fmt.Fprintln(w, "")
|
|
|
|
fmt.Fprintln(w, "// unmarshal from wire")
|
|
|
|
fmt.Fprintln(w, "func (r *"+thing+") Unmarshal(data []byte) error {")
|
|
|
|
fmt.Fprintln(w, " return proto.Unmarshal(data, r)")
|
|
|
|
fmt.Fprintln(w, "}")
|
|
|
|
fmt.Fprintln(w, "")
|
|
|
|
}
|