Skip to content
Myr

yaml_docs.go

This file

Path

doc/yaml_docs.go

174 lines · 4.8 KiB · Go

Last changed by

YAML documentation contains "Usage" (#1037)Alessandro (Ale) Segalabefore adoptioned7b60e

History of this file

Take it

1// Copyright 2016 French Ben. All rights reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package doc1516import (17	"fmt"18	"io"19	"os"20	"path/filepath"21	"sort"22	"strings"2324	"github.com/spf13/cobra"25	"github.com/spf13/pflag"26	"gopkg.in/yaml.v2"27)2829type cmdOption struct {30	Name         string31	Shorthand    string `yaml:",omitempty"`32	DefaultValue string `yaml:"default_value,omitempty"`33	Usage        string `yaml:",omitempty"`34}3536type cmdDoc struct {37	Name             string38	Synopsis         string      `yaml:",omitempty"`39	Description      string      `yaml:",omitempty"`40	Usage            string      `yaml:",omitempty"`41	Options          []cmdOption `yaml:",omitempty"`42	InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"`43	Example          string      `yaml:",omitempty"`44	SeeAlso          []string    `yaml:"see_also,omitempty"`45}4647// GenYamlTree creates yaml structured ref files for this command and all descendants48// in the directory given. This function may not work49// correctly if your command names have `-` in them. If you have `cmd` with two50// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`51// it is undefined which help output will be in the file `cmd-sub-third.1`.52func GenYamlTree(cmd *cobra.Command, dir string) error {53	identity := func(s string) string { return s }54	emptyStr := func(s string) string { return "" }55	return GenYamlTreeCustom(cmd, dir, emptyStr, identity)56}5758// GenYamlTreeCustom creates yaml structured ref files.59func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {60	for _, c := range cmd.Commands() {61		if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {62			continue63		}64		if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil {65			return err66		}67	}6869	basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml"70	filename := filepath.Join(dir, basename)71	f, err := os.Create(filename)72	if err != nil {73		return err74	}75	defer f.Close()7677	if _, err := io.WriteString(f, filePrepender(filename)); err != nil {78		return err79	}80	if err := GenYamlCustom(cmd, f, linkHandler); err != nil {81		return err82	}83	return nil84}8586// GenYaml creates yaml output.87func GenYaml(cmd *cobra.Command, w io.Writer) error {88	return GenYamlCustom(cmd, w, func(s string) string { return s })89}9091// GenYamlCustom creates custom yaml output.92func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {93	cmd.InitDefaultHelpCmd()94	cmd.InitDefaultHelpFlag()9596	yamlDoc := cmdDoc{}97	yamlDoc.Name = cmd.CommandPath()9899	yamlDoc.Synopsis = forceMultiLine(cmd.Short)100	yamlDoc.Description = forceMultiLine(cmd.Long)101102	if cmd.Runnable() {103		yamlDoc.Usage = cmd.UseLine()104	}105106	if len(cmd.Example) > 0 {107		yamlDoc.Example = cmd.Example108	}109110	flags := cmd.NonInheritedFlags()111	if flags.HasFlags() {112		yamlDoc.Options = genFlagResult(flags)113	}114	flags = cmd.InheritedFlags()115	if flags.HasFlags() {116		yamlDoc.InheritedOptions = genFlagResult(flags)117	}118119	if hasSeeAlso(cmd) {120		result := []string{}121		if cmd.HasParent() {122			parent := cmd.Parent()123			result = append(result, parent.CommandPath()+" - "+parent.Short)124		}125		children := cmd.Commands()126		sort.Sort(byName(children))127		for _, child := range children {128			if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {129				continue130			}131			result = append(result, child.Name()+" - "+child.Short)132		}133		yamlDoc.SeeAlso = result134	}135136	final, err := yaml.Marshal(&yamlDoc)137	if err != nil {138		fmt.Println(err)139		os.Exit(1)140	}141142	if _, err := w.Write(final); err != nil {143		return err144	}145	return nil146}147148func genFlagResult(flags *pflag.FlagSet) []cmdOption {149	var result []cmdOption150151	flags.VisitAll(func(flag *pflag.Flag) {152		// Todo, when we mark a shorthand is deprecated, but specify an empty message.153		// The flag.ShorthandDeprecated is empty as the shorthand is deprecated.154		// Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok.155		if !(len(flag.ShorthandDeprecated) > 0) && len(flag.Shorthand) > 0 {156			opt := cmdOption{157				flag.Name,158				flag.Shorthand,159				flag.DefValue,160				forceMultiLine(flag.Usage),161			}162			result = append(result, opt)163		} else {164			opt := cmdOption{165				Name:         flag.Name,166				DefaultValue: forceMultiLine(flag.DefValue),167				Usage:        forceMultiLine(flag.Usage),168			}169			result = append(result, opt)170		}171	})172173	return result174}