Skip to content
Myr

md_docs.go

This file

Path

doc/md_docs.go

158 lines · 4.5 KiB · Go

Last changed by

refactor: apply golangci-lint autofixes, work around false positivesVille Skyttäbefore adoption4af7b64

History of this file

Take it

1// Copyright 2013-2023 The Cobra Authors2//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 at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// 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 and13// limitations under the License.1415package doc1617import (18	"bytes"19	"fmt"20	"io"21	"os"22	"path/filepath"23	"sort"24	"strings"25	"time"2627	"github.com/spf13/cobra"28)2930const markdownExtension = ".md"3132func 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	}4041	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 nil49}5051// GenMarkdown creates markdown output.52func GenMarkdown(cmd *cobra.Command, w io.Writer) error {53	return GenMarkdownCustom(cmd, w, func(s string) string { return s })54}5556// GenMarkdownCustom creates custom markdown output.57func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {58	cmd.InitDefaultHelpCmd()59	cmd.InitDefaultHelpFlag()6061	buf := new(bytes.Buffer)62	name := cmd.CommandPath()6364	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	}7071	if cmd.Runnable() {72		fmt.Fprintf(buf, "```\n%s\n```\n\n", cmd.UseLine())73	}7475	if len(cmd.Example) > 0 {76		buf.WriteString("### Examples\n\n")77		fmt.Fprintf(buf, "```\n%s\n```\n\n", cmd.Example)78	}7980	if err := printOptions(buf, cmd, name); err != nil {81		return err82	}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 + markdownExtension89			link = strings.ReplaceAll(link, " ", "_")90			fmt.Fprintf(buf, "* [%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.DisableAutoGenTag94				}95			})96		}9798		children := cmd.Commands()99		sort.Sort(byName(children))100101		for _, child := range children {102			if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {103				continue104			}105			cname := name + " " + child.Name()106			link := cname + markdownExtension107			link = strings.ReplaceAll(link, " ", "_")108			fmt.Fprintf(buf, "* [%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 err117}118119// GenMarkdownTree will generate a markdown page for this command and all120// 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 which124// help output will be in the file `cmd-sub-third.1`.125func 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}130131// GenMarkdownTreeCustom is the same as GenMarkdownTree, but132// with custom filePrepender and linkHandler.133func 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			continue137		}138		if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {139			return err140		}141	}142143	basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + markdownExtension144	filename := filepath.Join(dir, basename)145	f, err := os.Create(filename)146	if err != nil {147		return err148	}149	defer f.Close()150151	if _, err := io.WriteString(f, filePrepender(filename)); err != nil {152		return err153	}154	if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {155		return err156	}157	return nil158}