-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen-const.go
87 lines (81 loc) · 2.21 KB
/
gen-const.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
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
)
var (
typeNames = flag.String("type", "", "以逗号分隔的类型名列表;必须设置")
output = flag.String("output", "", "输出文件名;默认 srcdir/<type>_gen.go")
trimprefix = flag.String("trimprefix", "", "从生成的常量名称中删除`前缀`")
buildTags = flag.String("tags", "", "要应用的生成标记的逗号分隔列表")
)
// Usage 是FLAGS包的替换使用函数。
func Usage() {
_, _ = fmt.Fprintf(os.Stderr, "gen-const 的使用方式:\n")
_, _ = fmt.Fprintf(os.Stderr, "\tgen-const [flags] -type T [directory]\n")
_, _ = fmt.Fprintf(os.Stderr, "\tgen-const [flags] -type T files... # 必须是单个包\n")
_, _ = fmt.Fprintf(os.Stderr, "Flags:\n")
flag.PrintDefaults()
}
func main() {
log.SetFlags(0)
log.SetPrefix("gen-const: ")
flag.Usage = Usage
flag.Parse()
if len(*typeNames) == 0 {
flag.Usage()
os.Exit(2)
}
// 判断输出
if *output == "" {
*output = strings.ToLower(*typeNames) + "_gen.go"
}
args := flag.Args()
if len(args) == 0 {
args = []string{"."}
}
var dir string
if len(args) == 1 && isDirectory(args[0]) {
dir = args[0]
} else {
dir = filepath.Dir(args[0])
}
var tags []string
if len(*buildTags) > 0 {
tags = strings.Split(*buildTags, ",")
}
g := Generator{
trimPrefix: *trimprefix,
}
g.parsePackage(args, tags)
headBuff := NewBuffer()
headBuff.WriteF("// Code generated by \"gen-const %s\"; DO NOT EDIT.\n", strings.Join(os.Args[1:], " "))
headBuff.WriteF("// 代码文件由 \"gen-const %s\" 生成; 不要编辑本代码文件。\n", strings.Join(os.Args[1:], " "))
headBuff.WriteS("\n")
headBuff.WriteF("package %s\n\n", g.pkg.name)
bodyBuffer := NewBuffer()
for _, typeName := range strings.Split(*typeNames, ",") {
g.generate(typeName, bodyBuffer)
}
src := g.format(headBuff, bodyBuffer)
outputName := *output
if outputName == "" {
baseName := *output
outputName = filepath.Join(dir, strings.ToLower(baseName))
}
err := os.WriteFile(outputName, src, 0644)
if err != nil {
log.Fatalf("writing output: %s", err)
}
}
func isDirectory(name string) bool {
info, err := os.Stat(name)
if err != nil {
log.Fatal(err)
}
return info.IsDir()
}