File: testfs.go

package info (click to toggle)
golang-github-twpayne-go-vfs 4.1.0-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 212 kB
  • sloc: makefile: 30
file content (58 lines) | stat: -rw-r--r-- 1,243 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package vfst

import (
	"os"

	vfs "github.com/twpayne/go-vfs/v4"
)

// A TestFS is a virtual filesystem based in a temporary directory.
type TestFS struct {
	vfs.PathFS
	tempDir string
	keep    bool
}

func newTestFS() (*TestFS, func(), error) {
	tempDir, err := os.MkdirTemp("", "go-vfs-vfst")
	if err != nil {
		return nil, nil, err
	}
	t := &TestFS{
		PathFS:  *vfs.NewPathFS(vfs.OSFS, tempDir),
		tempDir: tempDir,
		keep:    false,
	}
	return t, t.cleanup, nil
}

// NewTestFS returns a new *TestFS populated with root and a cleanup function.
func NewTestFS(root interface{}, builderOptions ...BuilderOption) (*TestFS, func(), error) {
	fileSystem, cleanup, err := newTestFS()
	if err != nil {
		cleanup()
		return nil, nil, err
	}
	if err := NewBuilder(builderOptions...).Build(fileSystem, root); err != nil {
		cleanup()
		return nil, nil, err
	}
	return fileSystem, cleanup, nil
}

// Keep prevents t's cleanup function from removing the temporary directory. It
// has no effect if cleanup has already been called.
func (t *TestFS) Keep() {
	t.keep = true
}

// TempDir returns t's temporary directory.
func (t *TestFS) TempDir() string {
	return t.tempDir
}

func (t *TestFS) cleanup() {
	if !t.keep {
		os.RemoveAll(t.tempDir)
	}
}