Skip to content

Commit

Permalink
Add FileSizeInBytes to FileManager
Browse files Browse the repository at this point in the history
  • Loading branch information
gaborpongracz committed Aug 1, 2024
1 parent 613f4cb commit 98ac150
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
13 changes: 13 additions & 0 deletions fileutil/fileutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type FileManager interface {
RemoveAll(path string) error
Write(path string, value string, perm os.FileMode) error
WriteBytes(path string, value []byte) error
FileSizeInBytes(pth string) (float64, error)
}

type fileManager struct {
Expand Down Expand Up @@ -89,3 +90,15 @@ func (fileManager) ensureSavePath(savePath string) error {
func (f fileManager) WriteBytes(path string, value []byte) error {
return os.WriteFile(path, value, 0600)
}

func (fileManager) FileSizeInBytes(pth string) (float64, error) {
if pth == "" {
return 0, errors.New("No path provided")
}
fileInf, err := os.Lstat(pth)
if err != nil {
return 0, err
}

return float64(fileInf.Size()), nil
}
32 changes: 31 additions & 1 deletion fileutil/fileutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import (
"path/filepath"
"testing"

"github.com/bitrise-io/go-utils/v2/pathutil"
"github.com/stretchr/testify/require"

"github.com/bitrise-io/go-utils/v2/pathutil"
)

func TestWrite(t *testing.T) {
Expand Down Expand Up @@ -52,3 +53,32 @@ func TestWrite(t *testing.T) {
require.Error(t, manager.WriteBytes(tmpFilePath, []byte("test string")), "open "+tmpFilePath+": no such file or directory")
}
}

func TestFileSizeInBytes(t *testing.T) {
provider := pathutil.NewPathProvider()
tmpDirPath, err := provider.CreateTempDir("go-utils-test-")
require.NoError(t, err)
manager := NewFileManager()
t.Run("Success when existing file provided", func(t *testing.T) {
const content = "test string"
{
tmpFilePath := filepath.Join(tmpDirPath, "FileSizeInBytes-success.txt")
require.NoError(t, manager.Write(tmpFilePath, content, 0600))

fileSize, err := manager.FileSizeInBytes(tmpFilePath)
require.NoError(t, err)
require.Equal(t, float64(len([]byte(content))), fileSize)
}
})

t.Run("Failure when non-existing path", func(t *testing.T) {
tmpFilePath := filepath.Join(tmpDirPath, "dir-does-not-exist-2", "FileSizeInBytes-error.txt")
_, err := manager.FileSizeInBytes(tmpFilePath)
require.EqualError(t, err, "lstat "+tmpFilePath+": no such file or directory")
})

t.Run("Failure when path is empty string", func(t *testing.T) {
_, err := manager.FileSizeInBytes("")
require.EqualError(t, err, "No path provided")
})
}

0 comments on commit 98ac150

Please sign in to comment.