...

Source file src/github.com/spf13/cobra/doc/md_docs.go

Documentation: github.com/spf13/cobra/doc

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

View as plain text