1//Copyright 2015 Red Hat Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package doc
15
16import (
17	"bytes"
18	"fmt"
19	"io"
20	"os"
21	"path/filepath"
22	"sort"
23	"strings"
24	"time"
25
26	"github.com/spf13/cobra"
27)
28
29func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
30	flags := cmd.NonInheritedFlags()
31	flags.SetOutput(buf)
32	if flags.HasFlags() {
33		buf.WriteString("### Options\n\n```\n")
34		flags.PrintDefaults()
35		buf.WriteString("```\n\n")
36	}
37
38	parentFlags := cmd.InheritedFlags()
39	parentFlags.SetOutput(buf)
40	if parentFlags.HasFlags() {
41		buf.WriteString("### Options inherited from parent commands\n\n```\n")
42		parentFlags.PrintDefaults()
43		buf.WriteString("```\n\n")
44	}
45	return nil
46}
47
48// GenMarkdown creates markdown output.
49func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
50	return GenMarkdownCustom(cmd, w, func(s string) string { return s })
51}
52
53// GenMarkdownCustom creates custom markdown output.
54func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
55	buf := new(bytes.Buffer)
56	name := cmd.CommandPath()
57
58	short := cmd.Short
59	long := cmd.Long
60	if len(long) == 0 {
61		long = short
62	}
63
64	buf.WriteString("## " + name + "\n\n")
65	buf.WriteString(short + "\n\n")
66	buf.WriteString("### Synopsis\n\n")
67	buf.WriteString("\n" + long + "\n\n")
68
69	if cmd.Runnable() {
70		buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))
71	}
72
73	if len(cmd.Example) > 0 {
74		buf.WriteString("### Examples\n\n")
75		buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))
76	}
77
78	if err := printOptions(buf, cmd, name); err != nil {
79		return err
80	}
81	if hasSeeAlso(cmd) {
82		buf.WriteString("### SEE ALSO\n")
83		if cmd.HasParent() {
84			parent := cmd.Parent()
85			pname := parent.CommandPath()
86			link := pname + ".md"
87			link = strings.Replace(link, " ", "_", -1)
88			buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short))
89			cmd.VisitParents(func(c *cobra.Command) {
90				if c.DisableAutoGenTag {
91					cmd.DisableAutoGenTag = c.DisableAutoGenTag
92				}
93			})
94		}
95
96		children := cmd.Commands()
97		sort.Sort(byName(children))
98
99		for _, child := range children {
100			if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
101				continue
102			}
103			cname := name + " " + child.Name()
104			link := cname + ".md"
105			link = strings.Replace(link, " ", "_", -1)
106			buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short))
107		}
108		buf.WriteString("\n")
109	}
110	if !cmd.DisableAutoGenTag {
111		buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")
112	}
113	_, err := buf.WriteTo(w)
114	return err
115}
116
117// GenMarkdownTree will generate a markdown page for this command and all
118// descendants in the directory given. The header may be nil.
119// This function may not work correctly if your command names have `-` in them.
120// If you have `cmd` with two subcmds, `sub` and `sub-third`,
121// and `sub` has a subcommand called `third`, it is undefined which
122// help output will be in the file `cmd-sub-third.1`.
123func GenMarkdownTree(cmd *cobra.Command, dir string) error {
124	identity := func(s string) string { return s }
125	emptyStr := func(s string) string { return "" }
126	return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
127}
128
129func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
130	for _, c := range cmd.Commands() {
131		if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
132			continue
133		}
134		if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
135			return err
136		}
137	}
138
139	basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
140	filename := filepath.Join(dir, basename)
141	f, err := os.Create(filename)
142	if err != nil {
143		return err
144	}
145	defer f.Close()
146
147	if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
148		return err
149	}
150	if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {
151		return err
152	}
153	return nil
154}
155