From 4ab579ba85eb88ef11dca04c041e96309c1d3f0d Mon Sep 17 00:00:00 2001 From: Inhere Date: Wed, 19 Apr 2023 14:53:38 +0800 Subject: [PATCH] :sparkles: feat(fs): add new util func ReadOrErr(), ReadStringOrErr() and with some unit tests --- fsutil/opread.go | 23 +++++++++++++++++++++++ fsutil/opread_test.go | 9 +++++++++ fsutil/opwrite_test.go | 4 ++++ 3 files changed, 36 insertions(+) diff --git a/fsutil/opread.go b/fsutil/opread.go index 68addecce..23f552332 100644 --- a/fsutil/opread.go +++ b/fsutil/opread.go @@ -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) } @@ -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) { diff --git a/fsutil/opread_test.go b/fsutil/opread_test.go index db4024c91..c01509519 100644 --- a/fsutil/opread_test.go +++ b/fsutil/opread_test.go @@ -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) { diff --git a/fsutil/opwrite_test.go b/fsutil/opwrite_test.go index 99e8bf72b..e4d425fbd 100644 --- a/fsutil/opwrite_test.go +++ b/fsutil/opwrite_test.go @@ -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) }