Skip to content

Commit

Permalink
Ensure CreateTempDir() is Multi-Process Safe (#246)
Browse files Browse the repository at this point in the history
Refining `CreateTempDir()` by appending a wildcard `*` at the end of the `MkdirTemp()` pattern argument. This ensures that a unique random string replaces the last `*`, preventing concurrent processes or goroutines from selecting the same directory. This approach is preferred over using only `strconv.FormatInt(time.Now().Unix(), 10)`, which may not offer sufficient distinction between processes.
  • Loading branch information
noyshabtay authored Apr 7, 2024
1 parent bb669f3 commit a7235a5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion utils/fileutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ func GetFileContentAndInfo(filePath string) (fileContent []byte, fileInfo os.Fil
func CreateTempDir() (string, error) {
tempDirBase := os.TempDir()
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
return os.MkdirTemp(tempDirBase, tempDirPrefix+timestamp+"-")
return os.MkdirTemp(tempDirBase, tempDirPrefix+timestamp+"-*")
}

func RemoveTempDir(dirPath string) error {
Expand Down
16 changes: 16 additions & 0 deletions utils/fileutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,19 @@ func TestReadNLines(t *testing.T) {
assert.True(t, strings.HasPrefix(lines[1], "781"))
assert.True(t, strings.HasSuffix(lines[1], ":true}}}"))
}

func TestCreateTempDir(t *testing.T) {
tempDir, err := CreateTempDir()
assert.NoError(t, err)

_, err = os.Stat(tempDir)
assert.NotErrorIs(t, err, os.ErrNotExist)

defer func() {
// Check that a timestamp can be extracted from the temp dir name
_, err = extractTimestamp(tempDir)
assert.NoError(t, err)

assert.NoError(t, os.RemoveAll(tempDir))
}()
}

0 comments on commit a7235a5

Please sign in to comment.