-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
76 lines (69 loc) · 1.51 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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/json-iterator/tinygo/generator"
)
var cwd string
var fset = token.NewFileSet()
var allImports = map[string]string{}
func init() {
var err error
cwd, err = os.Getwd()
if err != nil {
reportError(err)
return
}
}
func main() {
typeSpec := locateTypeSpec()
outputPath := filepath.Join(cwd, fmt.Sprintf("%s_json.go", typeSpec.Name.Name))
os.WriteFile(outputPath, generator.Generate(fset, allImports, typeSpec), 0644)
}
func reportError(err error) {
panic(err)
}
func locateTypeSpec() *ast.TypeSpec {
goline, err := strconv.Atoi(os.Getenv("GOLINE"))
if err != nil {
reportError(err)
return nil
}
f, err := parser.ParseFile(fset, os.Getenv("GOFILE"), nil, parser.ParseComments)
if err != nil {
reportError(err)
return nil
}
for _, importSpec := range f.Imports {
path, _ := strconv.Unquote(importSpec.Path.Value)
if importSpec.Name == nil {
parts := strings.Split(path, "/")
allImports[parts[len(parts)-1]] = path
} else {
allImports[importSpec.Name.Name] = path
}
}
var located *ast.TypeSpec
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.TypeSpec:
if goline+1 == fset.Position(x.Pos()).Line {
located = x
}
return false
}
return true
})
if located == nil {
reportError(fmt.Errorf("%s:%s go generate should be marked just before type definition",
os.Getenv("GOFILE"), os.Getenv("GOLINE")))
return nil
}
return located
}