Skip to content

Commit

Permalink
✨ feat(fs): add new util func ReadOrErr(), ReadStringOrErr() and with…
Browse files Browse the repository at this point in the history
… some unit tests
  • Loading branch information
inhere committed Apr 19, 2023
1 parent dadc1ca commit 4ab579b
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
23 changes: 23 additions & 0 deletions fsutil/opread.go
Expand Up @@ -55,6 +55,20 @@ func ReadString(in any) string {
return string(GetContents(in))
}

// ReadStringOrErr read contents from path or io.Reader, will panic on in type error
func ReadStringOrErr(in any) (string, error) {
r, err := NewIOReader(in)
if err != nil {
return "", err
}

bs, err := io.ReadAll(r)
if err != nil {
return "", err
}
return string(bs), nil
}

// ReadAll read contents from path or io.Reader, will panic on in type error
func ReadAll(in any) []byte { return GetContents(in) }

Expand All @@ -67,6 +81,15 @@ func GetContents(in any) []byte {
return MustReadReader(r)
}

// ReadOrErr read contents from path or io.Reader, will panic on in type error
func ReadOrErr(in any) ([]byte, error) {
r, err := NewIOReader(in)
if err != nil {
return nil, err
}
return io.ReadAll(r)
}

// ReadExistFile read file contents if existed, will panic on error
func ReadExistFile(filePath string) []byte {
if IsFile(filePath) {
Expand Down
9 changes: 9 additions & 0 deletions fsutil/opread_test.go
Expand Up @@ -10,10 +10,19 @@ import (

func TestDiscardReader(t *testing.T) {
sr := strings.NewReader("hello")
bs, err := fsutil.ReadOrErr(sr)
assert.NoErr(t, err)
assert.Eq(t, []byte("hello"), bs)

sr = strings.NewReader("hello")
assert.Eq(t, []byte("hello"), fsutil.GetContents(sr))

sr = strings.NewReader("hello")
fsutil.DiscardReader(sr)

assert.Empty(t, fsutil.ReadReader(sr))
assert.Empty(t, fsutil.ReadAll(sr))

}

func TestGetContents(t *testing.T) {
Expand Down
4 changes: 4 additions & 0 deletions fsutil/opwrite_test.go
Expand Up @@ -20,4 +20,8 @@ func TestMustCopyFile(t *testing.T) {
fsutil.MustCopyFile(srcPath, dstPath)
assert.Eq(t, []byte("hello"), fsutil.GetContents(dstPath))
assert.Eq(t, "hello", fsutil.ReadString(dstPath))

str, err := fsutil.ReadStringOrErr(dstPath)
assert.NoErr(t, err)
assert.Eq(t, "hello", str)
}

0 comments on commit 4ab579b

Please sign in to comment.