Skip to content
Myr

man_docs.go

This file

Path

doc/man_docs.go

245 lines · 7.2 KiB · Go

Last changed by

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

History of this file

Take it

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 at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// 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 and12// limitations under the License.1314package doc1516import (17	"bytes"18	"fmt"19	"io"20	"os"21	"path/filepath"22	"sort"23	"strconv"24	"strings"25	"time"2627	"github.com/cpuguy83/go-md2man/v2/md2man"28	"github.com/spf13/cobra"29	"github.com/spf13/pflag"30)3132// GenManTree will generate a man page for this command and all descendants33// in the directory given. The header may be nil. This function may not work34// correctly if your command names have `-` in them. If you have `cmd` with two35// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`36// it is undefined which help output will be in the file `cmd-sub-third.1`.37func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {38	return GenManTreeFromOpts(cmd, GenManTreeOptions{39		Header:           header,40		Path:             dir,41		CommandSeparator: "-",42	})43}4445// GenManTreeFromOpts generates a man page for the command and all descendants.46// The pages are written to the opts.Path directory.47func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {48	header := opts.Header49	if header == nil {50		header = &GenManHeader{}51	}52	for _, c := range cmd.Commands() {53		if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {54			continue55		}56		if err := GenManTreeFromOpts(c, opts); err != nil {57			return err58		}59	}60	section := "1"61	if header.Section != "" {62		section = header.Section63	}6465	separator := "_"66	if opts.CommandSeparator != "" {67		separator = opts.CommandSeparator68	}69	basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)70	filename := filepath.Join(opts.Path, basename+"."+section)71	f, err := os.Create(filename)72	if err != nil {73		return err74	}75	defer f.Close()7677	headerCopy := *header78	return GenMan(cmd, &headerCopy, f)79}8081// GenManTreeOptions is the options for generating the man pages.82// Used only in GenManTreeFromOpts.83type GenManTreeOptions struct {84	Header           *GenManHeader85	Path             string86	CommandSeparator string87}8889// GenManHeader is a lot like the .TH header at the start of man pages. These90// include the title, section, date, source, and manual. We will use the91// current time if Date is unset and will use "Auto generated by spf13/cobra"92// if the Source is unset.93type GenManHeader struct {94	Title   string95	Section string96	Date    *time.Time97	date    string98	Source  string99	Manual  string100}101102// GenMan will generate a man page for the given command and write it to103// w. The header argument may be nil, however obviously w may not.104func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {105	if header == nil {106		header = &GenManHeader{}107	}108	if err := fillHeader(header, cmd.CommandPath(), cmd.DisableAutoGenTag); err != nil {109		return err110	}111112	b := genMan(cmd, header)113	_, err := w.Write(md2man.Render(b))114	return err115}116117func fillHeader(header *GenManHeader, name string, disableAutoGen bool) error {118	if header.Title == "" {119		header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))120	}121	if header.Section == "" {122		header.Section = "1"123	}124	if header.Date == nil {125		now := time.Now()126		if epoch := os.Getenv("SOURCE_DATE_EPOCH"); epoch != "" {127			unixEpoch, err := strconv.ParseInt(epoch, 10, 64)128			if err != nil {129				return fmt.Errorf("invalid SOURCE_DATE_EPOCH: %v", err)130			}131			now = time.Unix(unixEpoch, 0)132		}133		header.Date = &now134	}135	header.date = (*header.Date).Format("Jan 2006")136	if header.Source == "" && !disableAutoGen {137		header.Source = "Auto generated by spf13/cobra"138	}139	return nil140}141142func manPreamble(buf io.StringWriter, header *GenManHeader, cmd *cobra.Command, dashedName string) {143	description := cmd.Long144	if len(description) == 0 {145		description = cmd.Short146	}147148	cobra.WriteStringAndCheck(buf, fmt.Sprintf(`%% "%s" "%s" "%s" "%s" "%s"149# NAME150`, header.Title, header.Section, header.date, header.Source, header.Manual))151	cobra.WriteStringAndCheck(buf, fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))152	cobra.WriteStringAndCheck(buf, "# SYNOPSIS\n")153	cobra.WriteStringAndCheck(buf, fmt.Sprintf("**%s**\n\n", cmd.UseLine()))154	cobra.WriteStringAndCheck(buf, "# DESCRIPTION\n")155	cobra.WriteStringAndCheck(buf, description+"\n\n")156}157158func manPrintFlags(buf io.StringWriter, flags *pflag.FlagSet) {159	flags.VisitAll(func(flag *pflag.Flag) {160		if len(flag.Deprecated) > 0 || flag.Hidden {161			return162		}163		format := ""164		if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {165			format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name)166		} else {167			format = fmt.Sprintf("**--%s**", flag.Name)168		}169		if len(flag.NoOptDefVal) > 0 {170			format += "["171		}172		if flag.Value.Type() == "string" {173			// put quotes on the value174			format += "=%q"175		} else {176			format += "=%s"177		}178		if len(flag.NoOptDefVal) > 0 {179			format += "]"180		}181		format += "\n\t%s\n\n"182		cobra.WriteStringAndCheck(buf, fmt.Sprintf(format, flag.DefValue, flag.Usage))183	})184}185186func manPrintOptions(buf io.StringWriter, command *cobra.Command) {187	flags := command.NonInheritedFlags()188	if flags.HasAvailableFlags() {189		cobra.WriteStringAndCheck(buf, "# OPTIONS\n")190		manPrintFlags(buf, flags)191		cobra.WriteStringAndCheck(buf, "\n")192	}193	flags = command.InheritedFlags()194	if flags.HasAvailableFlags() {195		cobra.WriteStringAndCheck(buf, "# OPTIONS INHERITED FROM PARENT COMMANDS\n")196		manPrintFlags(buf, flags)197		cobra.WriteStringAndCheck(buf, "\n")198	}199}200201func genMan(cmd *cobra.Command, header *GenManHeader) []byte {202	cmd.InitDefaultHelpCmd()203	cmd.InitDefaultHelpFlag()204205	// something like `rootcmd-subcmd1-subcmd2`206	dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)207208	buf := new(bytes.Buffer)209210	manPreamble(buf, header, cmd, dashCommandName)211	manPrintOptions(buf, cmd)212	if len(cmd.Example) > 0 {213		buf.WriteString("# EXAMPLE\n")214		buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example))215	}216	if hasSeeAlso(cmd) {217		buf.WriteString("# SEE ALSO\n")218		seealsos := make([]string, 0)219		if cmd.HasParent() {220			parentPath := cmd.Parent().CommandPath()221			dashParentPath := strings.Replace(parentPath, " ", "-", -1)222			seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section)223			seealsos = append(seealsos, seealso)224			cmd.VisitParents(func(c *cobra.Command) {225				if c.DisableAutoGenTag {226					cmd.DisableAutoGenTag = c.DisableAutoGenTag227				}228			})229		}230		children := cmd.Commands()231		sort.Sort(byName(children))232		for _, c := range children {233			if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {234				continue235			}236			seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)237			seealsos = append(seealsos, seealso)238		}239		buf.WriteString(strings.Join(seealsos, ", ") + "\n")240	}241	if !cmd.DisableAutoGenTag {242		buf.WriteString(fmt.Sprintf("# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006")))243	}244	return buf.Bytes()245}