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