-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
123 lines (103 loc) · 2.53 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"path"
"path/filepath"
)
const myName = "rei"
const (
_ = iota
exitcodeInvalidArgs
exitcodeInvalidTypeMapping
exitcodeDestFileFailed
exitcodeSourceFileInvalid
exitcodeGenFailed
)
func usage() {
fmt.Fprintln(os.Stderr, `Usage: `+myName+` -in {source} [-out {dest}] "{types}"
Generates concrete code from generic code.
{source} - (required) Source file with generic types
{dest} - (optional) Destination file
{types} - (required) Type mapping
Type mapping is in the following format:
{generic1}={concrete1},[{generic2}={concrete2}]
where concrete can be one of the following:
ConcreteType
`+"\t"+`concrete type in the same package
pkg/pkg/pkg.ConcreteType
`+"\t"+`concrete type in a different package
("pkg/pkg/go-pkg")pkg.ConcreteType
`+"\t"+`concrete type in a different package, package name
`+"\t"+`doesn't match directory name
Flags:`)
flag.PrintDefaults()
}
func fatal(code int, a ...interface{}) {
fmt.Fprintln(os.Stderr, a...)
os.Exit(code)
}
func main() {
var (
in = flag.String("in", "", "generic file")
out = flag.String("out", "", "file to save output to instead of stdout")
)
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) < 1 {
usage()
os.Exit(exitcodeInvalidArgs)
}
if len(*in) == 0 {
usage()
os.Exit(exitcodeInvalidArgs)
}
typeMapping, err := parseMapping(args[0])
if err != nil {
fatal(exitcodeInvalidTypeMapping, err)
}
var file *os.File
file, err = os.Open(*in)
if err != nil {
fatal(exitcodeSourceFileInvalid, err)
}
defer file.Close()
// if targetPackageName is empty, gen will use the source package's name.
targetPackageName := ""
var outWriter io.Writer
var outFilename string
if len(*out) > 0 {
targetDirName := path.Base(path.Dir(*out))
if rel, err := filepath.Rel(path.Dir(*in), path.Dir(*out)); err != nil || rel != "." {
// not the same directory, use directory name for generated package
targetPackageName = targetDirName
}
err = os.MkdirAll(path.Dir(*out), 0755)
if err != nil {
fatal(exitcodeDestFileFailed, err)
}
outFile, err := os.Create(*out)
if err != nil {
fatal(exitcodeDestFileFailed, err)
}
defer outFile.Close()
outWriter = outFile
outFilename = *out
} else {
outWriter = os.Stdout
outFilename = "stdout"
}
buffer := &bytes.Buffer{}
err = gen(file, *in, targetPackageName, typeMapping, buffer, outFilename)
if err != nil {
fatal(exitcodeGenFailed, err)
}
_, err = io.Copy(outWriter, buffer)
if err != nil {
fatal(exitcodeGenFailed, err)
}
}