Skip to content

Commit 2f239be

Browse files
authored
Fix races on temporary file copies (#616)
* Fix races on temporary file copies * Appease Windows * Fix ordering
1 parent 572e6f7 commit 2f239be

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

core/core.go

+20-5
Original file line numberDiff line numberDiff line change
@@ -404,10 +404,17 @@ func downloadBazelIfNecessary(version string, bazeliskHome string, bazelForkOrUR
404404
}
405405

406406
func atomicWriteFile(path string, contents []byte, perm os.FileMode) error {
407-
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
407+
parent := filepath.Dir(path)
408+
if err := os.MkdirAll(parent, 0755); err != nil {
408409
return fmt.Errorf("failed to MkdirAll parent of %s: %w", path, err)
409410
}
410-
tmpPath := path + ".tmp"
411+
tmpFile, err := os.CreateTemp(parent, filepath.Base(path)+".tmp")
412+
if err != nil {
413+
return fmt.Errorf("failed to create temporary file in %s: %w", parent, err)
414+
}
415+
tmpFile.Close()
416+
defer os.Remove(tmpFile.Name())
417+
tmpPath := tmpFile.Name()
411418
if err := os.WriteFile(tmpPath, contents, perm); err != nil {
412419
return fmt.Errorf("failed to write file %s: %w", tmpPath, err)
413420
}
@@ -458,12 +465,20 @@ func downloadBazelToCAS(version string, bazeliskHome string, repos *Repositories
458465
f.Close()
459466
actualSha256 := strings.ToLower(fmt.Sprintf("%x", h.Sum(nil)))
460467

461-
pathToBazelInCAS := filepath.Join(casDir, actualSha256, "bin", "bazel"+platforms.DetermineExecutableFilenameSuffix())
462-
if err := os.MkdirAll(filepath.Dir(pathToBazelInCAS), 0755); err != nil {
468+
bazelInCASBasename := "bazel" + platforms.DetermineExecutableFilenameSuffix()
469+
pathToBazelInCAS := filepath.Join(casDir, actualSha256, "bin", bazelInCASBasename)
470+
dirForBazelInCAS := filepath.Dir(pathToBazelInCAS)
471+
if err := os.MkdirAll(dirForBazelInCAS, 0755); err != nil {
463472
return "", "", fmt.Errorf("failed to MkdirAll parent of %s: %w", pathToBazelInCAS, err)
464473
}
465474

466-
tmpPathInCorrectDirectory := pathToBazelInCAS + ".tmp"
475+
tmpPathFile, err := os.CreateTemp(dirForBazelInCAS, bazelInCASBasename+".tmp")
476+
if err != nil {
477+
return "", "", fmt.Errorf("failed to create temporary file in %s: %w", dirForBazelInCAS, err)
478+
}
479+
tmpPathFile.Close()
480+
defer os.Remove(tmpPathFile.Name())
481+
tmpPathInCorrectDirectory := tmpPathFile.Name()
467482
if err := os.Rename(tmpDestPath, tmpPathInCorrectDirectory); err != nil {
468483
return "", "", fmt.Errorf("failed to move %s to %s: %w", tmpDestPath, tmpPathInCorrectDirectory, err)
469484
}

0 commit comments

Comments
 (0)