mcobra.go

 1package mcobra
 2
 3import (
 4	"github.com/muesli/mango"
 5	mpflag "github.com/muesli/mango-pflag"
 6	"github.com/spf13/cobra"
 7)
 8
 9// NewManPageFromCobra creates a new mango.ManPage from a cobra.Command.
10func NewManPage(section uint, c *cobra.Command) (*mango.ManPage, error) {
11	manPage := mango.NewManPage(section, c.Name(), c.Short).
12		WithLongDescription(c.Long)
13
14	if err := AddCommand(manPage, c); err != nil {
15		return nil, err
16	}
17	return manPage, nil
18}
19
20// AddCommand adds a cobra.Command to a mango.ManPage.
21func AddCommand(m *mango.ManPage, c *cobra.Command) error {
22	return addCommandTree(m, c, nil)
23}
24
25func addCommandTree(m *mango.ManPage, c *cobra.Command, parent *mango.Command) error {
26	var item *mango.Command
27	if parent == nil {
28		// set root command
29		item = mango.NewCommand(c.Name(), "", "")
30		m.Root = *item
31	} else {
32		item = mango.NewCommand(c.Name(), c.Short, c.Use)
33		if err := parent.AddCommand(item); err != nil {
34			return err
35		}
36	}
37
38	// add commands
39	if c.HasSubCommands() {
40		for _, sub := range c.Commands() {
41			if sub.Hidden {
42				// ignore hidden commands
43				continue
44			}
45
46			if err := addCommandTree(m, sub, item); err != nil {
47				return err
48			}
49		}
50	}
51
52	// add flags
53	if c.HasFlags() {
54		c.Flags().VisitAll(mpflag.PFlagCommandVisitor(item))
55	}
56	if c.HasPersistentFlags() {
57		c.PersistentFlags().VisitAll(mpflag.PFlagCommandVisitor(item))
58	}
59
60	return nil
61}