Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add check for path separator to TempDir #393

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions ioutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package afero

import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
Expand Down Expand Up @@ -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()
}
Expand Down
75 changes: 75 additions & 0 deletions ioutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package afero

import (
"path/filepath"
"regexp"
"strings"
"testing"
)
Expand Down Expand Up @@ -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)
})
}
}