diff --git a/storage.go b/storage.go index 8ba4a9d..c4cf72d 100644 --- a/storage.go +++ b/storage.go @@ -246,3 +246,30 @@ func (s *Storage) Stat(name string) (*FileInfo, error) { return fileInfo, nil } + +// Copy copies a file from one place to another. +// It takes the file name, and the destination name as its parameter. +// The function returns an error, if any. +func (s *Storage) Copy(name string, dest string) error { + if s.s3Client != nil { + if _, err := s.s3Client.CopyObject(s.ctx, minio.CopyDestOptions{ + Bucket: s.config.S3BucketName, + Object: dest, + }, minio.CopySrcOptions{ + Bucket: s.config.S3BucketName, + Object: name, + }); err != nil { + return err + } + return nil + } else { + fileContent, err := os.ReadFile(filepath.Join(s.config.Path, name)) + if err != nil { + return err + } + if err := os.WriteFile(filepath.Join(s.config.Path, dest), fileContent, 0600); err != nil { + return err + } + return nil + } +} diff --git a/storage_test.go b/storage_test.go index 8313616..0429ff8 100644 --- a/storage_test.go +++ b/storage_test.go @@ -31,6 +31,16 @@ func TestStorageLocal(t *testing.T) { assert.NoError(t, err) assert.Equal(t, []byte("hi"), fileContent) + t.Log("== Copy ==") + err = stor.Copy("test.txt", "test2.txt") + assert.NoError(t, err) + + copyFileInfo, err := stor.Stat("test2.txt") + assert.NoError(t, err) + assert.Equal(t, fs.FileMode(0600), copyFileInfo.Mode) + assert.Equal(t, "test2.txt", copyFileInfo.Name) + assert.Equal(t, int64(len("hi")), fileInfo.Size) + t.Log("== Open ==") file, err := stor.Open("test.txt") assert.NoError(t, err) @@ -76,6 +86,16 @@ func TestStorageS3(t *testing.T) { assert.NoError(t, err) assert.Equal(t, []byte("hi"), fileContent) + t.Log("== Copy ==") + err = stor.Copy("test.txt", "test2.txt") + assert.NoError(t, err) + + copyFileInfo, err := stor.Stat("test2.txt") + assert.NoError(t, err) + assert.Equal(t, fs.FileMode(0777), copyFileInfo.Mode) + assert.Equal(t, "test2.txt", copyFileInfo.Name) + assert.Equal(t, int64(len("hi")), fileInfo.Size) + t.Log("== Open ==") file, err := stor.Open("test.txt") assert.NoError(t, err)