/
main.go
76 lines (67 loc) · 1.77 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"
"log"
"os"
"path/filepath"
"github.com/spf13/cobra"
)
var opts struct {
StructName string
InterfaceName string
OutputFile string
Debug bool
}
func main() {
cmd := &cobra.Command{
Use: "ifacegen [dir]",
Args: cobra.MaximumNArgs(1),
SilenceErrors: true,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) (err error) {
if len(args) == 0 {
filename, ok := os.LookupEnv("GOFILE")
if !ok {
return fmt.Errorf("must provide package directory")
}
dir, err := os.Getwd()
if err != nil {
return err
}
data, err := os.ReadFile(filepath.Join(dir, filename))
if err != nil {
return err
}
opts.StructName = getStructName(data)
args = append(args, dir)
}
if opts.StructName == "" {
return fmt.Errorf("must provide StructName")
}
if opts.OutputFile == "" {
opts.OutputFile = fmt.Sprintf("zz_%s.iface.go", opts.StructName)
}
if opts.Debug {
fmt.Printf("PackageDir: %s\n", args[0])
fmt.Printf("StructName: %s\n", opts.StructName)
fmt.Printf("OutputFile: %s\n", opts.OutputFile)
}
files, err := ParsePackage(args[0], opts.StructName)
if err != nil {
return err
}
data, err := GenerateFile(files)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(args[0], opts.OutputFile), data, 0644)
},
}
cmd.Flags().StringVar(&opts.StructName, "struct", "", "name of struct to generate interface for")
cmd.Flags().StringVar(&opts.InterfaceName, "iface", "Interface", "name of generated interface")
cmd.Flags().StringVarP(&opts.OutputFile, "output", "o", "", "name of output file")
cmd.Flags().BoolVar(&opts.Debug, "debug", false, "")
if err := cmd.Execute(); err != nil {
log.Fatal(err)
}
}