typestar

Paths and walking in Go

filepath joins with the right separator and walks a tree.

func findGoFiles(root string) ([]string, error) {
    var found []string
    err := filepath.WalkDir(root, func(path string, entry fs.DirEntry,
        err error) error {
        if err != nil {
            return err
        }
        if entry.IsDir() && entry.Name() == "vendor" {
            return fs.SkipDir
        }
        if filepath.Ext(path) == ".go" {
            found = append(found, filepath.Base(path))
        }
        return nil
    })
    if err != nil {
        return nil, fmt.Errorf("walk %s: %w", root, err)
    }
    slices.Sort(found)
    return found, nil
}

How it works

  1. Join cleans the result; never concatenate with a slash.
  2. WalkDir is the fast walk, using directory entries.
  3. Returning fs.SkipDir prunes a subtree.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
448
Tokens
128
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 3 of 3 in Files & IO, step 8 of 26 in Standard library & project layout.

← Previous Next →