From 500d19e1c26466ef3efe0ac39f68c6cb8d160511 Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sat, 23 Apr 2022 14:59:46 -0400 Subject: [PATCH] Markdown supports commands with slashes --- doc/md_docs.go | 19 +++++++++++++------ doc/md_docs_test.go | 17 +++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/doc/md_docs.go b/doc/md_docs.go index 19d7e931..8aedc12c 100644 --- a/doc/md_docs.go +++ b/doc/md_docs.go @@ -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 diff --git a/doc/md_docs_test.go b/doc/md_docs_test.go index f3251679..76f86665 100644 --- a/doc/md_docs_test.go +++ b/doc/md_docs_test.go @@ -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 {