Golang afero

From wikinotes

Afero defines and implements an interface to access the filesystem.
You can then pass in an abstraction of real os calls, or a stub stub interface you can make assertions against.
It is maintained by the go developers.

Documentation

api docs https://pkg.go.dev/github.com/spf13/afero
github https://github.com/spf13/afero

Usage

Basics

// internal/fs/fs.go
import "github.com/spf13/afero"

Fs = Fs: afero.NewOsFs() // real 'os' calls
// foo.go
package foo
import (
    "example.com/x/mypkg/internal/fs"
    "github.com/spf13/afero"
)

func DoThing() {
    Os = afero.Afero{Fs: Fs}
    // os.* exposed on Fs
    Fs.Create("/var/tmp/foo.txt")

    // io, ioutil exposed in Afero{}
    Os.ReadFile("/var/tmp/foo.txt")
}
// foo_test.go
package foo

func TestDoThing(t *testing.T) {
    var fs.Fs = afero.NewMemMapFs()
    t.Run("Does Thing", func(t *testing.T) {
        err := foo.DoThing()
        assert.Nil(t, err)
    })
}

Common Tasks

Fs := afero.NewOsFs()
Os := afero.Afero{Fs: Fs}

path, err := Os.TempDir(os.TempDir(), "my-prefix-")
exists, err := Os.Exists("/var/tmp/foo")