Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
owenthereal committed Apr 9, 2013
0 parents commit d5615fc
Show file tree
Hide file tree
Showing 4 changed files with 137 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
gh
71 changes: 71 additions & 0 deletions help.go
Original file line number Diff line number Diff line change
@@ -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 changes: 62 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -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()
}
3 changes: 3 additions & 0 deletions version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package main

const Version = "dev"

0 comments on commit d5615fc

Please sign in to comment.