Skip to content

Commit 7208af1

Browse files
committed
print file name if passed a file
1 parent 8243544 commit 7208af1

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,24 @@ func NewRoodCmd() *cobra.Command {
2020
dir = args[0]
2121
}
2222

23+
// Stat the file so we can check if it's a directory or not before
24+
// we try to read it as a directory using ReadDir. os.ReadDir will
25+
// generates an error if the thing you pass to it is not a directory.
26+
// https://pkg.go.dev/os#Stat
27+
fileInfo, err := os.Stat(dir)
28+
if err != nil {
29+
return err
30+
}
31+
32+
// We can only list the contents of a directory.
33+
// To match the real ls, if we're asked to ls a file, we'll just print
34+
// out the file's name.
35+
// https://pkg.go.dev/io/fs#FileInfo
36+
if fileInfo.IsDir() == false {
37+
fmt.Fprintln(cmd.OutOrStdout(), fileInfo.Name())
38+
return nil
39+
}
40+
2341
// Read this directory to get a list of files
2442
// https://pkg.go.dev/os#ReadDir
2543
files, err := os.ReadDir(dir)

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,20 @@ rain.txt
4242
t.Fatalf("expected \"%s\" got \"%s\"", expected, string(out))
4343
}
4444
}
45+
46+
func TestRootCmdFile(t *testing.T) {
47+
cmd := NewRoodCmd()
48+
b := bytes.NewBufferString("")
49+
cmd.SetOut(b)
50+
cmd.SetArgs([]string{"../assets/dew.txt"})
51+
cmd.Execute()
52+
out, err := ioutil.ReadAll(b)
53+
if err != nil {
54+
t.Fatal(err)
55+
}
56+
expected := `dew.txt
57+
`
58+
if string(out) != expected {
59+
t.Fatalf("expected \"%s\" got \"%s\"", expected, string(out))
60+
}
61+
}

0 commit comments

Comments
 (0)