FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
gunk/loader/loader.go at master · gunk/gunk · GitHub
gunk
/
gunk
Public
Notifications
You must be signed in to change notification settings
Fork
34
Star
341
Code
Issues
15
Pull requests
2
Actions
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Security and quality
Insights
Expand file tree
Breadcrumbs
gunk
/
loader
/
loader.go
Copy path
More file actions
More file actions
Latest commit
History
History
History
766 lines (737 loc) · 23.2 KB
Breadcrumbs
gunk
/
loader
/
loader.go
Copy path
File metadata and controls
766 lines (737 loc) · 23.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
package
loader
import
(
"fmt"
"go/ast"
"go/constant"
"go/parser"
"go/scanner"
"go/token"
"go/types"
"html/template"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/gunk/gunk/assets"
"github.com/gunk/gunk/log"
"golang.org/x/tools/go/packages"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
)
type
Loader
struct
{
Dir
string
Fset
*
token.
FileSet
// If Types is true, we parse and type-check the given packages and all
// transitive dependencies, including gunk tags. Otherwise, we only
// parse the given packages.
Types
bool
cache
map
[
string
]
*
GunkPackage
// map from import path to pkg
stack
[]
string
// fakeFiles is a list of fake Go files added to make the Go compiler pick
// up gunk files in packages without Go files.
fakeFiles
map
[
string
][]
byte
}
// addFakeFiles iterate over all module dependencies of the specified directory
// and adds a fake Go file for all directories inside the dependencies that
// only has Gunk files and no Go files.
// This allows the loader to process Gunk packages using regular Go package
// parsing code when fakeFiles is used as an overlay.
func
(
l
*
Loader
)
addFakeFiles
()
error
{
l
.
fakeFiles
=
make
(
map
[
string
][]
byte
)
// use "." if we encountered an error, for e.g. GOPATH mode
roots
:=
[]
string
{
"."
}
cmd
:=
exec
.
Command
(
"go"
,
"list"
,
"-m"
,
"-f={{.Dir}}"
,
"all"
)
cmd
.
Dir
=
l
.
Dir
if
out
,
err
:=
cmd
.
Output
();
err
==
nil
{
rootOutput
:=
strings
.
Split
(
strings
.
TrimSpace
(
string
(
out
)),
"
\n
"
)
roots
=
make
([]
string
,
0
,
len
(
rootOutput
))
for
_
,
v
:=
range
rootOutput
{
roots
=
append
(
roots
,
strings
.
TrimSpace
(
v
))
}
}
// Walk through all directories and add fake files for all packages that
// only have gunk files.
for
_
,
root
:=
range
roots
{
if
err
:=
filepath
.
Walk
(
root
,
func
(
path
string
,
info
os.
FileInfo
,
err
error
)
error
{
if
err
!=
nil
{
return
err
}
if
!
info
.
IsDir
() {
return
nil
}
infos
,
err
:=
ioutil
.
ReadDir
(
path
)
if
err
!=
nil
{
return
err
}
pkgName
:=
info
.
Name
()
// default to the directory basename
anyGunk
:=
false
for
_
,
info
:=
range
infos
{
name
:=
info
.
Name
()
if
strings
.
HasSuffix
(
name
,
".go"
) {
// has Go files; nothing to do
return
nil
}
if
strings
.
HasSuffix
(
name
,
".gunk"
) {
f
,
err
:=
parser
.
ParseFile
(
token
.
NewFileSet
(),
filepath
.
Join
(
path
,
name
),
nil
,
parser
.
PackageClauseOnly
)
// Ignore errors, since Gunk packages being
// walked but not being loaded might have
// invalid syntax.
if
err
==
nil
{
pkgName
=
f
.
Name
.
Name
}
anyGunk
=
true
break
}
}
if
!
anyGunk
{
return
nil
}
tmpPath
:=
filepath
.
Join
(
path
,
"gunkpkg.go"
)
l
.
fakeFiles
[
tmpPath
]
=
[]
byte
(
`package `
+
pkgName
)
return
nil
});
err
!=
nil
{
return
err
}
}
return
nil
}
// Load loads the Gunk packages on the provided patterns from the given dir and
// using the given fileset.
//
// Similar to Go, if a path begins with ".", it is interpreted as a file system
// path where a package is located, and "..." patterns are supported.
func
(
l
*
Loader
)
Load
(
patterns
...
string
) ([]
*
GunkPackage
,
error
) {
if
l
.
stack
==
nil
{
l
.
stack
=
make
([]
string
,
0
,
1
)
}
if
len
(
patterns
)
==
1
{
pkgPath
:=
patterns
[
0
]
if
pkg
:=
l
.
cache
[
pkgPath
];
pkg
!=
nil
{
return
[]
*
GunkPackage
{
pkg
},
nil
}
}
var
pkgs
[]
*
GunkPackage
loadFiles
:=
len
(
patterns
)
>
0
&&
strings
.
HasSuffix
(
patterns
[
0
],
".gunk"
)
if
loadFiles
{
// If we're given a number of files, construct a
// packages.Package manually. go/packages will treat foo.gunk as
// an import path instead of a file, as it's not a Go file.
pkgs
=
append
(
pkgs
,
&
GunkPackage
{
Package
: packages.
Package
{
ID
:
"command-line-arguments"
,
Name
:
""
,
// will be filled later
PkgPath
:
"command-line-arguments"
,
},
GunkFiles
:
patterns
,
})
}
else
{
// Generate fake files if it has not been initialized yet.
if
l
.
fakeFiles
==
nil
{
err
:=
l
.
addFakeFiles
()
if
err
!=
nil
{
return
nil
,
err
}
}
// Load the Gunk packages as Go packages.
cfg
:=
&
packages.
Config
{
Dir
:
l
.
Dir
,
Mode
:
packages
.
NeedName
|
packages
.
NeedFiles
,
Overlay
:
l
.
fakeFiles
,
}
lpkgs
,
err
:=
packages
.
Load
(
cfg
,
patterns
...
)
if
err
!=
nil
{
return
nil
,
err
}
for
_
,
lpkg
:=
range
lpkgs
{
pkg
:=
&
GunkPackage
{
Package
:
*
lpkg
}
findGunkFiles
(
pkg
)
if
len
(
pkg
.
GunkFiles
)
==
0
&&
len
(
pkg
.
Errors
)
==
0
{
// Not a Gunk package. Skip.
continue
}
pkgs
=
append
(
pkgs
,
pkg
)
}
}
// Add the Gunk files to each package.
for
_
,
pkg
:=
range
pkgs
{
for
_
,
v
:=
range
l
.
stack
{
if
v
==
pkg
.
PkgPath
{
// Add the current package to the stack to demonstrate the import cycle.
l
.
stack
=
append
(
l
.
stack
,
pkg
.
PkgPath
)
importLoop
:=
strings
.
Join
(
l
.
stack
,
"
\n
\t
\t
imports "
)
return
nil
,
fmt
.
Errorf
(
"import cycle not allowed:
\n
\t
%s"
,
importLoop
)
}
}
// Add entry to stack.
l
.
stack
=
append
(
l
.
stack
,
pkg
.
PkgPath
)
l
.
parseGunkPackage
(
pkg
)
l
.
validatePackage
(
pkg
)
// Pop entry from stack.
l
.
stack
=
l
.
stack
[:
len
(
l
.
stack
)
-
1
]
if
l
.
cache
==
nil
{
l
.
cache
=
make
(
map
[
string
]
*
GunkPackage
)
}
l
.
cache
[
pkg
.
PkgPath
]
=
pkg
}
return
pkgs
,
nil
}
// findGunkFiles fills a package's GunkFiles field with the gunk files found in
// the package directory. This is used when loading a Gunk package via an import
// path or a directory.
//
// Note that this requires all the source files within the package to be in the
// same directory, which is true for Go Modules and GOPATH, but not other build
// systems like Bazel.
func
findGunkFiles
(
pkg
*
GunkPackage
) {
for
_
,
gofile
:=
range
pkg
.
GoFiles
{
dir
:=
filepath
.
Dir
(
gofile
)
if
pkg
.
Dir
==
""
{
pkg
.
Dir
=
dir
}
else
if
dir
!=
pkg
.
Dir
{
pkg
.
errorf
(
ListError
,
0
,
nil
,
"multiple dirs for %s: %s %s"
,
pkg
.
PkgPath
,
pkg
.
Dir
,
dir
)
return
// we can't continue
}
}
matches
,
err
:=
filepath
.
Glob
(
filepath
.
Join
(
pkg
.
Dir
,
"*.gunk"
))
if
err
!=
nil
{
// can only be a malformed pattern; should never happen.
panic
(
err
.
Error
())
}
pkg
.
GunkFiles
=
matches
}
const
(
UnknownError
=
packages
.
UnknownError
ListError
=
packages
.
ListError
ParseError
=
packages
.
ParseError
TypeError
=
packages
.
TypeError
// Our kinds of errors. Add a gap of 10 to be sure we won't conflict
// with previous enum values.
ValidateError
=
packages
.
TypeError
+
10
+
iota
)
// Import satisfies the go/types.Importer interface.
//
// Unlike standard Go ones like go/importer and x/tools/go/packages, this one is
// adapted to load Gunk packages.
//
// Aside from that, it is very similar to standard Go importers that load from
// source.
func
(
l
*
Loader
)
Import
(
path
string
) (
*
types.
Package
,
error
) {
if
!
strings
.
Contains
(
path
,
"."
) {
cfg
:=
&
packages.
Config
{
Mode
:
packages
.
LoadTypes
}
pkgs
,
err
:=
packages
.
Load
(
cfg
,
path
)
if
err
!=
nil
{
return
nil
,
err
}
if
len
(
pkgs
)
!=
1
{
panic
(
"expected go/packages.Load to return exactly one package"
)
}
return
pkgs
[
0
].
Types
,
nil
}
pkgs
,
err
:=
l
.
Load
(
path
)
if
err
!=
nil
{
return
nil
,
err
}
if
len
(
pkgs
)
!=
1
{
panic
(
"expected Loader.Load to return exactly one package"
)
}
if
PrintErrors
(
pkgs
)
>
0
{
// NOTE: The string "error importing package" is used to detect this
// error as the Go importer does not wrap errors.
return
nil
,
fmt
.
Errorf
(
"error importing package %q"
,
path
)
}
if
pkgs
[
0
].
Types
==
nil
{
panic
(
"expected packages to have non-nil Types"
)
}
return
pkgs
[
0
].
Types
,
nil
}
type
GunkPackage
struct
{
packages.
Package
Dir
string
// for now, we require all files to be in the same dir
GunkFiles
[]
string
// absolute paths of the Gunk files
GunkSyntax
[]
*
ast.
File
// syntax trees for the files in GunkFiles
// GunkNames are unique arbitrary names for each gunk file in GunkFiles.
// We don't want to use absolute paths when referring to files in the
// CodeGeneratorRequest, because that will trigger many generators to
// write to disk.
GunkNames
[]
string
// GunkTags stores the "+gunk" tags associated with each syntax tree
// node in GunkSyntax.
GunkTags
map
[ast.
Node
][]
GunkTag
Imports
map
[
string
]
*
GunkPackage
ProtoName
string
// protobuf package name
// errorsPrinted is true if the errors have been printed. This is used to
// deduplicate errors.
errorsPrinted
bool
}
func
(
g
*
GunkPackage
)
errorf
(
kind
packages.
ErrorKind
,
tokenPos
token.
Pos
,
fset
*
token.
FileSet
,
format
string
,
args
...
interface
{}) {
g
.
addError
(
kind
,
tokenPos
,
fset
,
fmt
.
Errorf
(
format
,
args
...
))
}
func
(
g
*
GunkPackage
)
addError
(
kind
packages.
ErrorKind
,
tokenPos
token.
Pos
,
fset
*
token.
FileSet
,
err
error
) {
pos
:=
""
if
tokenPos
>
0
&&
fset
!=
nil
{
pos
=
fset
.
Position
(
tokenPos
).
String
()
}
// errors.As is intentionally unused to prevent losing context.
if
pkgErr
,
ok
:=
err
.(packages.
Error
);
ok
{
pkgErr
.
Kind
=
kind
pkgErr
.
Pos
=
pos
// Don't unnecessarily wrap the error if it is already the right type.
g
.
Errors
=
append
(
g
.
Errors
,
pkgErr
)
return
}
// Create a packages.Error to add.
msg
:=
err
.
Error
()
if
typeErr
,
ok
:=
err
.(types.
Error
);
ok
{
// Populate info if the error is a type-checking error from go/types.
// This prevents an unnecessary -: at the front of error messages.
msg
=
typeErr
.
Msg
if
pos
==
""
||
pos
==
"-"
{
pos
=
typeErr
.
Fset
.
Position
(
typeErr
.
Pos
).
String
()
}
}
g
.
Errors
=
append
(
g
.
Errors
, packages.
Error
{
Pos
:
pos
,
Msg
:
msg
,
Kind
:
kind
,
})
}
type
GunkTag
struct
{
ast.
Expr
// original expression
Type
types.
Type
// type of the expression
Value
constant.
Value
// constant value of the expression, if any
}
// parseGunkPackage parses the package's GunkFiles, and type-checks the package
// if l.Types is set.
func
(
l
*
Loader
)
parseGunkPackage
(
pkg
*
GunkPackage
) {
// Clear the name before parsing to avoid Go files from triggering package
// name mismatch
pkg
.
Name
=
""
// parse the gunk files
for
_
,
fpath
:=
range
pkg
.
GunkFiles
{
file
,
err
:=
parser
.
ParseFile
(
l
.
Fset
,
fpath
,
nil
,
parser
.
ParseComments
)
if
err
!=
nil
{
pkg
.
addError
(
ParseError
,
0
,
nil
,
err
)
continue
}
// to make the generated code independent of the current
// directory when running gunk
relPath
:=
pkg
.
PkgPath
+
"/"
+
filepath
.
Base
(
fpath
)
pkg
.
GunkNames
=
append
(
pkg
.
GunkNames
,
relPath
)
pkg
.
GunkSyntax
=
append
(
pkg
.
GunkSyntax
,
file
)
if
name
:=
file
.
Name
.
Name
;
pkg
.
Name
==
""
{
pkg
.
Name
=
name
}
else
if
pkg
.
Name
!=
name
&&
l
.
Types
{
pkg
.
errorf
(
ValidateError
,
0
,
nil
,
"gunk package name mismatch: %q %q"
,
pkg
.
Name
,
name
)
}
name
,
err
:=
protoPackageName
(
l
.
Fset
,
file
)
if
err
!=
nil
{
pkg
.
addError
(
ParseError
,
0
,
nil
,
err
)
continue
}
if
pkg
.
ProtoName
==
""
{
pkg
.
ProtoName
=
name
}
else
if
name
!=
""
&&
l
.
Types
{
pkg
.
errorf
(
ValidateError
,
0
,
nil
,
"proto package name mismatch: %q %q"
,
pkg
.
ProtoName
,
name
)
continue
}
}
if
pkg
.
ProtoName
==
""
{
pkg
.
ProtoName
=
pkg
.
Name
}
// the reported error will be handle at generate.Run function.
if
len
(
pkg
.
Errors
)
>
0
{
return
}
if
!
l
.
Types
{
return
}
pkg
.
Types
=
types
.
NewPackage
(
pkg
.
PkgPath
,
pkg
.
Name
)
tconfig
:=
&
types.
Config
{
DisableUnusedImportCheck
:
true
,
Importer
:
l
,
}
pkg
.
TypesInfo
=
&
types.
Info
{
Types
:
make
(
map
[ast.
Expr
]types.
TypeAndValue
),
Defs
:
make
(
map
[
*
ast.
Ident
]types.
Object
),
Uses
:
make
(
map
[
*
ast.
Ident
]types.
Object
),
Implicits
:
make
(
map
[ast.
Node
]types.
Object
),
Scopes
:
make
(
map
[ast.
Node
]
*
types.
Scope
),
Selections
:
make
(
map
[
*
ast.
SelectorExpr
]
*
types.
Selection
),
}
check
:=
types
.
NewChecker
(
tconfig
,
l
.
Fset
,
pkg
.
Types
,
pkg
.
TypesInfo
)
if
err
:=
check
.
Files
(
pkg
.
GunkSyntax
);
err
!=
nil
{
pkg
.
addError
(
TypeError
,
0
,
nil
,
err
)
return
}
pkg
.
Imports
=
make
(
map
[
string
]
*
GunkPackage
)
for
_
,
file
:=
range
pkg
.
GunkSyntax
{
l
.
splitGunkTags
(
pkg
,
file
)
for
_
,
spec
:=
range
file
.
Imports
{
// we can't error, since the file parsed correctly
pkgPath
,
_
:=
strconv
.
Unquote
(
spec
.
Path
.
Value
)
pkgs
,
err
:=
l
.
Load
(
pkgPath
)
if
err
!=
nil
{
// shouldn't happen?
panic
(
err
)
}
if
len
(
pkgs
)
==
1
{
pkg
.
Imports
[
pkgPath
]
=
pkgs
[
0
]
}
}
}
}
// validatePackage sanity checks a gunk package, to find common errors which are
// shared among all gunk commands.
func
(
l
*
Loader
)
validatePackage
(
pkg
*
GunkPackage
) {
for
_
,
file
:=
range
pkg
.
GunkSyntax
{
ast
.
Inspect
(
file
,
func
(
node
ast.
Node
)
bool
{
st
,
ok
:=
node
.(
*
ast.
StructType
)
if
!
ok
||
st
.
Fields
==
nil
{
return
true
}
// Look through all fields for anonymous/unnamed types.
for
_
,
field
:=
range
st
.
Fields
.
List
{
if
len
(
field
.
Names
)
<
1
{
pkg
.
errorf
(
ParseError
,
st
.
Pos
(),
l
.
Fset
,
"anonymous struct fields are not supported"
)
return
false
}
}
// Check for struct tag 'pb' and ensure that if it does exist
// it is a valid integer, and it is unique in that struct.
// The other validation should happen in format and generate
// as they both treat the same error cases differently.
usedSequences
:=
make
(
map
[
int
]
bool
,
len
(
st
.
Fields
.
List
))
jsonNamesSeen
:=
map
[
string
]
bool
{}
for
_
,
f
:=
range
st
.
Fields
.
List
{
if
f
.
Tag
==
nil
{
continue
}
fieldName
:=
f
.
Names
[
0
].
Name
str
,
_
:=
strconv
.
Unquote
(
f
.
Tag
.
Value
)
if
err
:=
validateStructTag
(
str
);
err
!=
nil
{
pkg
.
errorf
(
ValidateError
,
st
.
Pos
(),
l
.
Fset
,
"error in struct tag on %s: %w"
,
fieldName
,
err
)
continue
}
stag
:=
reflect
.
StructTag
(
str
)
val
,
ok
:=
stag
.
Lookup
(
"pb"
)
if
!
ok
||
val
==
""
{
continue
}
valJson
,
ok
:=
stag
.
Lookup
(
"json"
)
if
ok
&&
valJson
!=
""
{
if
jsonNamesSeen
[
valJson
] {
err
:=
fmt
.
Errorf
(
"json tag %q seen twice"
,
valJson
)
pkg
.
errorf
(
ValidateError
,
st
.
Pos
(),
l
.
Fset
,
"error in struct tag on %s: %w"
,
fieldName
,
err
)
continue
}
jsonNamesSeen
[
valJson
]
=
true
}
sequence
,
err
:=
strconv
.
Atoi
(
val
)
if
err
!=
nil
{
pkg
.
errorf
(
ValidateError
,
st
.
Pos
(),
l
.
Fset
,
"unable to convert tag to number on %s: %w"
,
fieldName
,
err
)
continue
}
if
usedSequences
[
sequence
] {
pkg
.
errorf
(
ValidateError
,
st
.
Pos
(),
l
.
Fset
,
"sequence %q on %s has already been used in this struct"
,
val
,
fieldName
)
continue
}
usedSequences
[
sequence
]
=
true
}
return
true
})
}
}
const
protoCommentPrefix
=
"// proto "
func
protoPackageName
(
fset
*
token.
FileSet
,
file
*
ast.
File
) (
string
,
error
) {
packageLine
:=
fset
.
Position
(
file
.
Package
).
Line
allComments:
for
_
,
cgroup
:=
range
file
.
Comments
{
for
_
,
comment
:=
range
cgroup
.
List
{
cline
:=
fset
.
Position
(
comment
.
Pos
()).
Line
if
cline
<
packageLine
{
continue
// comment before package line
}
else
if
cline
>
packageLine
{
break
allComments
// we're past the package line
}
quoted
:=
strings
.
TrimPrefix
(
comment
.
Text
,
protoCommentPrefix
)
if
quoted
==
comment
.
Text
{
continue
// comment doesn't have the prefix
}
unquoted
,
err
:=
strconv
.
Unquote
(
quoted
)
return
unquoted
,
err
}
}
// none found
return
""
,
nil
}
type
ProtoLoader
struct
{
// Dir is the absolute path from where the LoadProto method
// will load proto files.
// If empty, it will load from executing directory
Dir
string
ProtocPath
string
}
// LoadProto loads the specified protobuf packages as if they were dependencies.
//
// It does so with protoc, to leverage protoc's features such as locating the
// files, and the protoc parser to get a FileDescriptorProto out of the proto
// file content.
func
(
l
*
ProtoLoader
)
LoadProto
(
names
...
string
) ([]
*
descriptorpb.
FileDescriptorProto
,
error
) {
tmpl
:=
template
.
Must
(
template
.
New
(
"letter"
).
Parse
(
`
syntax = "proto3";
{{range $_, $name := .}}import "{{$name}}";
{{end}}
`
))
// Imports to load from in-memory
generatedFilesToLoad
:=
[]
string
{}
// Imports to load using protoc
filteredNames
:=
make
([]
string
,
0
,
len
(
names
))
// Check to see if we are trying to load any libraries that we have
// bundled with Gunk. If so, load the generated libraries. If not, use
// protoc to load those libraries from disk.
for
_
,
n
:=
range
names
{
switch
n
{
case
"google/api/annotations.proto"
:
generatedFilesToLoad
=
append
(
generatedFilesToLoad
,
"google_api_annotations.fdp"
)
case
"google/protobuf/empty.proto"
:
generatedFilesToLoad
=
append
(
generatedFilesToLoad
,
"google_protobuf_empty.fdp"
)
case
"google/protobuf/timestamp.proto"
:
generatedFilesToLoad
=
append
(
generatedFilesToLoad
,
"google_protobuf_timestamp.fdp"
)
case
"google/protobuf/duration.proto"
:
generatedFilesToLoad
=
append
(
generatedFilesToLoad
,
"google_protobuf_duration.fdp"
)
case
"google/protobuf/struct.proto"
:
generatedFilesToLoad
=
append
(
generatedFilesToLoad
,
"google_protobuf_struct.fdp"
)
case
"protoc-gen-openapiv2/options/annotations.proto"
:
generatedFilesToLoad
=
append
(
generatedFilesToLoad
,
"protoc-gen-openapiv2_options_annotations.fdp"
)
case
"xo/xo.proto"
:
generatedFilesToLoad
=
append
(
generatedFilesToLoad
,
"xo_xo.fdp"
)
default
:
filteredNames
=
append
(
filteredNames
,
n
)
}
}
var
combinedFset
descriptorpb.
FileDescriptorSet
// Use protoc to load any imports that aren't currently bundles with
// Gunk.
if
len
(
filteredNames
)
>
0
{
gunkProtoFile
:=
"gunk-proto"
if
l
.
Dir
!=
""
{
gunkProtoFile
=
filepath
.
Join
(
l
.
Dir
,
gunkProtoFile
)
}
importsFile
,
err
:=
os
.
Create
(
gunkProtoFile
)
if
err
!=
nil
{
return
nil
,
err
}
if
err
:=
tmpl
.
Execute
(
importsFile
,
filteredNames
);
err
!=
nil
{
return
nil
,
err
}
if
err
:=
importsFile
.
Close
();
err
!=
nil
{
return
nil
,
err
}
defer
os
.
Remove
(
gunkProtoFile
)
// TODO(mvdan): any way to specify stdout while being portable?
// See https://github.com/protocolbuffers/protobuf/issues/4163.
args
:=
[]
string
{
"-o/dev/stdout"
,
"--include_imports"
,
gunkProtoFile
,
}
if
l
.
Dir
!=
""
{
args
=
append
(
args
,
"-I"
+
l
.
Dir
)
}
protocPath
:=
"protoc"
if
l
.
ProtocPath
!=
""
{
protocPath
=
l
.
ProtocPath
}
cmd
:=
log
.
ExecCommand
(
protocPath
,
args
...
)
out
,
err
:=
cmd
.
Output
()
if
err
!=
nil
{
if
e
,
ok
:=
err
.(
*
exec.
ExitError
);
ok
{
return
nil
,
fmt
.
Errorf
(
"protoc %s: %s"
,
e
,
e
.
Stderr
)
}
return
nil
,
err
}
var
fset
descriptorpb.
FileDescriptorSet
if
err
:=
proto
.
Unmarshal
(
out
,
&
fset
);
err
!=
nil
{
return
nil
,
err
}
for
i
:=
0
;
i
<
len
(
fset
.
File
);
i
++
{
if
*
fset
.
File
[
i
].
Name
!=
"gunk-proto"
{
continue
}
combinedFset
.
File
=
append
(
fset
.
File
[:
i
],
fset
.
File
[
i
+
1
:]
...
)
}
}
// Load any bundled libraries.
for
_
,
fileToLoad
:=
range
generatedFilesToLoad
{
buf
,
err
:=
assets
.
ReadFile
(
fileToLoad
)
if
err
!=
nil
{
return
nil
,
err
}
var
fset
descriptorpb.
FileDescriptorSet
if
err
:=
proto
.
Unmarshal
(
buf
,
&
fset
);
err
!=
nil
{
return
nil
,
err
}
combinedFset
.
File
=
append
(
combinedFset
.
File
,
fset
.
File
...
)
}
return
combinedFset
.
File
,
nil
}
// splitGunkTags parses and typechecks gunk tags from the comments in a Gunk
// file, adding them to pkg.GunkTags and removing the source lines from each
// comment.
func
(
l
*
Loader
)
splitGunkTags
(
pkg
*
GunkPackage
,
file
*
ast.
File
) {
hadError
:=
false
ast
.
Inspect
(
file
,
func
(
node
ast.
Node
)
bool
{
if
gd
,
ok
:=
node
.(
*
ast.
GenDecl
);
ok
{
if
len
(
gd
.
Specs
)
!=
1
{
return
true
}
if
doc
:=
nodeDoc
(
gd
.
Specs
[
0
]);
doc
!=
nil
{
// Move the doc to the only spec, since we want +gunk tags
// attached to the type specs.
*
doc
=
gd
.
Doc
}
return
true
}
doc
:=
nodeDoc
(
node
)
if
doc
==
nil
{
return
true
}
docText
,
exprs
,
err
:=
SplitGunkTag
(
pkg
,
l
.
Fset
,
*
doc
)
if
err
!=
nil
{
hadError
=
true
pkg
.
addError
(
ParseError
, (
*
doc
).
Pos
(),
l
.
Fset
,
err
)
return
false
}
if
len
(
exprs
)
>
0
{
if
pkg
.
GunkTags
==
nil
{
pkg
.
GunkTags
=
make
(
map
[ast.
Node
][]
GunkTag
)
}
pkg
.
GunkTags
[
node
]
=
exprs
*
*
doc
=
*
CommentFromText
(
*
doc
,
docText
)
}
return
true
})
if
!
hadError
{
for
_
,
cg
:=
range
file
.
Comments
{
for
_
,
c
:=
range
cg
.
List
{
if
strings
.
Contains
(
c
.
Text
,
"+gunk"
) {
pkg
.
errorf
(
ParseError
,
c
.
Pos
(),
l
.
Fset
,
"gunk tag without declaration: %s"
,
c
.
Text
)
}
}
}
}
}
func
nodeDoc
(
node
ast.
Node
)
*
*
ast.
CommentGroup
{
switch
node
:=
node
.(
type
) {
case
*
ast.
File
:
return
&
node
.
Doc
case
*
ast.
Field
:
return
&
node
.
Doc
case
*
ast.
TypeSpec
:
return
&
node
.
Doc
case
*
ast.
ValueSpec
:
return
&
node
.
Doc
}
return
nil
}
// TODO(mvdan): both loader and format use CommentFromText, but it feels awkward
// to have it here.
// CommentFromText creates a multi-line comment from the given text, with its
// start and end positions matching the given node's.
func
CommentFromText
(
orig
ast.
Node
,
text
string
)
*
ast.
CommentGroup
{
group
:=
&
ast.
CommentGroup
{}
lines
:=
strings
.
Split
(
text
,
"
\n
"
)
for
i
,
line
:=
range
lines
{
comment
:=
&
ast.
Comment
{
Text
:
"// "
+
line
}
// Ensure that group.Pos() and group.End() stay on the same
// lines, to ensure that printing doesn't move the comment
// around or introduce newlines.
switch
i
{
case
0
:
comment
.
Slash
=
orig
.
Pos
()
case
len
(
lines
)
-
1
:
comment
.
Slash
=
orig
.
End
()
}
group
.
List
=
append
(
group
.
List
,
comment
)
}
return
group
}
// SplitGunkTag splits '+gunk' tags from a comment group, returning the leading
// documentation and the tags Go expressions.
//
// If pkg is not nil, the tag is also type-checked using the package's type
// information.
func
SplitGunkTag
(
pkg
*
GunkPackage
,
fset
*
token.
FileSet
,
comment
*
ast.
CommentGroup
) (
string
, []
GunkTag
,
error
) {
// Remove the comment leading and / or trailing identifier; // and /* */ and `
docLines
:=
strings
.
Split
(
comment
.
Text
(),
"
\n
"
)
var
gunkTagLines
[]
string
var
gunkTagPos
[]
int
var
commentLines
[]
string
foundGunkTag
:=
false
for
i
,
line
:=
range
docLines
{
if
strings
.
HasPrefix
(
line
,
"+gunk "
) {
// Replace "+gunk" with spaces, so that we keep the
// tag's lines all starting at the same column, for
// accurate position information later.
gunkTagLine
:=
strings
.
Replace
(
line
,
"+gunk"
,
" "
,
1
)
gunkTagLines
=
append
(
gunkTagLines
,
gunkTagLine
)
gunkTagPos
=
append
(
gunkTagPos
,
i
)
foundGunkTag
=
true
}
else
if
foundGunkTag
{
gunkTagLines
[
len
(
gunkTagLines
)
-
1
]
+=
"
\n
"
+
line
}
else
{
commentLines
=
append
(
commentLines
,
line
)
}
}
if
len
(
gunkTagLines
)
==
0
{
return
comment
.
Text
(),
nil
,
nil
}
var
tags
[]
GunkTag
for
i
,
gunkTag
:=
range
gunkTagLines
{
expr
,
err
:=
parser
.
ParseExprFrom
(
fset
,
""
,
gunkTag
,
0
)
if
err
!=
nil
{
tagPos
:=
fset
.
Position
(
comment
.
Pos
())
tagPos
.
Line
+=
gunkTagPos
[
i
]
// relative to the "+gunk" line
tagPos
.
Column
+=
len
(
"// "
)
// .Text() stripped these prefixes
return
""
,
nil
,
ErrorAbsolutePos
(
err
,
tagPos
)
}
tag
:=
GunkTag
{
Expr
:
expr
}
if
pkg
!=
nil
{
tv
,
err
:=
types
.
Eval
(
fset
,
pkg
.
Types
,
comment
.
Pos
(),
gunkTag
)
if
err
!=
nil
{
return
""
,
nil
,
err
}
tag
.
Type
,
tag
.
Value
=
tv
.
Type
,
tv
.
Value
}
tags
=
append
(
tags
,
tag
)
}
// TODO: make positions in the tag expression absolute too
strComment
:=
strings
.
Join
(
commentLines
,
"
\n
"
)
return
strings
.
TrimSpace
(
strComment
),
tags
,
nil
}
// ErrorAbsolutePos modifies all positions in err, considered to be relative to
// pos. This is useful so that the position information of syntax tree nodes
// parsed from a comment are relative to the entire file, and not only relative
// to the comment containing the source.
func
ErrorAbsolutePos
(
err
error
,
pos
token.
Position
)
error
{
list
,
ok
:=
err
.(scanner.
ErrorList
)
if
!
ok
{
return
err
}
for
i
,
err
:=
range
list
{
err
.
Pos
.
Filename
=
pos
.
Filename
err
.
Pos
.
Line
+=
pos
.
Line
err
.
Pos
.
Line
--
// since these numbers are 1-based
err
.
Pos
.
Column
+=
pos
.
Column
err
.
Pos
.
Column
--
// since these numbers are 1-based
list
[
i
]
=
err
}
return
list
}
Back
|
FazBrowse Home
|
New Git URL