From 87ff1187ef3e6561b9ea207d651140484232a040 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Wed, 31 May 2023 13:57:48 +0200 Subject: [PATCH] Fix #104218: Shaman unit test TestGarbageCollect is unstable Copy files instead of hard-linking. The hard-links seemed to have some weird behaviour, at least on Windows 10 where I tested this. --- pkg/shaman/filestore/testing.go | 36 +++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/pkg/shaman/filestore/testing.go b/pkg/shaman/filestore/testing.go index efbc77ef..6b73d41b 100644 --- a/pkg/shaman/filestore/testing.go +++ b/pkg/shaman/filestore/testing.go @@ -23,6 +23,8 @@ package filestore import ( + "fmt" + "io" "io/ioutil" "os" "path/filepath" @@ -75,7 +77,7 @@ func (s *Store) MustStoreFileForTest(checksum string, filesize int64, contents [ } } -// LinkTestFileStore creates a copy of _test_file_store by hard-linking files into a temporary directory. +// LinkTestFileStore creates a copy of _test_file_store in a temporary directory. // Panics if there are any errors. func LinkTestFileStore(cloneTo string) { _, myFilename, _, _ := runtime.Caller(0) @@ -96,7 +98,7 @@ func LinkTestFileStore(cloneTo string) { if info.IsDir() { return os.MkdirAll(targetPath, 0755) } - err = os.Link(visitPath, targetPath) + err = copyFile(visitPath, targetPath) if err != nil { return err } @@ -107,3 +109,33 @@ func LinkTestFileStore(cloneTo string) { panic(err) } } + +func copyFile(sourcePath, destPath string) error { + // Open the source file. + srcFile, err := os.Open(sourcePath) + if err != nil { + return fmt.Errorf("could not open %q: %w", sourcePath, err) + } + defer srcFile.Close() + + // Create the destination file. + destFile, err := os.Create(destPath) + if err != nil { + return fmt.Errorf("could not create %q: %w", destPath, err) + } + defer destFile.Close() + + // Copy the contents from source to destination. + _, err = io.Copy(destFile, srcFile) + if err != nil { + return fmt.Errorf("could not copy contents of %q to %q: %w", sourcePath, destPath, err) + } + + // Flush any buffered data to ensure completion. + err = destFile.Sync() + if err != nil { + return fmt.Errorf("could not sync buffer of %q to disk: %w", destPath, err) + } + + return nil +}