diff --git a/internal/entity/file_normal.go b/internal/entity/file_normal.go index 11730fab08..a773c7d7e3 100644 --- a/internal/entity/file_normal.go +++ b/internal/entity/file_normal.go @@ -3,38 +3,21 @@ package entity import ( + "github.com/Zxilly/go-size-analyzer/internal/utils" "github.com/go-json-experiment/json" "github.com/go-json-experiment/json/jsontext" ) var FileMarshalerCompact = json.MarshalFuncV2[File](func(encoder *jsontext.Encoder, file File, options json.Options) error { - err := encoder.WriteToken(jsontext.ObjectStart) - if err != nil { - return err - } + utils.Must(encoder.WriteToken(jsontext.ObjectStart)) - if err = json.MarshalEncode(encoder, "file_path", options); err != nil { - return err - } - if err = json.MarshalEncode(encoder, file.FilePath, options); err != nil { - return err - } - if err = json.MarshalEncode(encoder, "size", options); err != nil { - return err - } - if err = json.MarshalEncode(encoder, file.FullSize(), options); err != nil { - return err - } - if err = json.MarshalEncode(encoder, "pcln_size", options); err != nil { - return err - } - if err = json.MarshalEncode(encoder, file.PclnSize(), options); err != nil { - return err - } + utils.Must(json.MarshalEncode(encoder, "file_path", options)) + utils.Must(json.MarshalEncode(encoder, file.FilePath, options)) + utils.Must(json.MarshalEncode(encoder, "size", options)) + utils.Must(json.MarshalEncode(encoder, file.FullSize(), options)) + utils.Must(json.MarshalEncode(encoder, "pcln_size", options)) + utils.Must(json.MarshalEncode(encoder, file.PclnSize(), options)) - err = encoder.WriteToken(jsontext.ObjectEnd) - if err != nil { - return err - } + utils.Must(encoder.WriteToken(jsontext.ObjectEnd)) return nil }) diff --git a/internal/utils/utils.go b/internal/utils/utils.go index 0f3ff719d0..272623cb66 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -116,3 +116,9 @@ func PrefixToPath(s string) (string, error) { } return string(p), nil } + +func Must(err error) { + if err != nil { + panic(err) + } +} diff --git a/internal/utils/utils_test.go b/internal/utils/utils_test.go index 3a0067f96a..4f35ac7e7f 100644 --- a/internal/utils/utils_test.go +++ b/internal/utils/utils_test.go @@ -2,6 +2,7 @@ package utils import ( "debug/gosym" + "fmt" "reflect" "testing" "unsafe" @@ -93,3 +94,13 @@ func TestPrefixToPath(t *testing.T) { } } } + +func TestMust(t *testing.T) { + t.Run("does not panic for nil error", func(t *testing.T) { + assert.NotPanics(t, func() { Must(nil) }) + }) + + t.Run("panics for non-nil error", func(t *testing.T) { + assert.Panics(t, func() { Must(fmt.Errorf("test error")) }) + }) +}