/
doc.go
95 lines (84 loc) · 2.38 KB
/
doc.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
package cmd
import (
"fmt"
"github.com/jenkins-zh/jenkins-cli/app"
"github.com/jenkins-zh/jenkins-cli/app/i18n"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"os"
"path"
"path/filepath"
"strings"
"time"
)
// DocOption is the option for doc generating
type DocOption struct {
DocType string
}
const (
// DocTypeMarkdown represents markdown type of doc
DocTypeMarkdown string = "Markdown"
// DocTypeManPage represents man page type of doc
DocTypeManPage string = "ManPage"
)
var docOption DocOption
func init() {
rootCmd.AddCommand(docCmd)
docCmd.Flags().StringVarP(&docOption.DocType, "doc-type", "", DocTypeMarkdown,
"Which type of document will generate")
err := docCmd.RegisterFlagCompletionFunc("doc-type", func(cmd *cobra.Command, args []string, toComplete string) (
i []string, directive cobra.ShellCompDirective) {
return []string{DocTypeMarkdown, DocTypeManPage}, cobra.ShellCompDirectiveDefault
})
if err != nil {
docCmd.PrintErrf("register flag doc-type for sub-command doc failed %#v\n", err)
}
}
const (
gendocFrontmatterTemplate = `---
date: %s
title: "%s"
version: %s
---
`
)
var docCmd = &cobra.Command{
Use: "doc",
Example: `jcli doc tmp
jcli doc --doc-type ManPage /usr/local/share/man/man1`,
Short: i18n.T("Generate document for all jcl commands"),
Long: i18n.T("Generate document for all jcl commands"),
Args: cobra.MinimumNArgs(1),
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) (err error) {
outputDir := args[0]
if err = os.MkdirAll(outputDir, os.FileMode(0755)); err != nil {
return
}
switch docOption.DocType {
case DocTypeMarkdown:
now := time.Now().Format(time.RFC3339)
prepender := func(filename string) string {
name := filepath.Base(filename)
base := strings.TrimSuffix(name, path.Ext(name))
return fmt.Sprintf(gendocFrontmatterTemplate, now,
strings.Replace(base, "_", " ", -1),
app.GetVersion())
}
linkHandler := func(name string) string {
base := strings.TrimSuffix(name, path.Ext(name))
return "/commands/" + strings.ToLower(base) + "/"
}
rootCmd.DisableAutoGenTag = true
err = doc.GenMarkdownTreeCustom(rootCmd, outputDir, prepender, linkHandler)
case DocTypeManPage:
header := &doc.GenManHeader{
Title: "Jenkins CLI",
Section: "1",
Source: "Jenkins Chinese Community",
}
err = doc.GenManTree(rootCmd, header, outputDir)
}
return
},
}