Skip to content

Commit

Permalink
handle command style arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
mrosset committed Apr 7, 2012
1 parent dd1b83f commit 6509805
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 0 deletions.
50 changes: 50 additions & 0 deletions console/command/command.go
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,50 @@
package command

import (
"flag"
"os"
)

type Command struct {
Name string
Run func()
Usage string
}

var (
Commands = []*Command{}
)

func Run() {
flag.Parse()
args := flag.Args()
if len(args) < 1 {
flag.Usage()
os.Exit(1)
}
for _, cmd := range Commands {
if cmd.Name == args[0] {
cmd.Run()
return
}
}
flag.Usage()
}

func Args() []string {
return flag.Args()[1:]
}

func Add(n string, r func(), u string) {
Commands = append(Commands, &Command{n, r, u})
}

func ArgsDo(f func(string) error) error {
for _, a := range Args() {
err := f(a)
if err != nil {
return err
}
}
return nil
}
22 changes: 22 additions & 0 deletions console/command/command_test.go
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,22 @@
package command

import (
"fmt"
"testing"
)

func TestCommands(t *testing.T) {
Add("test", test, "test function")
Add("test1", test1, "test1 function")
for _, c := range commands {
c.Run()
}
}

func test() {
fmt.Println("test run here")
}

func test1() {
fmt.Println("test1 run here")
}
34 changes: 34 additions & 0 deletions console/command/foo/main.go
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"fmt"
"github.com/str1ngs/util/console/command"
)

func main() {
command.Add("echo", echoArgs, "prints a line for each arg") // add new command : foo echo
command.Add("reverse", revArgs, "prints each arument in reverse") // add new command : foo reverse
command.Run() // run commands
}

func revArgs() {
command.ArgsDo(revArg) // loops through all arguments after command
}

func revArg(a string) error {
r := ""
for i := len(a) - 1; i >= 0; i-- {
r += string(a[i])
}
fmt.Println(r)
return nil
}

func echoArgs() {
command.ArgsDo(echoArg)
}

func echoArg(a string) error {
fmt.Println(a)
return nil
}
9 changes: 9 additions & 0 deletions console/command/foo/main_test.go
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,9 @@
package main

import (
"testing"
)

func TestRev(t *testing.T) {
revArg("test")
}

0 comments on commit 6509805

Please sign in to comment.