@@ -24,28 +24,38 @@ type Target struct {
24
24
25
25
// Parse Go source file or package folder and return WebRPC schema.
26
26
func Parse (filePath string ) ([]* Target , error ) {
27
- path , err := filepath .Abs (filePath )
27
+ dir , err := filepath .Abs (filePath )
28
28
if err != nil {
29
- return nil , fmt .Errorf ("failed to get directory from %q: %w" , path , err )
29
+ return nil , fmt .Errorf ("failed to get directory from %q: %w" , dir , err )
30
30
}
31
31
32
- file , err := os .Stat (path )
33
- if err != nil {
34
- return nil , fmt .Errorf ("failed to open %q" , path )
35
- }
36
- if file .Mode ().IsRegular () {
37
- // Parse all files in the given schema file's directory, so the parser can see all the pkg files.
38
- path = filepath .Dir (path )
32
+ // Parse the whole directory even if a single file is provided,
33
+ // so the parser can see all pkg files.
34
+ if file , err := os .Stat (dir ); err != nil {
35
+ return nil , fmt .Errorf ("failed to open %q" , dir )
36
+ } else if file .Mode ().IsRegular () {
37
+ dir = filepath .Dir (dir )
39
38
}
40
39
41
40
cfg := & packages.Config {
42
- Dir : path ,
43
- Mode : packages .NeedName | packages .NeedSyntax | packages .NeedTypes | packages .NeedTypesInfo | packages .NeedImports ,
41
+ Dir : dir ,
42
+ Mode : packages .NeedName | packages .NeedSyntax | packages .NeedTypes | packages .NeedTypesInfo | packages .NeedImports ,
43
+ Overlay : map [string ][]byte {},
44
44
}
45
45
46
- pkgs , err := packages .Load (cfg , path )
46
+ // Make the parser ignore all previously generated Go files to avoid the
47
+ // chicken-egg problem (ie. syntax errors in file we're currently generating).
48
+ _ = filepath .Walk (dir , func (path string , info os.FileInfo , err error ) error {
49
+ if err == nil && ! info .IsDir () && strings .HasSuffix (path , ".gen.go" ) {
50
+ // Overlay the source with an empty package name.
51
+ cfg .Overlay [path ] = []byte (fmt .Sprintf ("package %s" , filepath .Base (dir )))
52
+ }
53
+ return nil
54
+ })
55
+
56
+ pkgs , err := packages .Load (cfg , dir )
47
57
if err != nil {
48
- return nil , fmt .Errorf ("failed to load Go packages from %q: %w" , path , err )
58
+ return nil , fmt .Errorf ("failed to load Go packages from %q: %w" , dir , err )
49
59
}
50
60
51
61
// Print all errors.
@@ -60,7 +70,7 @@ func Parse(filePath string) ([]*Target, error) {
60
70
}
61
71
62
72
if len (pkgs ) != 1 {
63
- return nil , fmt .Errorf ("failed to load Go package (len=%v) from %q" , len (pkgs ), path )
73
+ return nil , fmt .Errorf ("failed to load Go package (len=%v) from %q" , len (pkgs ), dir )
64
74
}
65
75
pkg := pkgs [0 ]
66
76
0 commit comments