Markdown supports commands with slashes

This commit is contained in:
Jim Schubert 2022-04-23 14:59:46 -04:00
parent 8afe9d1b56
commit 500d19e1c2
2 changed files with 30 additions and 6 deletions

View file

@ -1,4 +1,4 @@
//Copyright 2015 Red Hat Inc. All rights reserved.
// Copyright 2015 Red Hat Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -26,6 +26,14 @@ import (
"github.com/spf13/cobra"
)
func cleanCommandName(name string) string {
r := strings.NewReplacer(
" ", "_",
"/", "_",
)
return r.Replace(name)
}
func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
flags := cmd.NonInheritedFlags()
flags.SetOutput(buf)
@ -82,8 +90,7 @@ func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string)
if cmd.HasParent() {
parent := cmd.Parent()
pname := parent.CommandPath()
link := pname + ".md"
link = strings.ReplaceAll(link, " ", "_")
link := cleanCommandName(pname + ".md")
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short))
cmd.VisitParents(func(c *cobra.Command) {
if c.DisableAutoGenTag {
@ -100,8 +107,7 @@ func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string)
continue
}
cname := name + " " + child.Name()
link := cname + ".md"
link = strings.ReplaceAll(link, " ", "_")
link := cleanCommandName(cname + ".md")
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short))
}
buf.WriteString("\n")
@ -137,8 +143,9 @@ func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHa
}
}
basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".md"
basename := cleanCommandName(cmd.CommandPath()) + ".md"
filename := filepath.Join(dir, basename)
f, err := os.Create(filename)
if err != nil {
return err

View file

@ -95,6 +95,23 @@ func TestGenMdTree(t *testing.T) {
}
}
func TestGenMdTreeSlashCommands(t *testing.T) {
c := &cobra.Command{Use: "run/first [OPTIONS] arg1 arg2"}
tmpdir, err := ioutil.TempDir("", "test-gen-md-tree-slash-commands")
if err != nil {
t.Fatalf("Failed to create tmpdir: %v", err)
}
defer os.RemoveAll(tmpdir)
if err := GenMarkdownTree(c, tmpdir); err != nil {
t.Fatalf("GenMarkdownTree failed: %v", err)
}
if _, err := os.Stat(filepath.Join(tmpdir, "run_first.md")); err != nil {
t.Fatalf("Expected file 'run_first.md' to exist")
}
}
func BenchmarkGenMarkdownToFile(b *testing.B) {
file, err := ioutil.TempFile("", "")
if err != nil {