Use the correct man page section for the filename

Also make header mutation cleaner.

Signed-off-by: Daniel Nephin <dnephin@gmail.com>
This commit is contained in:
Daniel Nephin 2016-06-21 12:25:26 -04:00
parent 112c7dca3a
commit 97206b3170
2 changed files with 36 additions and 14 deletions

View file

@ -45,9 +45,12 @@ func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {
return err
}
}
needToResetTitle := header.Title == ""
section := "1"
if header.Section != "" {
section = header.Section
}
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".1"
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + "." + section
filename := filepath.Join(dir, basename)
f, err := os.Create(filename)
if err != nil {
@ -55,14 +58,8 @@ func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {
}
defer f.Close()
if err := GenMan(cmd, header, f); err != nil {
return err
}
if needToResetTitle {
header.Title = ""
}
return nil
headerCopy := *header
return GenMan(cmd, &headerCopy, f)
}
// GenManHeader is a lot like the .TH header at the start of man pages. These
@ -84,9 +81,10 @@ func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
if header == nil {
header = &GenManHeader{}
}
fillHeader(header, cmd.CommandPath())
b := genMan(cmd, header)
final := mangen.Render(b)
_, err := w.Write(final)
_, err := w.Write(mangen.Render(b))
return err
}
@ -174,8 +172,6 @@ func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
// something like `rootcmd-subcmd1-subcmd2`
dashCommandName := strings.Replace(commandName, " ", "-", -1)
fillHeader(header, commandName)
buf := new(bytes.Buffer)
manPreamble(buf, header, cmd, dashCommandName)

View file

@ -4,7 +4,9 @@ import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
@ -144,6 +146,30 @@ func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {
}
}
func TestGenManTree(t *testing.T) {
cmd := &cobra.Command{
Use: "do [OPTIONS] arg1 arg2",
}
header := &GenManHeader{Section: "2"}
tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")
if err != nil {
t.Fatalf("Failed to create tempdir: %s", err.Error())
}
defer os.RemoveAll(tmpdir)
if err := GenManTree(cmd, header, tmpdir); err != nil {
t.Fatalf("GenManTree failed: %s", err.Error())
}
if _, err := os.Stat(filepath.Join(tmpdir, "do.2")); err != nil {
t.Fatalf("Expected file 'do.2' to exist")
}
if header.Title != "" {
t.Fatalf("Expected header.Title to be unmodified")
}
}
func AssertLineFound(scanner *bufio.Scanner, expectedLine string) error {
for scanner.Scan() {
line := scanner.Text()