Video Coming Soon...
43: ls
The ls command lists the contents of a directory. That's it. You can get extremely fancy with ls, but at its core it's just a lister of the files.
The Challenge
The biggest challenge with this is you'll have to reconcile listing the current directory vs. listing an entire directory tree with the -R option. You've done directory walking in another command, so hopefully you remember doing that. Right?
Here's the documentation for ls:
Requirements
The requirements for ls are simple at first, but you can get far more complex later.
See the list of requirements
- fmt -- https://pkg.go.dev/fmt
- io/fs -- https://pkg.go.dev/io/fs
- path/filepath -- https://pkg.go.dev/path/filepath
- flag -- https://pkg.go.dev/flag
Spoilers
Mine does the -R option, but not much else. Can you do better?
See my first version code
View Source file go-coreutils/ls/main.go Onlypackage main
import (
"fmt"
"io/fs"
"path/filepath"
"flag"
)
type Opts struct {
Recurse bool
Paths []string
}
func ParseOpts() Opts {
var opts Opts
flag.BoolVar(&opts.Recurse, "R", false, "recursive listing")
flag.Parse()
opts.Paths = flag.Args()
if len(opts.Paths) == 0 {
opts.Paths = append(opts.Paths, ".")
}
return opts
}
func main() {
opts := ParseOpts()
for _, what := range opts.Paths {
if flag.NArg() > 1 {
fmt.Printf("\n%s:\n", what)
}
filepath.WalkDir(what, func (path string, d fs.DirEntry, err error) error {
if path == what { return nil }
if d.IsDir() && opts.Recurse {
fmt.Printf("\n%s:\n", path)
} else if d.IsDir() {
fmt.Printf("%s\n", filepath.Base(path))
return fs.SkipDir
} else {
fmt.Printf("%s\n", filepath.Base(path))
}
return nil
})
}
}
Testing It
If you want to push your learning further then you can try to implement an automated test for this. I actually need to learn how to test utilities like this with Go, so for now just consider this an extra challenge for later until I learn how to teach it.
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.