From 38b01d10dabcdd7a56b177d69a731a0cd9b906b6 Mon Sep 17 00:00:00 2001 From: Alessio Perugini Date: Fri, 15 Sep 2023 12:11:02 +0200 Subject: [PATCH] Fix CopyTo same filepath truncate the file --- paths.go | 4 ++++ paths_test.go | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/paths.go b/paths.go index 8b07bdc..c0c1e4b 100644 --- a/paths.go +++ b/paths.go @@ -317,6 +317,10 @@ func (p *Path) IsDirCheck() (bool, error) { // of the source file. The file mode will be copied from the source and // the copied data is synced/flushed to stable storage. func (p *Path) CopyTo(dst *Path) error { + if p.EqualsTo(dst) { + return fmt.Errorf("%s and %s are the same file", p.path, dst.path) + } + in, err := os.Open(p.path) if err != nil { return err diff --git a/paths_test.go b/paths_test.go index 116131f..8cf8fc4 100644 --- a/paths_test.go +++ b/paths_test.go @@ -388,3 +388,21 @@ func TestWriteToTempFile(t *testing.T) { require.NoError(t, err) require.Equal(t, tmpData, data) } + +func TestCopyToSamePath(t *testing.T) { + tmpDir := New(t.TempDir()) + srcFile := tmpDir.Join("test_file") + dstFile := srcFile + + // create the source file in tmp dir + err := srcFile.WriteFile([]byte("hello")) + require.NoError(t, err) + content, err := srcFile.ReadFile() + require.NoError(t, err) + require.Equal(t, []byte("hello"), content) + + // cannot copy the same file + err = srcFile.CopyTo(dstFile) + require.Error(t, err) + require.Contains(t, err.Error(), "are the same file") +}