Skip to content

Commit

Permalink
helper.Duplicate uses openfile.
Browse files Browse the repository at this point in the history
  • Loading branch information
bengarrett committed Jul 2, 2024
1 parent 4054be8 commit 5d38840
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
9 changes: 4 additions & 5 deletions internal/helper/os.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,16 @@ func Count(dir string) (int, error) {

// Duplicate is a workaround for renaming files across different devices.
// A cross device can also be a different file system such as a Docker volume.
// It returns the number of bytes written to the new file.
func Duplicate(oldpath, newpath string) (int64, error) {
src, err := os.Open(oldpath)
if err != nil {
return 0, fmt.Errorf("duplicate os.open %w", err)
}
defer src.Close()
dst, err := os.Create(newpath)

const createNoTruncate = os.O_CREATE | os.O_WRONLY | os.O_EXCL
dst, err := os.OpenFile(newpath, createNoTruncate, WriteWriteRead)
if err != nil {
return 0, fmt.Errorf("duplicate os.create %w", err)
}
Expand All @@ -105,10 +108,6 @@ func Duplicate(oldpath, newpath string) (int64, error) {
if err != nil {
return 0, fmt.Errorf("duplicate io.copy %w", err)
}
if err = os.Chmod(newpath, WriteWriteRead); err != nil {
defer os.Remove(newpath)
return 0, fmt.Errorf("duplicate os.chmod %d %w", WriteWriteRead, err)
}
return written, nil
}

Expand Down
40 changes: 40 additions & 0 deletions internal/helper/os_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,46 @@ func TestCount(t *testing.T) {
assert.Equal(t, testDataFileCount, i)
}

func TestDuplicate(t *testing.T) {
dir, err := filepath.Abs("../../assets/testdata")
require.NoError(t, err)

r, err := helper.Duplicate(dir, "")
require.Error(t, err)
assert.Empty(t, r)
r, err = helper.Duplicate(dir, dir)
require.Error(t, err)
assert.Empty(t, r)

file, err := filepath.Abs("../../assets/testdata/uncompress/TEST.NFO")
require.NoError(t, err)

r, err = helper.Duplicate(file, "")
require.Error(t, err)
assert.Empty(t, r)

r, err = helper.Duplicate("", file)
require.Error(t, err)
assert.Empty(t, r)

r, err = helper.Duplicate(file, file)
require.Error(t, err)
assert.Empty(t, r)

dest, err := os.MkdirTemp(os.TempDir(), "test_duplicate")
require.NoError(t, err)
defer os.RemoveAll(dest)

r, err = helper.Duplicate(file, dest)
require.Error(t, err)
assert.Empty(t, r)

dest = filepath.Join(dest, "TEST.NFO")
written, err := helper.Duplicate(file, dest)
require.NoError(t, err)
assert.Equal(t, written, int64(13))
}

func TestFiles(t *testing.T) {
dir, err := filepath.Abs("../../assets/testdata")
require.NoError(t, err)
Expand Down

0 comments on commit 5d38840

Please sign in to comment.