home » torr/pasy.git
ID: 05dee240dc997534adf443bca08538063bfd14ee
55 lines — 925B — View raw


package prog

import (
	"bytes"
	"fmt"
	"os"
	"sort"
	"strings"

	"github.com/mitchellh/cli"
)

const (
	Name    = "pasy"
	Version = "0.1.0"

	helpFmt = `Usage: %s [-h|--help|-v|--version] <command> [<args>]

Available commands are:
`
)

func FuncHelp(cma map[string]cli.CommandFactory) string {
	bu := &bytes.Buffer{}
	bu.WriteString(fmt.Sprintf(helpFmt, Name))

	keys := make([]string, 0, len(cma))
	longest := 0
	for c, _ := range cma {
		if len(c) > longest {
			longest = len(c)
		}
		keys = append(keys, c)
	}

	sort.Strings(keys)
	for _, k := range keys {
		cmd, err := cma[k]()
		if err != nil {
			PrintErr(fmt.Sprintf("unable to call init function from command '%s': %v", k, err))
			continue
		}

		bu.WriteString(fmt.Sprintf("  %s%s    %s\n",
			k,
			strings.Repeat(" ", longest-len(k)),
			cmd.Synopsis(),
		))
	}
	return bu.String()
}

func PrintErr(msg string) {
	fmt.Fprintf(os.Stderr, "error: %s\n", msg)
}