From 778bd2e14f457e1e81a8d226377d851c9bdbe4f2 Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:03:37 +0300 Subject: [PATCH] fix(fileutil): reject copies onto the source file (#379) --- fileutil/file.go | 7 +++++++ fileutil/file_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/fileutil/file.go b/fileutil/file.go index 642d52b..a329072 100644 --- a/fileutil/file.go +++ b/fileutil/file.go @@ -229,6 +229,13 @@ func CopyFile(srcPath string, dstPath string) error { return err } defer srcFile.Close() + srcInfo, err := srcFile.Stat() + if err != nil { + return err + } + if dstInfo, err := os.Stat(dstPath); err == nil && os.SameFile(srcInfo, dstInfo) { + return errors.New("source and destination are the same file") + } distFile, err := os.Create(dstPath) if err != nil { diff --git a/fileutil/file_test.go b/fileutil/file_test.go index 63b13cf..9b48d65 100644 --- a/fileutil/file_test.go +++ b/fileutil/file_test.go @@ -139,6 +139,34 @@ func TestCopyFile(t *testing.T) { os.Remove(destFile) } +func TestCopyFilePreservesSource(t *testing.T) { + for _, mode := range []string{"same", "hardlink", "different"} { + t.Run(mode, func(t *testing.T) { + assert := internal.NewAssert(t, "TestCopyFilePreservesSource") + src := filepath.Join(t.TempDir(), "source.txt") + assert.IsNil(os.WriteFile(src, []byte("keep this content"), 0600)) + dst := src + ".copy" + if mode == "same" { + dst = src + } else if mode == "hardlink" { + if err := os.Link(src, dst); err != nil { + t.Skipf("hard links unavailable: %v", err) + } + } + err := CopyFile(src, dst) + if (err != nil) != (mode != "different") { + t.Errorf("unexpected copy result: %v", err) + } + data, err := os.ReadFile(src) + assert.IsNil(err) + assert.Equal("keep this content", string(data)) + data, err = os.ReadFile(dst) + assert.IsNil(err) + assert.Equal("keep this content", string(data)) + }) + } +} + func TestReadFileToString(t *testing.T) { assert := internal.NewAssert(t, "TestReadFileToString")