Source File: go-coreutils/ls/main.go
package 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
})
}
}