Skip to content

Commit 55e0e25

Browse files
committed
basic go-cat implementation
1 parent 5d76dbd commit 55e0e25

File tree

5 files changed

+63
-1
lines changed

5 files changed

+63
-1
lines changed

cli-files/go-cat/assets/dew.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
“A World of Dew” by Kobayashi Issa
2+
3+
A world of dew,
4+
And within every dewdrop
5+
A world of struggle.

cli-files/go-cat/assets/for_you.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Sonia Sanchez “Haiku [for you]”
2+
3+
Love between us is
4+
speech and breath. Loving you is
5+
a long river running.

cli-files/go-cat/assets/rain.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
“The Taste of Rain” by Jack Kerouac
2+
3+
The taste
4+
Of rain
5+
—Why kneel?

cli-files/go-cat/cmd/root.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,34 @@ func NewRoodCmd() *cobra.Command {
1717
Use: "go-cat",
1818
Short: "Go implementation of cat",
1919
Long: `Works like cat`,
20-
Run: func(cmd *cobra.Command, args []string) {
20+
RunE: func(cmd *cobra.Command, args []string) error {
21+
// Don't do anything if we didn't get an arg
22+
if len(args) < 1 {
23+
return nil
24+
}
25+
path := args[0]
26+
27+
// Get data about the file so we can do this safely
28+
file, err := os.Stat(path)
29+
if err != nil {
30+
return err
31+
}
32+
33+
// If it's a directory, do the right thing and error
34+
if file.IsDir() {
35+
return fmt.Errorf("go-cat: %s: Is a directory", path)
36+
}
37+
38+
data, err := os.ReadFile(path)
39+
if err != nil {
40+
return err
41+
}
42+
43+
// Print those lovely bytes
44+
out := cmd.OutOrStdout()
45+
out.Write(data)
46+
47+
return nil
2148
},
2249
}
2350
}

cli-files/go-cat/cmd/root_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,23 @@ func TestRootCmd(t *testing.T) {
2121
t.Fatalf("expected \"%s\" got \"%s\"", expected, string(out))
2222
}
2323
}
24+
25+
func TestRootCmdWithFile(t *testing.T) {
26+
cmd := NewRoodCmd()
27+
b := bytes.NewBufferString("")
28+
cmd.SetOut(b)
29+
cmd.SetArgs([]string{"../assets/dew.txt"})
30+
cmd.Execute()
31+
out, err := ioutil.ReadAll(b)
32+
if err != nil {
33+
t.Fatal(err)
34+
}
35+
expected := `“A World of Dew” by Kobayashi Issa
36+
37+
A world of dew,
38+
And within every dewdrop
39+
A world of struggle.`
40+
if string(out) != expected {
41+
t.Fatalf("expected \"%s\" got \"%s\"", expected, string(out))
42+
}
43+
}

0 commit comments

Comments
 (0)