This repository has been archived by the owner on Apr 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gostub.go
97 lines (82 loc) · 2.33 KB
/
gostub.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
95
96
97
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
cli "gopkg.in/urfave/cli.v1"
"github.com/mokiat/gostub/generator"
"github.com/mokiat/gostub/util"
)
func RunGoStub(c *cli.Context) {
input, err := parseInput(c)
exitOnErr(err)
config, err := prepareGeneratorConfig(input)
exitOnErr(err)
err = os.MkdirAll(filepath.Dir(input.OutputFilePath), 0755)
exitOnErr(err)
err = generator.Generate(config)
exitOnErr(err)
}
type goStubInput struct {
InterfaceName string
SourceDirectory string
StubName string
OutputFilePath string
}
func parseInput(c *cli.Context) (goStubInput, error) {
if len(c.Args()) == 0 {
return goStubInput{}, errors.New("Interface name not specified! Run `gostub --help` for more information.")
}
interfaceName := c.Args().First()
sourceDir := c.String("source")
if sourceDir == "" {
sourceDir = filepath.Dir(c.App.Name)
}
sourceDir, err := filepath.Abs(sourceDir)
if err != nil {
return goStubInput{}, err
}
stubName := c.String("name")
if stubName == "" {
stubName = interfaceName + "Stub"
}
outputFileName := c.String("output")
if outputFileName == "" {
outputFolder := filepath.Join(sourceDir, filepath.Base(sourceDir)+"_stubs")
outputFile := util.SnakeCase(interfaceName) + "_stub.go"
outputFileName = filepath.Join(outputFolder, outputFile)
}
if filepath.Ext(outputFileName) != ".go" {
return goStubInput{}, errors.New("The output file needs to have the `go` extension! Run `gostub --help` for more information.")
}
outputFileName, err = filepath.Abs(outputFileName)
if err != nil {
return goStubInput{}, err
}
return goStubInput{
InterfaceName: interfaceName,
SourceDirectory: sourceDir,
StubName: stubName,
OutputFilePath: outputFileName,
}, nil
}
func prepareGeneratorConfig(input goStubInput) (generator.Config, error) {
sourcePackageLocation, err := util.DirToImport(input.SourceDirectory)
if err != nil {
return generator.Config{}, err
}
config := generator.Config{}
config.SourcePackageLocation = sourcePackageLocation
config.SourceInterfaceName = input.InterfaceName
config.TargetFilePath = input.OutputFilePath
config.TargetPackageName = filepath.Base(filepath.Dir(input.OutputFilePath))
config.TargetStructName = input.StubName
return config, nil
}
func exitOnErr(err error) {
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
}