Merge pull request #294 from dnephin/fix_man_page_gen_bugs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fix man page gen bugs
authored by Eric Paris · committed by GitHub · parents bc81c21, e291587 · Browse files · 2 files·+88 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+88 added−34 removed
- other:+88 added−34 removed
Provenance
- Commit
6a8bd97- Tree
cc1e7b1- Author
Eric Paris <eparis@redhat.com>- Committer
GitHub <noreply@github.com>- Parent 1
bc81c21- Parent 2
e291587
2 files changed+88 added−34 removed
modified:doc/man_docs_test.go+41 added
2 unmodified lines3 import (4 "bufio"5 "bytes"6 "fmt"7+ "io/ioutil"8 "os"9+ "path/filepath"10 "strings"11 "testing"12 13 "github.com/spf13/cobra"116 unmodified lines130 t.Fatal(fmt.Errorf("Second line after SEE ALSO wasn't correct: %s", err.Error()))131 }132 }133 134+func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {135+ cmd := &cobra.Command{}136+ flags := cmd.Flags()137+ flags.StringP("foo", "f", "default", "Foo flag")138+ flags.MarkShorthandDeprecated("foo", "don't use it no more")139+140+ out := new(bytes.Buffer)141+ manPrintFlags(out, flags)142+143+ expected := "**--foo**=\"default\"\n\tFoo flag\n\n"144+ if out.String() != expected {145+ t.Fatalf("Expected %s, but got %s", expected, out.String())146+ }147+}148+149+func TestGenManTree(t *testing.T) {150+ cmd := &cobra.Command{151+ Use: "do [OPTIONS] arg1 arg2",152+ }153+ header := &GenManHeader{Section: "2"}154+ tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")155+ if err != nil {156+ t.Fatalf("Failed to create tempdir: %s", err.Error())157+ }158+ defer os.RemoveAll(tmpdir)159+160+ if err := GenManTree(cmd, header, tmpdir); err != nil {161+ t.Fatalf("GenManTree failed: %s", err.Error())162+ }163+164+ if _, err := os.Stat(filepath.Join(tmpdir, "do.2")); err != nil {165+ t.Fatalf("Expected file 'do.2' to exist")166+ }167+168+ if header.Title != "" {169+ t.Fatalf("Expected header.Title to be unmodified")170+ }171+}172+173 func AssertLineFound(scanner *bufio.Scanner, expectedLine string) error {174 for scanner.Scan() {175 line := scanner.Text()176 if line == expectedLine {26 unmodified linesmodified:doc/man_docs.go+47 added-34 removed
32 unmodified lines33 // correctly if your command names have - in them. If you have `cmd` with two34 // subcmds, `sub` and `sub-third`. And `sub` has a subcommand called `third`35 // it is undefined which help output will be in the file `cmd-sub-third.1`.36 func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {37+ return GenManTreeFromOpts(cmd, GenManTreeOptions{38+ Header: header,39+ Path: dir,40+ CommandSeparator: "_",41+ })42+}43+44+// GenManTreeFromOpts generates a man page for the command and all descendants.45+// The pages are written to the opts.Path directory.46+func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {47+ header := opts.Header48 if header == nil {49 header = &GenManHeader{}50 }51 for _, c := range cmd.Commands() {52 if !c.IsAvailableCommand() || c.IsHelpCommand() {53 continue54 }44- if err := GenManTree(c, header, dir); err != nil {55+ if err := GenManTreeFromOpts(c, opts); err != nil {56 return err57 }58 }48- needToResetTitle := header.Title == ""59+ section := "1"60+ if header.Section != "" {61+ section = header.Section62+ }63 64+ separator := "_"65+ if opts.CommandSeparator != "" {66+ separator = opts.CommandSeparator67+ }50- basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".1"51- filename := filepath.Join(dir, basename)68+ basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)69+ filename := filepath.Join(opts.Path, basename + "." + section)70 f, err := os.Create(filename)71 if err != nil {72 return err73 }74 defer f.Close()75 58- if err := GenMan(cmd, header, f); err != nil {59- return err60- }76+ headerCopy := *header77+ return GenMan(cmd, &headerCopy, f)78+}79 62- if needToResetTitle {63- header.Title = ""64- }65- return nil80+type GenManTreeOptions struct {81+ Header *GenManHeader82+ Path string83+ CommandSeparator string84 }85 86 // GenManHeader is a lot like the .TH header at the start of man pages. These87 // include the title, section, date, source, and manual. We will use the13 unmodified lines101 func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {102 if header == nil {103 header = &GenManHeader{}104 }105+ fillHeader(header, cmd.CommandPath())106+107 b := genMan(cmd, header)88- final := mangen.Render(b)89- _, err := w.Write(final)108+ _, err := w.Write(mangen.Render(b))109 return err110 }111 112 func fillHeader(header *GenManHeader, name string) {12 unmodified lines125 header.Source = "Auto generated by spf13/cobra"126 }127 }128 110-func manPreamble(out io.Writer, header *GenManHeader, name, short, long string) {111- dashName := strings.Replace(name, " ", "-", -1)129+func manPreamble(out io.Writer, header *GenManHeader, cmd *cobra.Command, dashedName string) {130+ description := cmd.Long131+ if len(description) == 0 {132+ description = cmd.Short133+ }134+135 fmt.Fprintf(out, `%% %s(%s)%s136 %% %s137 %% %s138 # NAME139 `, header.Title, header.Section, header.date, header.Source, header.Manual)117- fmt.Fprintf(out, "%s \\- %s\n\n", dashName, short)140+ fmt.Fprintf(out, "%s \\- %s\n\n", dashedName, cmd.Short)141 fmt.Fprintf(out, "# SYNOPSIS\n")119- fmt.Fprintf(out, "**%s** [OPTIONS]\n\n", name)142+ fmt.Fprintf(out, "**%s**\n\n", cmd.UseLine())143 fmt.Fprintf(out, "# DESCRIPTION\n")121- fmt.Fprintf(out, "%s\n\n", long)144+ fmt.Fprintf(out, "%s\n\n", description)145 }146 147 func manPrintFlags(out io.Writer, flags *pflag.FlagSet) {148 flags.VisitAll(func(flag *pflag.Flag) {149 if len(flag.Deprecated) > 0 || flag.Hidden {150 return151 }152 format := ""130- if len(flag.Shorthand) > 0 {131- format = "**-%s**, **--%s**"153+ if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {154+ format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name)155 } else {133- format = "%s**--%s**"156+ format = fmt.Sprintf("**--%s**", flag.Name)157 }158 if len(flag.NoOptDefVal) > 0 {159 format = format + "["160 }6 unmodified lines167 if len(flag.NoOptDefVal) > 0 {168 format = format + "]"169 }170 format = format + "\n\t%s\n\n"148- fmt.Fprintf(out, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)171+ fmt.Fprintf(out, format, flag.DefValue, flag.Usage)172 })173 }174 175 func manPrintOptions(out io.Writer, command *cobra.Command) {11 unmodified lines187 }188 }189 190 func genMan(cmd *cobra.Command, header *GenManHeader) []byte {168- // something like `rootcmd subcmd1 subcmd2`169- commandName := cmd.CommandPath()191 // something like `rootcmd-subcmd1-subcmd2`171- dashCommandName := strings.Replace(commandName, " ", "-", -1)192+ dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)193 173- fillHeader(header, commandName)174-194 buf := new(bytes.Buffer)195 177- short := cmd.Short178- long := cmd.Long179- if len(long) == 0 {180- long = short181- }182-183- manPreamble(buf, header, commandName, short, long)196+ manPreamble(buf, header, cmd, dashCommandName)197 manPrintOptions(buf, cmd)198 if len(cmd.Example) > 0 {199 fmt.Fprintf(buf, "# EXAMPLE\n")200 fmt.Fprintf(buf, "```\n%s\n```\n", cmd.Example)31 unmodified lines