From c0f33a3456bd8205b15a6376af361ce5bdd0a45b Mon Sep 17 00:00:00 2001 From: David Dworken Date: Sat, 2 Sep 2023 18:50:52 -0700 Subject: [PATCH] Swap from os.Rename to a custom implementation that copies files to support cross-device renames, as needed for making ~/.hishtory/ a tmpfs for tests --- shared/testutils/testutils.go | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/shared/testutils/testutils.go b/shared/testutils/testutils.go index 6c4284f..a57a532 100644 --- a/shared/testutils/testutils.go +++ b/shared/testutils/testutils.go @@ -88,7 +88,7 @@ func BackupAndRestoreWithId(t testing.TB, id string) func() { } for _, file := range renameFiles { touchFile(file) - Check(t, os.Rename(file, getBackPath(file, id))) + Check(t, rename(file, getBackPath(file, id))) } copyFiles := []string{ path.Join(homedir, ".zshrc"), @@ -113,7 +113,7 @@ func BackupAndRestoreWithId(t testing.TB, id string) func() { Check(t, os.RemoveAll(path.Join(homedir, data.GetHishtoryPath()))) Check(t, os.MkdirAll(path.Join(homedir, data.GetHishtoryPath()), os.ModePerm)) for _, file := range renameFiles { - checkError(os.Rename(getBackPath(file, id), file)) + checkError(rename(getBackPath(file, id), file)) } for _, file := range copyFiles { checkError(copy(getBackPath(file, id), file)) @@ -154,7 +154,17 @@ setopt SHARE_HISTORY checkError(err) } +// Similar to os.Rename, except it supports renaming cross-mount +func rename(src, dst string) error { + err := copy(src, dst) + if err != nil { + return err + } + return os.Remove(src) +} + func copy(src, dst string) error { + // Copy the contents of the file in, err := os.Open(src) if err != nil { return err @@ -171,7 +181,17 @@ func copy(src, dst string) error { if err != nil { return err } - return out.Close() + err = out.Close() + if err != nil { + return err + } + + // And copy the permissions + srcStat, err := in.Stat() + if err != nil { + return err + } + return os.Chmod(dst, srcStat.Mode()) } func BackupAndRestoreEnv(k string) func() {