-
Notifications
You must be signed in to change notification settings - Fork 14
/
gorums_bundle.go
260 lines (231 loc) · 6.92 KB
/
gorums_bundle.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package gengorums
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/printer"
"go/token"
"go/types"
"log"
"os"
"path"
"sort"
"strings"
"github.com/google/go-cmp/cmp"
"golang.org/x/tools/go/packages"
)
const (
devPkgPath = "./cmd/protoc-gen-gorums/dev"
)
// GenerateBundleFile generates a file with static definitions for Gorums.
func GenerateBundleFile(dst string) {
pkg := loadPackage(devPkgPath)
code := printFiles(pkg)
pkgIdentMap, reservedIdents := findIdentifiers(pkg)
src := fmt.Sprintf(`// Code generated by protoc-gen-gorums. DO NOT EDIT.
// Source files can be found in: %s
package gengorums
// pkgIdentMap maps from package name to one of the package's identifiers.
// These identifiers are used by the Gorums protoc plugin to generate import statements.
var pkgIdentMap = %#v
// reservedIdents holds the set of Gorums reserved identifiers.
// These identifiers cannot be used to define message types in a proto file.
var reservedIdents = %#v
var staticCode = `+"`%s`", devPkgPath, pkgIdentMap, reservedIdents, code)
staticContent, err := format.Source([]byte(src))
if err != nil {
log.Fatalf("formatting failed: %v", err)
}
currentContent, err := os.ReadFile(dst)
if err != nil {
log.Fatal(err)
}
if diff := cmp.Diff(currentContent, staticContent); diff != "" {
fmt.Fprintf(os.Stderr, "change detected (-current +new):\n%s", diff)
fmt.Fprintf(os.Stderr, "\nReview changes above; to revert use:\n")
fmt.Fprintf(os.Stderr, "mv %s.bak %s\n", dst, dst)
}
err = os.WriteFile(dst, []byte(staticContent), 0666)
if err != nil {
log.Fatal(err)
}
}
// loadPackage returns the parsed package.
func loadPackage(pkgPath string) *packages.Package {
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedFiles | packages.NeedSyntax | packages.NeedImports | packages.NeedTypes | packages.NeedTypesInfo,
}
pkgs, err := packages.Load(cfg, pkgPath)
if err != nil {
log.Fatalf("failed to load %s: %v", pkgPath, err)
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1)
}
// Since Load succeeded and pkgPath is a single package, the following is safe
return pkgs[0]
}
// findIdentifiers returns the imported packages as a map from package name to one of its identifiers,
// and a slice of Gorums reserved identifiers that cannot be used in proto files.
// The returned map is used by the Gorums protoc plugin to generate import statements.
func findIdentifiers(pkgInfo *packages.Package) (map[string]string, []string) {
pkgIdents := make(map[string][]string)
for id, obj := range pkgInfo.TypesInfo.Uses {
pos := pkgInfo.Fset.Position(id.Pos())
if ignore(pos.Filename) || !obj.Exported() {
// ignore identifiers in zorums generated files and unexported identifiers
continue
}
if pkg := obj.Pkg(); pkg != nil {
switch obj := obj.(type) {
case *types.Func:
if typ := obj.Type(); typ != nil {
if recv := typ.(*types.Signature).Recv(); recv != nil {
// ignore functions on non-package types
continue
}
}
addUniqueIdentifier(pkgIdents, pkg.Path(), obj.Name())
case *types.Const, *types.TypeName:
addUniqueIdentifier(pkgIdents, pkg.Path(), obj.Name())
case *types.Var:
// no need to import obj's pkg if obj is a field of a struct.
if obj.IsField() {
continue
}
addUniqueIdentifier(pkgIdents, pkg.Path(), obj.Name())
}
}
}
// Only need to store one identifier for each imported package.
// However, to ensure stable output, we sort the identifiers
// and use the first element.
pkgIdent := make(map[string]string, len(pkgIdents))
var reservedIdents []string
for path, idents := range pkgIdents {
sort.Strings(idents)
if path == pkgInfo.PkgPath {
reservedIdents = idents
continue
}
pkgIdent[path] = idents[0]
}
return pkgIdent, reservedIdents
}
func addUniqueIdentifier(pkgIdents map[string][]string, path, name string) {
currentNames := pkgIdents[path]
for _, known := range currentNames {
if name == known {
return
}
}
pkgIdents[path] = append(pkgIdents[path], name)
}
// printFiles returns the source files of pkg without package and import statements.
func printFiles(pkg *packages.Package) string {
out := &bytes.Buffer{}
for _, f := range pkg.Syntax {
// filter files in dev package that shouldn't be bundled in template_static.go
fileName := pkg.Fset.File(f.Pos()).Name()
if ignore(fileName) {
continue
}
last := f.Package
if len(f.Imports) > 0 {
imp := f.Imports[len(f.Imports)-1]
last = imp.End()
if imp.Comment != nil {
if e := imp.Comment.End(); e > last {
last = e
}
}
}
// Pretty-print package-level declarations.
// but no package or import declarations.
var buf bytes.Buffer
for _, decl := range f.Decls {
if decl, ok := decl.(*ast.GenDecl); ok && decl.Tok == token.IMPORT {
continue
}
beg, end := sourceRange(decl)
printComments(out, f.Comments, last, beg)
buf.Reset()
err := format.Node(&buf, pkg.Fset, &printer.CommentedNode{Node: decl, Comments: f.Comments})
if err != nil {
log.Fatalf("failed to format source AST node: %v", err)
}
out.Write(buf.Bytes())
last = printSameLineComment(out, f.Comments, pkg.Fset, end)
out.WriteString("\n\n")
}
printLastComments(out, f.Comments, last)
}
// escape backticks
return strings.ReplaceAll(out.String(), "`", "`+\"`\"+`")
}
// ignore files in dev folder with suffixes that shouldn't be bundled.
func ignore(file string) bool {
for _, suffix := range []string{".proto", "_test.go"} {
if strings.HasSuffix(file, suffix) {
return true
}
}
base := path.Base(file)
// ignore zorums* files
return strings.HasPrefix(base, "zorums")
}
// sourceRange returns the [beg, end) interval of source code
// belonging to decl (incl. associated comments).
func sourceRange(decl ast.Decl) (beg, end token.Pos) {
beg = decl.Pos()
end = decl.End()
var doc, com *ast.CommentGroup
switch d := decl.(type) {
case *ast.GenDecl:
doc = d.Doc
if len(d.Specs) > 0 {
switch spec := d.Specs[len(d.Specs)-1].(type) {
case *ast.ValueSpec:
com = spec.Comment
case *ast.TypeSpec:
com = spec.Comment
}
}
case *ast.FuncDecl:
doc = d.Doc
}
if doc != nil {
beg = doc.Pos()
}
if com != nil && com.End() > end {
end = com.End()
}
return beg, end
}
func printComments(out *bytes.Buffer, comments []*ast.CommentGroup, pos, end token.Pos) {
for _, cg := range comments {
if pos <= cg.Pos() && cg.Pos() < end {
for _, c := range cg.List {
fmt.Fprintln(out, c.Text)
}
fmt.Fprintln(out)
}
}
}
const infinity = 1 << 30
func printLastComments(out *bytes.Buffer, comments []*ast.CommentGroup, pos token.Pos) {
printComments(out, comments, pos, infinity)
}
func printSameLineComment(out *bytes.Buffer, comments []*ast.CommentGroup, fset *token.FileSet, pos token.Pos) token.Pos {
tf := fset.File(pos)
for _, cg := range comments {
if pos <= cg.Pos() && tf.Line(cg.Pos()) == tf.Line(pos) {
for _, c := range cg.List {
fmt.Fprintln(out, c.Text)
}
return cg.End()
}
}
return pos
}