Permalink
Browse files

Init

  • Loading branch information...
jingweno committed Apr 9, 2013
0 parents commit d5615fcb6f9c983fbf5d1297700a26531ddf1173
Showing with 137 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. +71 −0 help.go
  3. +62 −0 main.go
  4. +3 −0 version.go
@@ -0,0 +1 @@
gh
71 help.go
@@ -0,0 +1,71 @@
package main
import (
"fmt"
"log"
"os"
"text/template"
)
var cmdVersion = &Command{
Run: runVersion,
Usage: "version",
Short: "show gh version",
Long: `Version shows the gh client version showstring.`,
}
func runVersion(cmd *Command, args []string) {
fmt.Println(Version)
}
var cmdHelp = &Command{
Usage: "help [command]",
Short: "show help",
Long: `Help shows usage for a command.`,
}
func init() {
cmdHelp.Run = runHelp // break init loop
}
func runHelp(cmd *Command, args []string) {
if len(args) == 0 {
printUsage()
return // not os.Exit(2); success
}
if len(args) != 1 {
log.Fatal("too many arguments")
}
for _, cmd := range commands {
if cmd.Name() == args[0] {
cmd.printUsage()
return
}
}
fmt.Fprintf(os.Stderr, "Unknown help topic: %q. Run 'acldt helpp'.\n", args[0])
os.Exit(2)
}
var usageTemplate = template.Must(template.New("usage").Parse(`Usage: gh [command] [options] [arguments]
Supported commands are:
{{range .Commands}}{{if .Runnable}}{{if .ShowUsage}}
{{.Name | printf "%-8s"}} {{.Short}}{{end}}{{end}}{{end}}
See 'gh help [command]' for more information about a command.
`))
func printUsage() {
usageTemplate.Execute(os.Stdout, struct {
Commands []*Command
}{
commands,
})
}
func usage() {
printUsage()
os.Exit(2)
}
62 main.go
@@ -0,0 +1,62 @@
package main
import (
"flag"
"fmt"
"os"
"strings"
)
type Command struct {
Run func(cmd *Command, args []string)
Flag flag.FlagSet
Usage string
Short string
Long string
}
func (c *Command) printUsage() {
if c.Runnable() {
fmt.Printf("Usage: gh %s\n\n", c.Usage)
}
fmt.Println(strings.Trim(c.Long, "\n"))
}
func (c *Command) Name() string {
name := c.Usage
i := strings.Index(name, " ")
if i >= 0 {
name = name[:i]
}
return name
}
func (c *Command) Runnable() bool {
return c.Run != nil
}
var commands = []*Command{}
func main() {
args := os.Args[1:]
if len(args) < 1 {
usage()
}
for _, cmd := range commands {
if cmd.Name() == args[0] && cmd.Run != nil {
cmd.Flag.Usage = func() {
cmd.printUsage()
}
if err := cmd.Flag.Parse(args[1:]); err != nil {
os.Exit(2)
}
cmd.Run(cmd, cmd.Flag.Args())
return
}
}
fmt.Fprintf(os.Stderr, "Unknown command: %s\n", args[0])
usage()
}
@@ -0,0 +1,3 @@
package main
const Version = "dev"

0 comments on commit d5615fc

Please sign in to comment.