github.com/aca02djr/gb@v0.4.1/cmd/gb-vendor/help.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "bytes" 6 "fmt" 7 "io" 8 "os" 9 "strings" 10 "text/template" 11 "unicode" 12 "unicode/utf8" 13 14 "github.com/constabulary/gb/cmd" 15 ) 16 17 var helpTemplate = `{{if .Runnable}}usage: gb vendor {{.UsageLine}} 18 19 {{end}}{{.Long | trim}} 20 ` 21 22 // help implements the 'help' command. 23 func help(args []string) { 24 if len(args) == 0 { 25 printUsage(os.Stdout) 26 return 27 } 28 if len(args) != 1 { 29 fmt.Fprintf(os.Stderr, "usage: gb vendor help command\n\nToo many arguments given.\n") 30 os.Exit(2) 31 } 32 33 arg := args[0] 34 35 // 'gb vendor help documentation' generates alldocs.go. 36 if arg == "documentation" { 37 var buf bytes.Buffer 38 printUsage(&buf) 39 usage := &cmd.Command{Long: buf.String()} 40 f, _ := os.Create("alldocs.go") 41 tmpl(f, documentationTemplate, append([]*cmd.Command{usage}, commands...)) 42 f.Close() 43 return 44 } 45 46 for _, cmd := range commands { 47 if cmd.Name == arg { 48 tmpl(os.Stdout, helpTemplate, cmd) 49 // not exit 2: succeeded at 'gb help cmd'. 50 return 51 } 52 } 53 54 fmt.Fprintf(os.Stderr, "Unknown help topic %#q. Run 'gb help'.\n", arg) 55 os.Exit(2) // failed at 'gb help cmd' 56 } 57 58 var usageTemplate = `gb-vendor, a gb plugin to manage your vendored dependencies. 59 60 Usage: 61 62 gb vendor command [arguments] 63 64 The commands are: 65 {{range .}}{{if .Runnable}} 66 {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}} 67 68 Use "gb vendor help [command]" for more information about a command. 69 70 Additional help topics: 71 {{range .}}{{if not .Runnable}} 72 {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}} 73 74 Use "gb vendor help [topic]" for more information about that topic. 75 ` 76 77 var documentationTemplate = `// DO NOT EDIT THIS FILE. 78 //go:generate gb vendor help documentation 79 80 /* 81 {{range .}}{{if .Short}}{{.Short | capitalize}} 82 83 {{end}}{{if .Runnable}}Usage: 84 85 gb vendor {{.UsageLine}} 86 87 {{end}}{{.Long | trim}} 88 89 90 {{end}}*/ 91 package main 92 ` 93 94 // tmpl executes the given template text on data, writing the result to w. 95 func tmpl(w io.Writer, text string, data interface{}) { 96 t := template.New("top") 97 t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize}) 98 template.Must(t.Parse(text)) 99 if err := t.Execute(w, data); err != nil { 100 panic(err) 101 } 102 } 103 104 func capitalize(s string) string { 105 if s == "" { 106 return s 107 } 108 r, n := utf8.DecodeRuneInString(s) 109 return string(unicode.ToTitle(r)) + s[n:] 110 } 111 112 func printUsage(w io.Writer) { 113 bw := bufio.NewWriter(w) 114 tmpl(bw, usageTemplate, commands) 115 bw.Flush() 116 } 117 118 func usage() { 119 printUsage(os.Stderr) 120 os.Exit(2) 121 }