-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (84 loc) · 2.72 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
Copyright Arata Furukawa
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"flag"
"fmt"
"cuelang.org/go/cue/ast"
cueastutil "cuelang.org/go/cue/ast/astutil"
cueformat "cuelang.org/go/cue/format"
"cuelang.org/go/cue/token"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/types/pluginpb"
encodingcue "github.com/ornew/protoc-gen-cue/internal/encoding/cue"
)
var (
Version = "(unknown)"
SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
)
func main() {
var flags flag.FlagSet
_ = flags.String("root", ".", "")
protogen.Options{
ParamFunc: flags.Set,
}.Run(func(gen *protogen.Plugin) error {
protocVersion := "(unknown)"
if v := gen.Request.GetCompilerVersion(); v != nil {
protocVersion = fmt.Sprintf("v%v.%v.%v", v.GetMajor(), v.GetMinor(), v.GetPatch())
if s := v.GetSuffix(); s != "" {
protocVersion += "-" + s
}
}
gen.SupportedFeatures = SupportedFeatures
cuegen := encodingcue.NewGenerator()
genFiles := make(map[string]*protogen.File, len(gen.FilesByPath))
for path, file := range gen.FilesByPath {
cuegen.AddFile(path, file)
if file.Generate {
genFiles[path] = file
}
}
ctx := context.Background()
for path, file := range genFiles {
node, err := cuegen.GenerateFile(ctx, path)
if err != nil {
return fmt.Errorf("encode: %w", err)
}
node.AddComment(&ast.CommentGroup{
Position: 0,
List: []*ast.Comment{
{Slash: token.Newline.Pos(), Text: "// Code generated by protoc-gen-cue. DO NOT EDIT."},
{Slash: token.Newline.Pos(), Text: "// Versions:"},
{Slash: token.Newline.Pos(), Text: "// protoc-gen-cue: " + protocVersion},
{Slash: token.Newline.Pos(), Text: "// protoc: " + Version},
{Slash: token.Newline.Pos(), Text: "// Source: " + path},
},
})
if err := cueastutil.Sanitize(node); err != nil {
return fmt.Errorf("sanitize: %w", err)
}
b, err := cueformat.Node(node)
if err != nil {
return fmt.Errorf("format: %w", err)
}
filename := file.GeneratedFilenamePrefix + "_gen.cue"
o := gen.NewGeneratedFile(filename, file.GoImportPath)
_, err = o.Write(b)
if err != nil {
return fmt.Errorf("write: %w", err)
}
}
return nil
})
}