forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gendocs.go
98 lines (86 loc) · 2.05 KB
/
gendocs.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
package gendocs
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"sort"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/printers"
)
type Examples []*unstructured.Unstructured
func (x Examples) Len() int { return len(x) }
func (x Examples) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x Examples) Less(i, j int) bool {
xi, _ := x[i].Object["fullName"].(string)
xj, _ := x[j].Object["fullName"].(string)
return xi < xj
}
func GenDocs(cmd *cobra.Command, filename string) error {
out := new(bytes.Buffer)
templateFile, err := filepath.Abs("hack/clibyexample/template")
if err != nil {
return err
}
template, err := ioutil.ReadFile(templateFile)
if err != nil {
return err
}
examples := extractExamples(cmd)
items := []runtime.Object{}
for _, example := range examples {
items = append(items, example)
}
printer, err := printers.GetStandardPrinter(
&printers.OutputOptions{
FmtType: "template",
FmtArg: string(template),
AllowMissingKeys: false,
},
false, nil, nil, nil, nil, printers.PrintOptions{})
if err != nil {
return err
}
err = printer.PrintObj(&kapi.List{
ListMeta: metav1.ListMeta{},
Items: items,
}, out)
if err != nil {
return err
}
outFile, err := os.Create(filename)
if err != nil {
return err
}
defer outFile.Close()
_, err = outFile.Write(out.Bytes())
if err != nil {
return err
}
return nil
}
func extractExamples(cmd *cobra.Command) Examples {
objs := Examples{}
for _, c := range cmd.Commands() {
if len(c.Deprecated) > 0 {
continue
}
objs = append(objs, extractExamples(c)...)
}
if cmd.HasExample() {
o := &unstructured.Unstructured{
Object: make(map[string]interface{}),
}
o.Object["name"] = cmd.Name()
o.Object["fullName"] = cmd.CommandPath()
o.Object["description"] = cmd.Short
o.Object["examples"] = cmd.Example
objs = append(objs, o)
}
sort.Sort(objs)
return objs
}