Debian Codegraph @

lib/proto/cmd/star2proto/star2proto.go

raw
1 // The star2proto command executes a Starlark file and prints a protocol
2 // message, which it expects to find in a module-level variable named 'result'.
3 //
4 // THIS COMMAND IS EXPERIMENTAL AND ITS INTERFACE MAY CHANGE.
5 package main
6
7 // TODO(adonovan): add features to make this a useful tool for querying,
8 // converting, and building messages in proto, JSON, and YAML.
9 // - define operations for reading and writing files.
10 // - support (e.g.) querying a proto file given a '-e expr' flag.
11 // This will need a convenient way to put the relevant descriptors in scope.
12
13 import (
14 "flag"
15 "fmt"
16 "log"
17 "os"
18 "strings"
19
20 "go.starlark.net/lib/json"
21 starlarkproto "go.starlark.net/lib/proto"
22 "go.starlark.net/resolve"
23 "go.starlark.net/starlark"
24 "google.golang.org/protobuf/encoding/protojson"
25 "google.golang.org/protobuf/encoding/prototext"
26 "google.golang.org/protobuf/proto"
27 "google.golang.org/protobuf/reflect/protodesc"
28 "google.golang.org/protobuf/reflect/protoreflect"
29 "google.golang.org/protobuf/reflect/protoregistry"
30 "google.golang.org/protobuf/types/descriptorpb"
31 )
32
33 // flags
34 var (
35 outputFlag = flag.String("output", "text", "output format (text, wire, json)")
36 varFlag = flag.String("var", "result", "the variable to output")
37 descriptors = flag.String("descriptors", "", "comma-separated list of names of files containing proto.FileDescriptorProto messages")
38 )
39
40 // obsolete Starlark dialect flags
41 func init() {
42 flag.BoolVar(&resolve.AllowFloat, "fp", true, "obsolete; no effect")
43 flag.BoolVar(&resolve.AllowLambda, "lambda", true, "obsolete; no effect")
44 flag.BoolVar(&resolve.AllowNestedDef, "nesteddef", true, "obsolete; no effect")
45 flag.BoolVar(&resolve.AllowSet, "set", true, "obsolete; no effect")
46 }
47
48 func main() {
49 log.SetPrefix("star2proto: ")
50 log.SetFlags(0)
51 flag.Parse()
52 if len(flag.Args()) != 1 {
53 fatalf("requires a single Starlark file name")
54 }
55 filename := flag.Args()[0]
56
57 // By default, use the linked-in descriptors
58 // (very few in star2proto, e.g. descriptorpb itself).
59 pool := protoregistry.GlobalFiles
60
61 // Load a user-provided FileDescriptorSet produced by a command such as:
62 // $ protoc --descriptor_set_out=foo.fds foo.proto
63 if *descriptors != "" {
64 var fdset descriptorpb.FileDescriptorSet
65 for i, filename := range strings.Split(*descriptors, ",") {
66 data, err := os.ReadFile(filename)
67 if err != nil {
68 log.Fatalf("--descriptors[%d]: %s", i, err)
69 }
70 // Accumulate into the repeated field of FileDescriptors.
71 if err := (proto.UnmarshalOptions{Merge: true}).Unmarshal(data, &fdset); err != nil {
72 log.Fatalf("%s does not contain a proto2.FileDescriptorSet: %v", filename, err)
73 }
74 }
75
76 files, err := protodesc.NewFiles(&fdset)
77 if err != nil {
78 log.Fatalf("protodesc.NewFiles: could not build FileDescriptor index: %v", err)
79 }
80 pool = files
81 }
82
83 // Execute the Starlark file.
84 thread := &starlark.Thread{
85 Print: func(_ *starlark.Thread, msg string) { fmt.Println(msg) },
86 }
87 starlarkproto.SetPool(thread, pool)
88 predeclared := starlark.StringDict{
89 "proto": starlarkproto.Module,
90 "json": json.Module,
91 }
92 globals, err := starlark.ExecFile(thread, filename, nil, predeclared)
93 if err != nil {
94 if evalErr, ok := err.(*starlark.EvalError); ok {
95 fatalf("%s", evalErr.Backtrace())
96 } else {
97 fatalf("%s", err)
98 }
99 }
100
101 // Print the output variable as a message.
102 // TODO(adonovan): this is clumsy.
103 // Let the user call print(), or provide an expression on the command line.
104 result, ok := globals[*varFlag]
105 if !ok {
106 fatalf("%s must define a module-level variable named %q", filename, *varFlag)
107 }
108 msgwrap, ok := result.(*starlarkproto.Message)
109 if !ok {
110 fatalf("got %s, want proto.Message, for %q", result.Type(), *varFlag)
111 }
112 msg := msgwrap.Message()
113
114 // -output
115 var marshal func(protoreflect.ProtoMessage) ([]byte, error)
116 switch *outputFlag {
117 case "wire":
118 marshal = proto.Marshal
119
120 case "text":
121 marshal = prototext.MarshalOptions{Multiline: true, Indent: "\t"}.Marshal
122
123 case "json":
124 marshal = protojson.MarshalOptions{Multiline: true, Indent: "\t"}.Marshal
125
126 default:
127 fatalf("unsupported -output format: %s", *outputFlag)
128 }
129 data, err := marshal(msg)
130 if err != nil {
131 fatalf("%s", err)
132 }
133 os.Stdout.Write(data)
134 }
135
136 func fatalf(format string, args ...any) {
137 fmt.Fprintf(os.Stderr, "star2proto: ")
138 fmt.Fprintf(os.Stderr, format, args...)
139 fmt.Fprintln(os.Stderr)
140 os.Exit(1)
141 }