From 16fd4c44e8c1e75f9570f4e126fc8a15dec17167 Mon Sep 17 00:00:00 2001 From: Leon Rosenshein Date: Mon, 10 Jul 2023 02:59:56 +0000 Subject: [PATCH] Add check for path separator to TempDir --- ioutil.go | 7 +++++ ioutil_test.go | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/ioutil.go b/ioutil.go index fa6abe1e..48b6f0b1 100644 --- a/ioutil.go +++ b/ioutil.go @@ -17,6 +17,7 @@ package afero import ( "bytes" + "fmt" "io" "os" "path/filepath" @@ -218,6 +219,12 @@ func (a Afero) TempDir(dir, prefix string) (name string, err error) { } func TempDir(fs Fs, dir, prefix string) (name string, err error) { + + if strings.Contains(prefix, string(os.PathSeparator)) { + err = fmt.Errorf("%s: pattern contains path separator", prefix) + return + } + if dir == "" { dir = os.TempDir() } diff --git a/ioutil_test.go b/ioutil_test.go index 004c66ba..4c355c5f 100644 --- a/ioutil_test.go +++ b/ioutil_test.go @@ -17,6 +17,7 @@ package afero import ( "path/filepath" + "regexp" "strings" "testing" ) @@ -174,3 +175,77 @@ func TestTempFile(t *testing.T) { }) } } + +func TestTempDir(t *testing.T) { + + type testData struct { + dir string + prefix string + expectedPrefix string + shouldError bool + } + + tests := map[string]testData{ + "TempDirWithStar": { + dir: "", + prefix: "withStar*", + expectedPrefix: "/tmp/withStar", + }, + "TempDirWithTwoStars": { + dir: "", + prefix: "withStar**", + expectedPrefix: "/tmp/withStar*", + }, + "TempDirWithoutStar": { + dir: "", + prefix: "withoutStar", + expectedPrefix: "/tmp/withoutStar", + }, + "UserDir": { + dir: "dir1", + prefix: "", + expectedPrefix: "dir1/", + }, + "InvalidPrefix": { + dir: "", + prefix: "hello/world", + expectedPrefix: "hello", + shouldError: true, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + afs := NewMemMapFs() + result, err := TempDir(afs, test.dir, test.prefix) + + if test.shouldError { + if err == nil { + t.Error("err should not be nil") + return + } + if result != "" { + t.Errorf("result was %s and should be the empty string", result) + return + } + } else { + match, _ := regexp.MatchString(test.expectedPrefix+".*", result) + if !match { + t.Errorf("directory should have prefix %s should exist, but doesn't", test.expectedPrefix) + return + } + exists, err := DirExists(afs, result) + if !exists { + t.Errorf("directory with prefix %s should exist, but doesn't", test.expectedPrefix) + return + } + if err != nil { + t.Errorf("err should be nil, but was %s", err.Error()) + return + } + } + + afs.RemoveAll(result) + }) + } +}