rest_docs.go
This file
Path
doc/rest_docs.go
186 lines · 5.2 KiB · Go
Last changed by
refactor: apply golangci-lint autofixes, work around false positivesVille Skyttäbefore adoption4af7b64
History of this fileTake 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)2930func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error {31 flags := cmd.NonInheritedFlags()32 flags.SetOutput(buf)33 if flags.HasAvailableFlags() {34 buf.WriteString("Options\n")35 buf.WriteString("~~~~~~~\n\n::\n\n")36 flags.PrintDefaults()37 buf.WriteString("\n")38 }3940 parentFlags := cmd.InheritedFlags()41 parentFlags.SetOutput(buf)42 if parentFlags.HasAvailableFlags() {43 buf.WriteString("Options inherited from parent commands\n")44 buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n")45 parentFlags.PrintDefaults()46 buf.WriteString("\n")47 }48 return nil49}5051// defaultLinkHandler for default ReST hyperlink markup52func defaultLinkHandler(name, ref string) string {53 return fmt.Sprintf("`%s <%s.rst>`_", name, ref)54}5556// GenReST creates reStructured Text output.57func GenReST(cmd *cobra.Command, w io.Writer) error {58 return GenReSTCustom(cmd, w, defaultLinkHandler)59}6061// GenReSTCustom creates custom reStructured Text output.62func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error {63 cmd.InitDefaultHelpCmd()64 cmd.InitDefaultHelpFlag()6566 buf := new(bytes.Buffer)67 name := cmd.CommandPath()6869 short := cmd.Short70 long := cmd.Long71 if len(long) == 0 {72 long = short73 }74 ref := strings.ReplaceAll(name, " ", "_")7576 buf.WriteString(".. _" + ref + ":\n\n")77 buf.WriteString(name + "\n")78 buf.WriteString(strings.Repeat("-", len(name)) + "\n\n")79 buf.WriteString(short + "\n\n")80 buf.WriteString("Synopsis\n")81 buf.WriteString("~~~~~~~~\n\n")82 buf.WriteString("\n" + long + "\n\n")8384 if cmd.Runnable() {85 fmt.Fprintf(buf, "::\n\n %s\n\n", cmd.UseLine())86 }8788 if len(cmd.Example) > 0 {89 buf.WriteString("Examples\n")90 buf.WriteString("~~~~~~~~\n\n")91 fmt.Fprintf(buf, "::\n\n%s\n\n", indentString(cmd.Example, " "))92 }9394 if err := printOptionsReST(buf, cmd, name); err != nil {95 return err96 }97 if hasSeeAlso(cmd) {98 buf.WriteString("SEE ALSO\n")99 buf.WriteString("~~~~~~~~\n\n")100 if cmd.HasParent() {101 parent := cmd.Parent()102 pname := parent.CommandPath()103 ref = strings.ReplaceAll(pname, " ", "_")104 fmt.Fprintf(buf, "* %s \t - %s\n", linkHandler(pname, ref), parent.Short)105 cmd.VisitParents(func(c *cobra.Command) {106 if c.DisableAutoGenTag {107 cmd.DisableAutoGenTag = c.DisableAutoGenTag108 }109 })110 }111112 children := cmd.Commands()113 sort.Sort(byName(children))114115 for _, child := range children {116 if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {117 continue118 }119 cname := name + " " + child.Name()120 ref = strings.ReplaceAll(cname, " ", "_")121 fmt.Fprintf(buf, "* %s \t - %s\n", linkHandler(cname, ref), child.Short)122 }123 buf.WriteString("\n")124 }125 if !cmd.DisableAutoGenTag {126 buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n")127 }128 _, err := buf.WriteTo(w)129 return err130}131132// GenReSTTree will generate a ReST page for this command and all133// descendants in the directory given.134// This function may not work correctly if your command names have `-` in them.135// If you have `cmd` with two subcmds, `sub` and `sub-third`,136// and `sub` has a subcommand called `third`, it is undefined which137// help output will be in the file `cmd-sub-third.1`.138func GenReSTTree(cmd *cobra.Command, dir string) error {139 emptyStr := func(s string) string { return "" }140 return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)141}142143// GenReSTTreeCustom is the same as GenReSTTree, but144// with custom filePrepender and linkHandler.145func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {146 for _, c := range cmd.Commands() {147 if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {148 continue149 }150 if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil {151 return err152 }153 }154155 basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".rst"156 filename := filepath.Join(dir, basename)157 f, err := os.Create(filename)158 if err != nil {159 return err160 }161 defer f.Close()162163 if _, err := io.WriteString(f, filePrepender(filename)); err != nil {164 return err165 }166 if err := GenReSTCustom(cmd, f, linkHandler); err != nil {167 return err168 }169 return nil170}171172// indentString adapted from: https://github.com/kr/text/blob/main/indent.go173func indentString(s, p string) string {174 var res []byte175 b := []byte(s)176 prefix := []byte(p)177 bol := true178 for _, c := range b {179 if bol && c != '\n' {180 res = append(res, prefix...)181 }182 res = append(res, c)183 bol = c == '\n'184 }185 return string(res)186}