-
Notifications
You must be signed in to change notification settings - Fork 75
/
godoc.go
121 lines (94 loc) · 2.12 KB
/
godoc.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
package main
import (
"bytes"
"io"
"os"
"sort"
"text/template"
"github.com/mitchellh/cli"
)
// CommandDoc stores command documentation strings.
type CommandDoc struct {
Name string
Synopsis string
Help string
}
func runGodoc(commands map[string]cli.CommandFactory) int {
f, err := os.Create("doc.go")
if err != nil {
return 1
}
defer f.Close()
commandDocs := newCommandDocs(commands)
var buf bytes.Buffer
if err := tmpl(&buf, docTmpl, commandDocs); err != nil {
return 1
}
err = tmpl(f, godocTmpl, struct {
Content string
}{
Content: buf.String(),
})
if err != nil {
return 1
}
return 0
}
func newCommandDocs(commands map[string]cli.CommandFactory) []CommandDoc {
keys := make([]string, 0, len(commands))
// Extract key (command name) for sort.
for key, _ := range commands {
keys = append(keys, key)
}
sort.Strings(keys)
commandDocs := make([]CommandDoc, 0, len(commands))
for _, key := range keys {
if key == "version" {
continue
}
cmdFunc, ok := commands[key]
if !ok {
// Should not reach here..
panic("command not found: " + key)
}
cmd, _ := cmdFunc()
commandDocs = append(commandDocs, CommandDoc{
Name: key,
Synopsis: cmd.Synopsis(),
Help: cmd.Help(),
})
}
return commandDocs
}
// tmpl evaluates template content with data
// and write them to writer, return error if any
func tmpl(wr io.Writer, content string, data interface{}) error {
tmpl, err := template.New("doc").Parse(content)
if err != nil {
return err
}
if err := tmpl.Execute(wr, data); err != nil {
return err
}
return nil
}
var docTmpl = `Command gcli generates a skeleton (codes and its directory structure) you need to start building CLI tool by Golang.
https://github.com/tcnksm/gcli
Usage:
gcli [-version] [-help] <command> [<options>]
Available commands:
{{ range .}}
{{ .Name | printf "%-11s"}} {{ .Synopsis }}{{end}}
Use "gcli <command> -help" for more information about command.
{{ range . }}
{{ .Synopsis }}
{{ .Help }}
{{ end }}
`
var godocTmpl = `// DO NOT EDIT THIS FILE.
// THIS FILE IS GENERATED BY GO GENERATE.
/*
{{ .Content }}
*/
package main
`