forked from mrsinham/goreset
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
105 lines (83 loc) · 1.96 KB
/
main.go
File metadata and controls
105 lines (83 loc) · 1.96 KB
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
package main
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"os/exec"
"runtime"
"strings"
"io"
"github.com/jawher/mow.cli"
)
func main() {
app := cli.App("goreset", "generate reset method")
chosenPackage := app.StringArg("PKG", "", "package to walk to")
chosenStruct := app.StringArg("STRUCTURE", "", "structure to attach the Reset() method to")
// writeType
write := app.BoolOpt("w write", false, "writes the result in file")
exitOnError := func(err error) {
fmt.Println(err)
os.Exit(1)
}
var err error
app.Action = func() {
err = parsePackage(chosenPackage, chosenStruct, write, nil)
if err != nil {
exitOnError(err)
}
}
err = app.Run(os.Args)
if err != nil {
exitOnError(err)
}
}
// parsePackage launchs the generation
func parsePackage(pkg *string, structure *string, write *bool, customWriter io.Writer) error {
if pkg == nil {
return errors.New("no directory submitted")
}
if strings.TrimSpace(*pkg) == "" {
return errors.New("directory empty submitted")
}
var writeToFile bool
if write != nil && *write {
writeToFile = true
}
// reinstall package to be sure that we are uptodate
c := exec.Command(runtime.GOROOT()+"/bin/go", []string{"install", *pkg}...)
c.Stderr = os.Stderr
err := c.Run()
if err != nil {
return err
}
var gopath string
if paths := strings.Split(os.Getenv("GOPATH"), ":"); len(paths) != 0 {
gopath = paths[0]
}
// get the path of the package
pkgdir := gopath + "/src/" + *pkg
fset := token.NewFileSet()
var f map[string]*ast.Package
f, err = parser.ParseDir(fset, pkgdir, nil, 0)
if err != nil {
return err
}
for i := range f {
var files []*ast.File
for j := range f[i].Files {
files = append(files, f[i].Files[j])
}
for j := range f[i].Files {
if !strings.Contains(j, "_reset.go") {
err = generate(fset, f[i].Files[j], files, pkgdir, i, j, *structure, writeToFile, customWriter)
if err != nil {
return err
}
}
}
}
return nil
}