Skip to content

Commit a68e5d6

Browse files
committed
fs: add DirFromPath
1 parent 196ee67 commit a68e5d6

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

fs/file.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,18 @@ func (d *Dir) Remove() {
113113
func (d *Dir) Join(parts ...string) string {
114114
return filepath.Join(append([]string{d.Path()}, parts...)...)
115115
}
116+
117+
// DirFromPath returns a Dir for a path that already exists. No directory is created.
118+
// DirFromPath can be used with Apply to modify an existing directory.
119+
//
120+
// If the path does not already exist, use NewDir instead.
121+
func DirFromPath(t assert.TestingT, path string, ops ...PathOp) *Dir {
122+
if ht, ok := t.(helperT); ok {
123+
ht.Helper()
124+
}
125+
126+
dir := &Dir{path: path}
127+
cleanup.Cleanup(t, dir.Remove)
128+
assert.NilError(t, applyPathOps(dir, ops))
129+
return dir
130+
}

fs/file_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package fs_test
22

33
import (
4+
"errors"
5+
"io/ioutil"
46
"os"
7+
"path/filepath"
58
"testing"
69

710
"gotest.tools/v3/assert"
@@ -92,3 +95,24 @@ func TestNewDir_IntegrationWithCleanup(t *testing.T) {
9295
assert.ErrorType(t, err, os.IsNotExist)
9396
})
9497
}
98+
99+
func TestDirFromPath(t *testing.T) {
100+
tmpdir, err := ioutil.TempDir("", t.Name())
101+
assert.NilError(t, err)
102+
t.Cleanup(func() {
103+
os.RemoveAll(tmpdir)
104+
})
105+
106+
dir := fs.DirFromPath(t, tmpdir, fs.WithFile("newfile", ""))
107+
108+
_, err = os.Stat(dir.Join("newfile"))
109+
assert.NilError(t, err)
110+
111+
assert.Equal(t, dir.Path(), tmpdir)
112+
assert.Equal(t, dir.Join("newfile"), filepath.Join(tmpdir, "newfile"))
113+
114+
dir.Remove()
115+
116+
_, err = os.Stat(tmpdir)
117+
assert.Assert(t, errors.Is(err, os.ErrNotExist))
118+
}

0 commit comments

Comments
 (0)