Skip to content

Commit

Permalink
style: no error will throw for marshaler
Browse files Browse the repository at this point in the history
  • Loading branch information
Zxilly committed May 30, 2024
1 parent be0f2e3 commit 5618c4d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 26 deletions.
35 changes: 9 additions & 26 deletions internal/entity/file_normal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
6 changes: 6 additions & 0 deletions internal/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,9 @@ func PrefixToPath(s string) (string, error) {
}
return string(p), nil
}

func Must(err error) {
if err != nil {
panic(err)
}
}
11 changes: 11 additions & 0 deletions internal/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import (
"debug/gosym"
"fmt"
"reflect"
"testing"
"unsafe"
Expand Down Expand Up @@ -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")) })
})
}

0 comments on commit 5618c4d

Please sign in to comment.