Skip to content

Commit

Permalink
Merge pull request #74 from CircleCI-Public/doc
Browse files Browse the repository at this point in the history
Allow printing positional arguments in generated markdown docs
  • Loading branch information
Zachary Scott authored Aug 24, 2018
2 parents 148db24 + d67bc8f commit 255077c
Show file tree
Hide file tree
Showing 5 changed files with 276 additions and 7 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

This project is the seed for CircleCI's new command-line application.

[Documentation](https://circleci-public.github.io/circleci-cli) |
[Code of Conduct](./CODE_OF_CONDUCT.md) |
[Contribution Guidelines](./CONTRIBUTING.md) |
[Hacking](./HACKING.md)
Expand Down
14 changes: 9 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"path"

"github.com/CircleCI-Public/circleci-cli/logger"
"github.com/CircleCI-Public/circleci-cli/md_docs"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -50,9 +51,9 @@ Examples:
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if (HasAnnotations .)}}
Args:{{range $arg, $desc := .Annotations}}
{{rpad $arg 11}} {{$desc}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
{{$cmd := .}}
Args:
{{range (PositionalArgs .)}} {{(FormatPositionalArg $cmd .)}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Expand All @@ -68,13 +69,16 @@ Use "{{.CommandPath}} [command] --help" for more information about a command.{{e
func MakeCommands() *cobra.Command {
rootCmd = &cobra.Command{
Use: "circleci",
Short: "Use CircleCI from the command line.",
Long: `Use CircleCI from the command line.`,
Short: `Use CircleCI from the command line.`,
Long: `This project is the seed for CircleCI's new command-line application.`,
}

// For supporting "Args" in command usage help
cobra.AddTemplateFunc("HasAnnotations", hasAnnotations)
cobra.AddTemplateFunc("PositionalArgs", md_docs.PositionalArgs)
cobra.AddTemplateFunc("FormatPositionalArg", md_docs.FormatPositionalArg)
rootCmd.SetUsageTemplate(usageTemplate)
rootCmd.DisableAutoGenTag = true

rootCmd.AddCommand(newTestsCommand())
rootCmd.AddCommand(newQueryCommand())
Expand Down
4 changes: 2 additions & 2 deletions cmd/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import (
"path/filepath"
"strings"

"github.com/CircleCI-Public/circleci-cli/md_docs"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
)

func newUsageCommand() *cobra.Command {
Expand Down Expand Up @@ -40,7 +40,7 @@ func usage(cmd *cobra.Command, args []string) error {

// generate markdown to out
emptyStr := func(s string) string { return "" }
return doc.GenMarkdownTreeCustom(rootCmd, out, emptyStr, func(name string) string {
return md_docs.GenMarkdownTreeCustom(rootCmd, out, emptyStr, func(name string) string {
base := strings.TrimSuffix(name, path.Ext(name))
return base + ".html"
})
Expand Down
212 changes: 212 additions & 0 deletions md_docs/md_docs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
//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.
// 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.

// nolint
package md_docs

import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"

"github.com/spf13/cobra"
)

var introHeader = `
[Readme](https://github.com/CircleCI-Public/circleci-cli#readme) |
[Code of Conduct](https://github.com/CircleCI-Public/circleci-cli/blob/master/CODE_OF_CONDUCT.md) |
[Contribution Guidelines](https://github.com/CircleCI-Public/circleci-cli/blob/master/CONTRIBUTING.md) |
[Hacking](https://github.com/CircleCI-Public/circleci-cli/blob/master/HACKING.md)
[![CircleCI](https://circleci.com/gh/CircleCI-Public/circleci-cli.svg?style=svg)](https://circleci.com/gh/CircleCI-Public/circleci-cli)
[![GitHub release](https://img.shields.io/github/tag/CircleCI-Public/circleci-cli.svg?label=latest)](https://github.com/CircleCI-Public/circleci-cli/releases)
[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://godoc.org/github.com/CircleCI-Public/circleci-cli)
[![Codecov](https://codecov.io/gh/CircleCI-Public/circleci-cli/branch/master/graph/badge.svg)](https://codecov.io/gh/CircleCI-Public/circleci-cli)
[![License](https://img.shields.io/badge/license-MIT-red.svg)](./LICENSE)
`

// PositionalArgs returns a slice of the given command's positional arguments
func PositionalArgs(cmd *cobra.Command) []string {
args := strings.Split(cmd.Use, " ")
if len(args) <= 1 {
return nil
}
return args[1:]
}

// FormatPositionalArg will format the positional arguments of a command from it's annotations.
func FormatPositionalArg(cmd *cobra.Command, arg string) string {
description, ok := cmd.Annotations[arg]
if !ok {
return ""
}
return fmt.Sprintf("%-11v %s\n", arg, description)
}

// Print the arguments with 11 characters of padding
func printArguments(buf *bytes.Buffer, command *cobra.Command, name string) error {
if len(command.Annotations) > 0 {
buf.WriteString("### Arguments\n\n```\n")
for _, arg := range PositionalArgs(command) {
buf.WriteString(FormatPositionalArg(command, arg))
}
buf.WriteString("```\n\n")
}

return nil
}

func printFlags(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
flags := cmd.NonInheritedFlags()
flags.SetOutput(buf)
if flags.HasAvailableFlags() {
buf.WriteString("### Flags\n\n```\n")
flags.PrintDefaults()
buf.WriteString("```\n\n")
}

parentFlags := cmd.InheritedFlags()
parentFlags.SetOutput(buf)
if parentFlags.HasAvailableFlags() {
buf.WriteString("### Flags inherited from parent commands\n\n```\n")
parentFlags.PrintDefaults()
buf.WriteString("```\n\n")
}
return nil
}

// GenMarkdown creates markdown output.
func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
return GenMarkdownCustom(cmd, w, func(s string) string { return s })
}

// GenMarkdownCustom creates custom markdown output.
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
cmd.InitDefaultHelpCmd()
cmd.InitDefaultHelpFlag()

buf := new(bytes.Buffer)
name := cmd.CommandPath()

short := cmd.Short
long := cmd.Long
if len(long) == 0 {
long = short
}

buf.WriteString("## " + name + "\n\n")
buf.WriteString(short + "\n\n")

if name == "circleci" {
buf.WriteString(introHeader + "\n\n")
}
buf.WriteString("### Synopsis\n\n")
buf.WriteString(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 := printArguments(buf, cmd, name); err != nil {
return err
}

if err := printFlags(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 + ".md"
link = strings.Replace(link, " ", "_", -1)
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), 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 + ".md"
link = strings.Replace(link, " ", "_", -1)
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), 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
}

// GenMarkdownTree will generate a markdown 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 GenMarkdownTree(cmd *cobra.Command, dir string) error {
identity := func(s string) string { return s }
emptyStr := func(s string) string { return "" }
return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
}

// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
// with custom filePrepender and linkHandler.
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
continue
}
if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
return err
}
}

basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
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 := GenMarkdownCustom(cmd, f, linkHandler); err != nil {
return err
}
return nil
}
52 changes: 52 additions & 0 deletions md_docs/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// 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.
// 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.

// nolint
package md_docs

import (
"strings"

"github.com/spf13/cobra"
)

// Test to see if we have a reason to print See Also information in docs
// Basically this is a test for a parent commend or a subcommand which is
// both not deprecated and not the autogenerated help command.
func hasSeeAlso(cmd *cobra.Command) bool {
if cmd.HasParent() {
return true
}
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
continue
}
return true
}
return false
}

// Temporary workaround for yaml lib generating incorrect yaml with long strings
// that do not contain \n.
func forceMultiLine(s string) string {
if len(s) > 60 && !strings.Contains(s, "\n") {
s = s + "\n"
}
return s
}

type byName []*cobra.Command

func (s byName) Len() int { return len(s) }
func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }

0 comments on commit 255077c

Please sign in to comment.