diff --git a/common/helpers/cache/persist.go b/common/helpers/cache/persist.go index 2e4a565f..a58b8008 100644 --- a/common/helpers/cache/persist.go +++ b/common/helpers/cache/persist.go @@ -9,29 +9,18 @@ import ( "fmt" "os" "path/filepath" + + "github.com/google/renameio/v2" ) // Save persists the cache to the specified file func (c *Cache[K, V]) Save(cacheFile string) error { - tmpFile, err := os.CreateTemp( - filepath.Dir(cacheFile), - fmt.Sprintf("%s-*", filepath.Base(cacheFile))) - if err != nil { - return fmt.Errorf("unable to create cache file %q: %w", cacheFile, err) - } - defer func() { - tmpFile.Close() // ignore errors - os.Remove(tmpFile.Name()) // ignore errors - }() - - // Write cache - encoder := gob.NewEncoder(tmpFile) + var buf bytes.Buffer + encoder := gob.NewEncoder(&buf) if err := encoder.Encode(c); err != nil { return fmt.Errorf("unable to encode cache: %w", err) } - - // Move cache to new location - if err := os.Rename(tmpFile.Name(), cacheFile); err != nil { + if err := renameio.WriteFile(cacheFile, buf.Bytes(), 0o666, renameio.WithTempDir(filepath.Dir(cacheFile))); err != nil { return fmt.Errorf("unable to write cache file %q: %w", cacheFile, err) } return nil diff --git a/go.mod b/go.mod index 45e5b535..d5bc6386 100644 --- a/go.mod +++ b/go.mod @@ -114,6 +114,7 @@ require ( github.com/golang/protobuf v1.5.4 // indirect github.com/google/licensecheck v0.3.1 // indirect github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 // indirect + github.com/google/renameio/v2 v2.0.0 // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 // indirect diff --git a/go.sum b/go.sum index 289e76ff..6fe0de6b 100644 --- a/go.sum +++ b/go.sum @@ -193,6 +193,8 @@ github.com/google/licensecheck v0.3.1/go.mod h1:ORkR35t/JjW+emNKtfJDII0zlciG9Jgb github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J0b1vyeLSOYI8bm5wbJM/8yDe8= github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/renameio/v2 v2.0.0 h1:UifI23ZTGY8Tt29JbYFiuyIU3eX+RNFtUwefq9qAhxg= +github.com/google/renameio/v2 v2.0.0/go.mod h1:BtmJXm5YlszgC+TD4HOEEUFgkJP3nLxehU6hfe7jRt4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=