-
Notifications
You must be signed in to change notification settings - Fork 1
/
gen.go
94 lines (75 loc) · 1.92 KB
/
gen.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
84
85
86
87
88
89
90
91
92
93
94
package command
import (
"errors"
"flag"
"fmt"
"io/fs"
"os"
"path"
"github.com/liampulles/juryrig/internal/config"
"github.com/liampulles/juryrig/internal/parse"
"github.com/liampulles/juryrig/internal/template"
)
// Gen implements Command to generate go files.
type Gen struct {
cfgService config.Service
}
var _ Command = &Gen{} //nolint:exhaustruct
// NewGen is a constructor.
func NewGen(cfgService config.Service) *Gen {
return &Gen{
cfgService: cfgService,
}
}
// Run generates mappers, as per a the spec in the comments of the file.
func (g *Gen) Run(args []string) error {
// Read args
arguments, err := g.parseArgs(args)
if err != nil {
return err
}
// Read config
cfg, err := g.cfgService.Read()
if err != nil {
return fmt.Errorf("could not fetch config: %w", err)
}
// Parse mappers
spec, err := parse.Read(cfg.BaseFilename)
if err != nil {
return fmt.Errorf("could not parse file %s: %w", cfg.BaseFilename, err)
}
if len(spec.Mappers) == 0 {
// Nothing to do.
return nil
}
// Template
out := template.Generate(spec)
// Write out
outFile := g.adjustedOutputFile(cfg, arguments)
if err := os.WriteFile(outFile, out, fs.ModePerm); err != nil {
return fmt.Errorf("could not create %s: %w", arguments.OutputFile, err)
}
return nil
}
type arguments struct {
OutputFile string
}
var ErrInvalidArgs = errors.New("invalid args")
func (g *Gen) parseArgs(args []string) (arguments, error) {
fs := flag.NewFlagSet("gen", flag.ContinueOnError)
outputFile := fs.String("o", "", "output file")
if err := fs.Parse(args); err != nil {
fs.Usage()
return arguments{}, fmt.Errorf("could not parse args for gen: %w", err)
}
if *outputFile == "" {
return arguments{}, ErrInvalidArgs
}
return arguments{
OutputFile: *outputFile,
}, nil
}
func (g *Gen) adjustedOutputFile(cfg *config.Config, args arguments) string {
dir := path.Dir(cfg.BaseFilename)
return path.Join(dir, args.OutputFile)
}