-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
83 lines (69 loc) · 1.88 KB
/
run.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
package fenneg
import (
"go/token"
"go/types"
"os"
"path"
"strings"
"github.com/alecthomas/kong"
"github.com/sirkon/errors"
"github.com/sirkon/fenneg/internal/renderer"
"github.com/sirkon/gogh"
"golang.org/x/tools/go/packages"
)
// Run is the entry point of a final utility.
func Run(
appName string,
handlers *TypesHandlers,
) error {
var args arguments
cliParser := kong.Must(
&args,
kong.Name(appName),
kong.Description("Generate records encoder and encoding dispatcher for the given interface."),
kong.UsageOnError(),
)
ctx, err := cliParser.Parse(os.Args[1:])
if err != nil {
cliParser.FatalIfErrorf(err)
}
renderer.SetStructuredErrorsPkgPath(string(args.ErrorsPath))
runCtx := &runContext{
fset: handlers.fs(),
handlers: handlers,
logger: Logger(handlers.fs()),
args: &args,
}
if err := ctx.Run(runCtx); err != nil {
return errors.Wrap(err, "run command")
}
return nil
}
func getRenderer(appName string, fset *token.FileSet, typ *types.Named) (*Project, *Go, error) {
prj, err := gogh.New(gogh.FancyFmt, renderer.NewImports)
if err != nil {
return nil, nil, err
}
pkg, err := prj.Package("", typ.Obj().Pkg().Path())
if err != nil {
return nil, nil, errors.Wrap(err, "")
}
pos := fset.Position(typ.Obj().Pos())
_, filename := path.Split(pos.Filename)
destfile := strings.TrimSuffix(filename, ".go") + "_generated.go"
r := pkg.Go(destfile, gogh.Autogen(appName))
return prj, r, nil
}
func getType(l *souceLoader, p sourcePoint, g typeGetter, what string) (*packages.Package, *types.Named, error) {
pkg, err := l.loadPkg(p.Path)
if err != nil {
return nil, nil, errors.Wrap(err, "load package").Pfx(what).Str("package-name", p.Path)
}
res, err := g(pkg, p.ID)
if err != nil {
return nil, nil, errors.Wrap(err, "load type by name").Pfx(what).
Str("package-name", p.Path).
Str("type-name", p.ID)
}
return pkg, res, nil
}