From 007ab721c3bf1cda3b31fb05f9cf2b4f3b3ef112 Mon Sep 17 00:00:00 2001 From: Taylon Silmer Date: Sun, 15 May 2016 11:17:37 -0300 Subject: [PATCH] Add support to on/off arguments in the list command --- commands.go | 23 ++++++++++++++++++++++- commands_test.go | 41 +++++++++++++++++++++++++++++++++++++++-- test-fixtures/ls_on_off | 2 ++ 3 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 test-fixtures/ls_on_off diff --git a/commands.go b/commands.go index 50116f1..16ccf3c 100644 --- a/commands.go +++ b/commands.go @@ -193,6 +193,17 @@ func OnOff(c *cli.Context) { // Ls command shows a list of hostnames in the hosts file func Ls(c *cli.Context) { + var status bool + printall := true + if len(c.Args()) != 0 { + printall = false + status = false + + if c.Args()[0] == "on" { + status = true + } + } + hostsfile := AlwaysLoadHostFile(c) maxdomain := 0 maxip := 0 @@ -207,12 +218,22 @@ func Ls(c *cli.Context) { } } - for _, hostname := range hostsfile.Hosts { + printHost := func(hostname *Hostname) { fmt.Printf("%s -> %s %s\n", StrPadRight(hostname.Domain, maxdomain), StrPadRight(hostname.IP.String(), maxip), hostname.FormatEnabled()) } + + for _, hostname := range hostsfile.Hosts { + if printall { + printHost(hostname) + } else { + if hostname.Enabled == status { + printHost(hostname) + } + } + } } const fixHelp = `Programmatically rewrite your hostsfile. diff --git a/commands_test.go b/commands_test.go index ff0e13e..795a75f 100644 --- a/commands_test.go +++ b/commands_test.go @@ -2,6 +2,7 @@ package hostess import ( "flag" + "io/ioutil" "os" "testing" @@ -15,9 +16,45 @@ func TestStrPadRight(t *testing.T) { assert.Equal(t, "string", StrPadRight("string", 0), "6-length 0 padding") } +func captureOutput(f func()) string { + rescueStdout := os.Stdout + r, w, _ := os.Pipe() + os.Stdout = w + + f() + + w.Close() + out, _ := ioutil.ReadAll(r) + os.Stdout = rescueStdout + + return string(out[:]) +} + func TestLs(t *testing.T) { os.Setenv("HOSTESS_PATH", "test-fixtures/hostfile1") defer os.Setenv("HOSTESS_PATH", "") - c := cli.NewContext(cli.NewApp(), &flag.FlagSet{}, nil) - Ls(c) + + app := cli.NewApp() + + context := cli.NewContext(app, &flag.FlagSet{}, nil) + Ls(context) + + // Test on/off arguments functionality + os.Setenv("HOSTESS_PATH", "test-fixtures/ls_on_off") + set := flag.NewFlagSet("test", 0) + set.Parse([]string{"list", "on"}) + context = cli.NewContext(app, set, nil) + command := cli.Command{ + Name: "list", + Aliases: []string{"ls"}, + Usage: "Testing Ls", + Description: "Testing Ls", + Action: Ls, + } + + output := captureOutput(func() { + command.Run(context) + }) + + assert.Equal(t, "chocolate.pie.example.com -> fe:23b3:890e:342e::ef (On)\n", output) } diff --git a/test-fixtures/ls_on_off b/test-fixtures/ls_on_off new file mode 100644 index 0000000..5cd3027 --- /dev/null +++ b/test-fixtures/ls_on_off @@ -0,0 +1,2 @@ +# fe:23b3:890e:342e::ef dev.strawberry.pie.example.com +fe:23b3:890e:342e::ef chocolate.pie.example.com