-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
52 lines (41 loc) · 1.15 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
package main
import (
"fmt"
"github.com/butzopower/natsu/generator"
"github.com/butzopower/natsu/parser"
"os"
"path/filepath"
"regexp"
"strings"
)
func main() {
if len(os.Args) != 4 {
failErr(fmt.Errorf("expected exactly two arguments: <pkg> <original union type> <name to generate>"))
}
sourcePkg := os.Args[1]
sourceType := os.Args[2]
nameToGenerate := os.Args[3]
unionDetails, err := parser.Parse(sourcePkg, sourceType)
if err != nil {
failErr(err)
}
sourceFile := generator.Generate(nameToGenerate, unionDetails)
goFile := os.Getenv("GOFILE")
dir := filepath.Dir(goFile)
filename := fmt.Sprintf("%s.go", toSnakeCase(nameToGenerate))
targetFilename := filepath.Join(dir, filename)
failErr(sourceFile.Save(targetFilename))
}
func failErr(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
func toSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}