forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
244 lines (201 loc) · 5.33 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/gookit/color"
"github.com/snail-plus/goutil"
"github.com/snail-plus/goutil/arrutil"
"github.com/snail-plus/goutil/fsutil"
"github.com/snail-plus/goutil/strutil"
)
var (
hidden = []string{"netutil", "internal"}
nameMap = map[string]string{
"arr": "array/Slice",
"str": "string",
"sys": "system",
"math": "math/Number",
"fs": "fileSystem",
"fmt": "formatting",
"test": "testing",
"dump": "dump",
"structs": "struct",
"json": "JSON",
"cli": "CLI",
"env": "ENV",
}
pkgDesc = map[string]map[string]string{
"en": {
"arr": "Package arrutil provides some util functions for array, slice",
},
"zh-CN": {
"arr": "`arrutil` 包提供一些辅助函数,用于数组、切片处理",
},
}
allowLang = map[string]int{
"en": 1,
"zh-CN": 1,
}
)
type genOptsSt struct {
lang string
output string
template string
tplDir string
}
func (o genOptsSt) tplFilename() string {
if o.lang == "en" {
return "README.md.tpl"
}
return fmt.Sprintf("README.%s.md.tpl", o.lang)
}
func (o genOptsSt) tplFilepath(givePath string) string {
if givePath != "" {
return path.Join(o.tplDir, givePath)
}
return path.Join(o.tplDir, o.tplFilename())
}
var genOpts = genOptsSt{}
func bindingFlags() {
flag.StringVar(&genOpts.lang, "l", "en", "package desc message language. allow: en, zh-CN")
flag.StringVar(&genOpts.output,
"o",
"./metadata.log",
"the result output file. if is 'stdout', will direct print it.",
)
flag.StringVar(&genOpts.tplDir,
"t",
"./internal/template",
"the template file dir, use for generate, will inject metadata to the template.\nsee ./internal/template/*.tpl",
)
flag.Usage = func() {
color.Info.Println("Collect and dump all exported functions for goutil\n")
// fmt.Println()
color.Comment.Println("Options:")
flag.PrintDefaults()
color.Comment.Println("Example:")
fmt.Println(`
go run ./internal/gendoc -o stdout
go run ./internal/gendoc -o stdout -l zh-CN
go run ./internal/gendoc -o README.md
go run ./internal/gendoc -o README.md -l zh-CN`)
}
}
// go run ./internal/gendoc -h
// go run ./internal/gendoc
func main() {
bindingFlags()
flag.Parse()
ms, err := filepath.Glob("./*/*.go")
goutil.PanicIfErr(err)
var out io.Writer
var toFile bool
if genOpts.output == "stdout" {
out = os.Stdout
} else {
toFile = true
out, err = os.OpenFile(genOpts.output, os.O_CREATE|os.O_WRONLY, fsutil.DefaultFilePerm)
goutil.PanicIfErr(err)
// close after handle
defer out.(*os.File).Close()
}
// want output by template file
// var tplFile *os.File
var tplBody []byte
if genOpts.tplDir != "" {
tplFile := genOpts.tplFilepath("")
color.Info.Println("- read template file contents from", tplFile)
tplBody = fsutil.MustReadFile(tplFile)
}
basePkg := "github.com/snail-plus/goutil"
// collect functions
buf := collectPgkFunc(ms, basePkg)
// write to output
if len(tplBody) > 0 {
_, err = fmt.Fprint(out, strings.Replace(string(tplBody), "{{pgkFuncs}}", buf.String(), 1))
} else {
_, err = buf.WriteTo(out)
}
goutil.PanicIfErr(err)
if toFile {
color.Info.Println("OK. write result to the", genOpts.output)
}
}
func collectPgkFunc(ms []string, basePkg string) *bytes.Buffer {
var name, dirname string
var pkgFuncs = make(map[string][]string)
// match func
reg := regexp.MustCompile(`func [A-Z]\w+\(.*\).*`)
buf := new(bytes.Buffer)
color.Info.Println("- find and collect exported functions...")
for _, filename := range ms { // for each go file
// "jsonutil/jsonutil_test.go"
if strings.HasSuffix(filename, "_test.go") {
continue
}
// "sysutil/sysutil_windows.go"
if strings.HasSuffix(filename, "_windows.go") {
continue
}
idx := strings.IndexRune(filename, '/')
dir := filename[:idx]
if arrutil.StringsHas(hidden, dir) {
continue
}
pkgPath := basePkg + "/" + dir
if ss, ok := pkgFuncs[pkgPath]; ok {
pkgFuncs[pkgPath] = append(ss, "added")
} else {
if len(pkgFuncs) > 0 { // end of prev package.
bufWriteln(buf, "```")
// load example file.
partReadme := genOpts.tplDir + "/part-" + dirname + ".md"
// color.Infoln("- try read part readme from", partReadme)
partBody := fsutil.ReadExistFile(partReadme)
if len(partBody) > 0 {
color.Infoln("- find and inject part doc for the package:", name)
bufWriteln(buf, string(partBody))
}
}
dirname = dir
name = dir
if strings.HasSuffix(dir, "util") {
name = dir[:len(dir)-4]
}
if setTitle, ok := nameMap[name]; ok {
name = setTitle
}
// now: name is package name.
bufWriteln(buf, "\n###", strutil.UpperFirst(name))
bufWritef(buf, "\n> Package `%s`\n\n", pkgPath)
pkgFuncs[pkgPath] = []string{"xx"}
bufWriteln(buf, "```go")
}
// read contents
text := fsutil.MustReadFile(filename)
lines := reg.FindAllString(string(text), -1)
if len(lines) > 0 {
bufWriteln(buf, "// source at", filename)
for _, line := range lines {
bufWriteln(buf, strings.TrimRight(line, "{ "))
}
}
}
if len(pkgFuncs) > 0 {
bufWriteln(buf, "```")
}
return buf
}
func bufWritef(buf *bytes.Buffer, f string, a ...interface{}) {
_, _ = fmt.Fprintf(buf, f, a...)
}
func bufWriteln(buf *bytes.Buffer, a ...interface{}) {
_, _ = fmt.Fprintln(buf, a...)
}