spf13--cobra/doc/md_docs.go
Matthew Fisher 070f6ff0a8 enable changing the command separator when generating markdown
In certain cases, hyphens are preferred over underscores for command
separators.
2017-11-03 13:11:27 -07:00

198 lines
5.8 KiB
Go

//Copyright 2015 Red Hat Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doc
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/spf13/cobra"
)
// GenMarkdownOptions is the options for generating the man pages.
// Used only in GenMarkdownWithOpts.
type GenMarkdownOptions struct {
Writer io.Writer
LinkHandler func(string) string
CommandSeparator string
}
// GenMarkdownTreeOptions is the options for generating the man pages.
// Used only in GenMarkdownTreeWithOpts.
type GenMarkdownTreeOptions struct {
CommandSeparator string
FilePrepender func(string) string
LinkHandler func(string) string
}
func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
flags := cmd.NonInheritedFlags()
flags.SetOutput(buf)
if flags.HasFlags() {
buf.WriteString("### Options\n\n```\n")
flags.PrintDefaults()
buf.WriteString("```\n\n")
}
parentFlags := cmd.InheritedFlags()
parentFlags.SetOutput(buf)
if parentFlags.HasFlags() {
buf.WriteString("### Options inherited from parent commands\n\n```\n")
parentFlags.PrintDefaults()
buf.WriteString("```\n\n")
}
return nil
}
// GenMarkdown creates markdown output.
func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
return GenMarkdownCustom(cmd, w, func(s string) string { return s })
}
// GenMarkdownWithOpts creates markdown output.
func GenMarkdownWithOpts(cmd *cobra.Command, opts GenMarkdownOptions) error {
cmd.InitDefaultHelpCmd()
cmd.InitDefaultHelpFlag()
buf := new(bytes.Buffer)
name := cmd.CommandPath()
short := cmd.Short
long := cmd.Long
if len(long) == 0 {
long = short
}
buf.WriteString("## " + name + "\n\n")
buf.WriteString(short + "\n\n")
buf.WriteString("### Synopsis\n\n")
buf.WriteString("\n" + long + "\n\n")
if cmd.Runnable() {
buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))
}
if len(cmd.Example) > 0 {
buf.WriteString("### Examples\n\n")
buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))
}
if err := printOptions(buf, cmd, name); err != nil {
return err
}
if hasSeeAlso(cmd) {
buf.WriteString("### SEE ALSO\n")
if cmd.HasParent() {
parent := cmd.Parent()
pname := parent.CommandPath()
link := pname + ".md"
link = strings.Replace(link, " ", opts.CommandSeparator, -1)
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, opts.LinkHandler(link), parent.Short))
cmd.VisitParents(func(c *cobra.Command) {
if c.DisableAutoGenTag {
cmd.DisableAutoGenTag = c.DisableAutoGenTag
}
})
}
children := cmd.Commands()
sort.Sort(byName(children))
for _, child := range children {
if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
continue
}
cname := name + " " + child.Name()
link := cname + ".md"
link = strings.Replace(link, " ", opts.CommandSeparator, -1)
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, opts.LinkHandler(link), child.Short))
}
buf.WriteString("\n")
}
if !cmd.DisableAutoGenTag {
buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")
}
_, err := buf.WriteTo(opts.Writer)
return err
}
// GenMarkdownCustom creates custom markdown output.
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
return GenMarkdownWithOpts(cmd, GenMarkdownOptions{
Writer: w,
LinkHandler: linkHandler,
CommandSeparator: "_",
})
}
// GenMarkdownTree will generate a markdown page for this command and all
// descendants in the directory given. The header may be nil.
// This function may not work correctly if your command names have `-` in them.
// If you have `cmd` with two subcmds, `sub` and `sub-third`,
// and `sub` has a subcommand called `third`, it is undefined which
// help output will be in the file `cmd-sub-third.1`.
func GenMarkdownTree(cmd *cobra.Command, dir string) error {
identity := func(s string) string { return s }
emptyStr := func(s string) string { return "" }
return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
}
// GenMarkdownTreeWithOpts is the the same as GenMarkdownTree.
func GenMarkdownTreeWithOpts(cmd *cobra.Command, dir string, opts GenMarkdownTreeOptions) error {
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
continue
}
if err := GenMarkdownTreeWithOpts(c, dir, opts); err != nil {
return err
}
}
basename := strings.Replace(cmd.CommandPath(), " ", opts.CommandSeparator, -1) + ".md"
filename := filepath.Join(dir, basename)
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
if _, err := io.WriteString(f, opts.FilePrepender(filename)); err != nil {
return err
}
markdownOpts := GenMarkdownOptions{
Writer: f,
LinkHandler: opts.LinkHandler,
CommandSeparator: opts.CommandSeparator,
}
if err := GenMarkdownWithOpts(cmd, markdownOpts); err != nil {
return err
}
return nil
}
// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
// with custom filePrepender and linkHandler.
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
return GenMarkdownTreeWithOpts(cmd, dir, GenMarkdownTreeOptions{
FilePrepender: filePrepender,
LinkHandler: linkHandler,
CommandSeparator: "_",
})
}