-
Notifications
You must be signed in to change notification settings - Fork 14
/
gorums_bundle.go
296 lines (270 loc) · 7.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package gengorums
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/printer"
"go/token"
"go/types"
"io/ioutil"
"log"
"os"
"path"
"sort"
"strings"
"unicode"
"github.com/google/go-cmp/cmp"
"golang.org/x/tools/go/loader"
)
const (
devPkgPath = "./cmd/protoc-gen-gorums/dev"
)
// GenerateBundleFile generates a file with static definitions for Gorums.
func GenerateBundleFile(dst string) {
pkgIdent, reservedIdents, code := bundle(devPkgPath)
// escape backticks
escaped := strings.ReplaceAll(string(code), "`", "`+\"`\"+`")
src := "// Code generated by protoc-gen-gorums. DO NOT EDIT.\n" +
"// Source files can be found in: " + devPkgPath + "\n\n" +
"package gengorums\n\n" +
generatePkgMap(pkgIdent, reservedIdents) +
"var staticCode = `" + escaped + "`\n"
staticContent, err := format.Source([]byte(src))
if err != nil {
log.Fatalf("formatting failed: %v", err)
}
currentContent, err := ioutil.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 = ioutil.WriteFile(dst, []byte(staticContent), 0666)
if err != nil {
log.Fatal(err)
}
}
func generatePkgMap(pkgs map[string]string, reservedIdents []string) string {
var keys []string
for k := range pkgs {
keys = append(keys, k)
}
sort.Strings(keys)
var buf bytes.Buffer
buf.WriteString(`
// pkgIdentMap maps from package name to one of the package's identifiers.
// These identifiers are used by the Gorums protoc plugin to generate
// appropriate import statements.
`)
buf.WriteString("var pkgIdentMap = map[string]string{\n")
for _, imp := range keys {
buf.WriteString("\t" + `"`)
buf.WriteString(imp)
buf.WriteString(`": "`)
buf.WriteString(pkgs[imp])
buf.WriteString(`",` + "\n")
}
buf.WriteString("}\n\n")
buf.WriteString(`
// reservedIdents holds the set of Gorums reserved identifiers.
// These identifiers cannot be used to define message types in a proto file.
`)
buf.WriteString("var reservedIdents = []string{\n")
for _, ident := range reservedIdents {
buf.WriteString("\t" + `"`)
buf.WriteString(ident)
buf.WriteString(`",` + "\n")
}
buf.WriteString("}\n\n")
return buf.String()
}
// findIdentifiers examines the given package to find all imported packages,
// and one used identifier in that imported package. These identifiers are
// used by the Gorums protoc plugin to generate appropriate import statements.
func findIdentifiers(fset *token.FileSet, info *loader.PackageInfo) (map[string]string, []string) {
packagePath := info.Pkg.Path()
pkgIdents := make(map[string][]string)
for id, obj := range info.Uses {
pos := fset.Position(id.Pos())
if strings.Contains(pos.Filename, "zorums") {
// ignore identifiers in zorums generated files
continue
}
r := []rune(obj.Name())
if unicode.IsLower(r[0]) {
// ignore 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 == packagePath {
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)
}
// bundle returns a slice with the code for the given src package without imports.
// The returned map contains packages to be imported along with one identifier
// using the relevant import path.
// Loosly based on x/tools/cmd/bundle
func bundle(src string) (map[string]string, []string, []byte) {
conf := loader.Config{ParserMode: parser.ParseComments, Build: &build.Default}
conf.Import(src)
lprog, err := conf.Load()
if err != nil {
log.Fatalf("failed to load Go package: %v", err)
}
// Because there was a single Import call and Load succeeded,
// InitialPackages is guaranteed to hold the sole requested package.
info := lprog.InitialPackages()[0]
var out bytes.Buffer
printFiles(&out, lprog.Fset, info)
pkgIdentMap, reservedIdents := findIdentifiers(lprog.Fset, info)
return pkgIdentMap, reservedIdents, out.Bytes()
}
func printFiles(out *bytes.Buffer, fset *token.FileSet, info *loader.PackageInfo) {
for _, f := range info.Files {
// filter files in dev package that shouldn't be bundled in template_static.go
fileName := 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, 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, fset, end)
out.WriteString("\n\n")
}
printLastComments(out, f.Comments, last)
}
}
// 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
}