mirror of
https://github.com/spf13/cobra
synced 2024-11-24 22:57:12 +00:00
Add Asciidoc documentation generation support
This commit is contained in:
parent
4fa4fdf5cd
commit
b41b0d7931
4 changed files with 379 additions and 0 deletions
|
@ -1,5 +1,6 @@
|
||||||
# Documentation generation
|
# Documentation generation
|
||||||
|
|
||||||
|
- [Asciidoc docs](./asciidoc_docs.md)
|
||||||
- [Man page docs](./man_docs.md)
|
- [Man page docs](./man_docs.md)
|
||||||
- [Markdown docs](./md_docs.md)
|
- [Markdown docs](./md_docs.md)
|
||||||
- [Rest docs](./rest_docs.md)
|
- [Rest docs](./rest_docs.md)
|
||||||
|
|
126
doc/ascii_docs_test.go
Normal file
126
doc/ascii_docs_test.go
Normal file
|
@ -0,0 +1,126 @@
|
||||||
|
// Copyright 2013-2022 The Cobra Authors
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package doc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/interlink-elliot/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGenAsciidocDoc(t *testing.T) {
|
||||||
|
// We generate on subcommand so we have both subcommands and parents.
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
if err := GenAsciidoc(echoCmd, buf); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
output := buf.String()
|
||||||
|
|
||||||
|
checkStringContains(t, output, echoCmd.Long)
|
||||||
|
checkStringContains(t, output, echoCmd.Example)
|
||||||
|
checkStringContains(t, output, "boolone")
|
||||||
|
checkStringContains(t, output, "rootflag")
|
||||||
|
checkStringContains(t, output, rootCmd.Short)
|
||||||
|
checkStringContains(t, output, echoSubCmd.Short)
|
||||||
|
checkStringOmits(t, output, deprecatedCmd.Short)
|
||||||
|
checkStringContains(t, output, "Options inherited from parent commands")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenAsciidocDocWithNoLongOrSynopsis(t *testing.T) {
|
||||||
|
// We generate on subcommand so we have both subcommands and parents.
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
if err := GenAsciidoc(dummyCmd, buf); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
output := buf.String()
|
||||||
|
|
||||||
|
checkStringContains(t, output, dummyCmd.Example)
|
||||||
|
checkStringContains(t, output, dummyCmd.Short)
|
||||||
|
checkStringContains(t, output, "Options inherited from parent commands")
|
||||||
|
checkStringOmits(t, output, "=== Synopsis")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenAsciidocNoHiddenParents(t *testing.T) {
|
||||||
|
// We generate on subcommand so we have both subcommands and parents.
|
||||||
|
for _, name := range []string{"rootflag", "strtwo"} {
|
||||||
|
f := rootCmd.PersistentFlags().Lookup(name)
|
||||||
|
f.Hidden = true
|
||||||
|
defer func() { f.Hidden = false }()
|
||||||
|
}
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
if err := GenAsciidoc(echoCmd, buf); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
output := buf.String()
|
||||||
|
|
||||||
|
checkStringContains(t, output, echoCmd.Long)
|
||||||
|
checkStringContains(t, output, echoCmd.Example)
|
||||||
|
checkStringContains(t, output, "boolone")
|
||||||
|
checkStringOmits(t, output, "rootflag")
|
||||||
|
checkStringContains(t, output, rootCmd.Short)
|
||||||
|
checkStringContains(t, output, echoSubCmd.Short)
|
||||||
|
checkStringOmits(t, output, deprecatedCmd.Short)
|
||||||
|
checkStringOmits(t, output, "Options inherited from parent commands")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenAsciidocNoTag(t *testing.T) {
|
||||||
|
rootCmd.DisableAutoGenTag = true
|
||||||
|
defer func() { rootCmd.DisableAutoGenTag = false }()
|
||||||
|
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
if err := GenAsciidoc(rootCmd, buf); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
output := buf.String()
|
||||||
|
|
||||||
|
checkStringOmits(t, output, "Auto generated")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenAsciidocTree(t *testing.T) {
|
||||||
|
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||||
|
tmpdir, err := ioutil.TempDir("", "test-gen-asciidoc-tree")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to create tmpdir: %v", err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(tmpdir)
|
||||||
|
|
||||||
|
if err := GenAsciidocTree(c, tmpdir); err != nil {
|
||||||
|
t.Fatalf("GenAsciidocTree failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(filepath.Join(tmpdir, "do.adoc")); err != nil {
|
||||||
|
t.Fatalf("Expected file 'do.adoc' to exist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkGenAsciidocToFile(b *testing.B) {
|
||||||
|
file, err := ioutil.TempFile("", "")
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
defer os.Remove(file.Name())
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
if err := GenAsciidoc(rootCmd, file); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
137
doc/asciidoc_docs.go
Normal file
137
doc/asciidoc_docs.go
Normal file
|
@ -0,0 +1,137 @@
|
||||||
|
// Copyright 2013-2022 The Cobra Authors
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package doc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GenAsciidoc creates asciidoc output.
|
||||||
|
func GenAsciidoc(cmd *cobra.Command, w io.Writer) error {
|
||||||
|
return GenAsciidocCustom(cmd, w, func(s string) string { return s })
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenAsciidocCustom creates custom asciidoc output.
|
||||||
|
func GenAsciidocCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
|
||||||
|
cmd.InitDefaultHelpCmd()
|
||||||
|
cmd.InitDefaultHelpFlag()
|
||||||
|
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
name := cmd.CommandPath()
|
||||||
|
|
||||||
|
buf.WriteString("## " + name + "\n\n")
|
||||||
|
buf.WriteString(cmd.Short + "\n\n")
|
||||||
|
if len(cmd.Long) > 0 {
|
||||||
|
buf.WriteString("=== Synopsis\n\n")
|
||||||
|
buf.WriteString(cmd.Long + "\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
if cmd.Runnable() {
|
||||||
|
buf.WriteString(fmt.Sprintf("----\n%s\n----\n\n", cmd.UseLine()))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(cmd.Example) > 0 {
|
||||||
|
buf.WriteString("=== Examples\n\n")
|
||||||
|
buf.WriteString(fmt.Sprintf("----\n%s\n----\n\n", cmd.Example))
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := printOptions(buf, cmd, name); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if hasSeeAlso(cmd) {
|
||||||
|
buf.WriteString("=== SEE ALSO\n\n")
|
||||||
|
if cmd.HasParent() {
|
||||||
|
parent := cmd.Parent()
|
||||||
|
pname := parent.CommandPath()
|
||||||
|
link := pname + ".adoc"
|
||||||
|
link = strings.ReplaceAll(link, " ", "_")
|
||||||
|
buf.WriteString(fmt.Sprintf("* xref:%s[%s]\t - %s\n", linkHandler(link), pname, parent.Short))
|
||||||
|
cmd.VisitParents(func(c *cobra.Command) {
|
||||||
|
if c.DisableAutoGenTag {
|
||||||
|
cmd.DisableAutoGenTag = c.DisableAutoGenTag
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
children := cmd.Commands()
|
||||||
|
sort.Sort(byName(children))
|
||||||
|
|
||||||
|
for _, child := range children {
|
||||||
|
if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cname := name + " " + child.Name()
|
||||||
|
link := cname + ".adoc"
|
||||||
|
link = strings.ReplaceAll(link, " ", "_")
|
||||||
|
buf.WriteString(fmt.Sprintf("* xref:%s[%s]\t - %s\n", linkHandler(link), cname, child.Short))
|
||||||
|
}
|
||||||
|
buf.WriteString("\n")
|
||||||
|
}
|
||||||
|
if !cmd.DisableAutoGenTag {
|
||||||
|
buf.WriteString("====== Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")
|
||||||
|
}
|
||||||
|
_, err := buf.WriteTo(w)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenAsciidocTree will generate a asciidoc page for this command and all
|
||||||
|
// descendants in the directory given. The header may be nil.
|
||||||
|
// This function may not work correctly if your command names have `-` in them.
|
||||||
|
// If you have `cmd` with two subcmds, `sub` and `sub-third`,
|
||||||
|
// and `sub` has a subcommand called `third`, it is undefined which
|
||||||
|
// help output will be in the file `cmd-sub-third.1`.
|
||||||
|
func GenAsciidocTree(cmd *cobra.Command, dir string) error {
|
||||||
|
identity := func(s string) string { return s }
|
||||||
|
emptyStr := func(s string) string { return "" }
|
||||||
|
return GenAsciidocTreeCustom(cmd, dir, emptyStr, identity)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenAsciidocTreeCustom is the the same as GenAsciidocTree, but
|
||||||
|
// with custom filePrepender and linkHandler.
|
||||||
|
func GenAsciidocTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||||
|
for _, c := range cmd.Commands() {
|
||||||
|
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := GenAsciidocTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".adoc"
|
||||||
|
filename := filepath.Join(dir, basename)
|
||||||
|
f, err := os.Create(filename)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := GenAsciidocCustom(cmd, f, linkHandler); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
115
doc/asciidoc_docs.md
Normal file
115
doc/asciidoc_docs.md
Normal file
|
@ -0,0 +1,115 @@
|
||||||
|
# Generating Asciidoc Docs For Your Own cobra.Command
|
||||||
|
|
||||||
|
Generating Asciidoc pages from a cobra command is incredibly easy. An example is as follows:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
"github.com/spf13/cobra/doc"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "test",
|
||||||
|
Short: "my test program",
|
||||||
|
}
|
||||||
|
err := doc.GenAsciidocTree(cmd, "/tmp")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
That will get you a Asciidoc document `/tmp/test.adoc`
|
||||||
|
|
||||||
|
## Generate asciidoc docs for the entire command tree
|
||||||
|
|
||||||
|
This program can actually generate docs for the kubectl command in the kubernetes project
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||||
|
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra/doc"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||||
|
err := doc.GenAsciidocTree(kubectl, "./")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
|
||||||
|
|
||||||
|
## Generate asciidoc docs for a single command
|
||||||
|
|
||||||
|
You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenAsciidoc` instead of `GenAsciidocTree`
|
||||||
|
|
||||||
|
```go
|
||||||
|
out := new(bytes.Buffer)
|
||||||
|
err := doc.GenAsciidoc(cmd, out)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This will write the asciidoc doc for ONLY "cmd" into the out, buffer.
|
||||||
|
|
||||||
|
## Customize the output
|
||||||
|
|
||||||
|
Both `GenAsciidoc` and `GenAsciidocTree` have alternate versions with callbacks to get some control of the output:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func GenAsciidocTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||||
|
//...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```go
|
||||||
|
func GenAsciidocCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
|
||||||
|
//...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `filePrepender` will prepend the return value given the full filepath to the rendered Asciidoc file. A common use case is to add front matter to use the generated documentation with [Hugo](https://gohugo.io/):
|
||||||
|
|
||||||
|
```go
|
||||||
|
const fmTemplate = `---
|
||||||
|
date: %s
|
||||||
|
title: "%s"
|
||||||
|
slug: %s
|
||||||
|
url: %s
|
||||||
|
---
|
||||||
|
`
|
||||||
|
|
||||||
|
filePrepender := func(filename string) string {
|
||||||
|
now := time.Now().Format(time.RFC3339)
|
||||||
|
name := filepath.Base(filename)
|
||||||
|
base := strings.TrimSuffix(name, path.Ext(name))
|
||||||
|
url := "/commands/" + strings.ToLower(base) + "/"
|
||||||
|
return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
|
||||||
|
|
||||||
|
```go
|
||||||
|
linkHandler := func(name string) string {
|
||||||
|
base := strings.TrimSuffix(name, path.Ext(name))
|
||||||
|
return "/commands/" + strings.ToLower(base) + "/"
|
||||||
|
}
|
||||||
|
```
|
Loading…
Reference in a new issue