mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-18 02:52:36 +03:00
chore(lint): enable errchkjson (#6486)
errchkjson flags json.Marshal/MarshalIndent/Encoder.Encode calls whose error is discarded.
Fixed all 27 sites by hand: errors are returned where the caller already returns one, logged
in HTTP handlers and string-returning helpers, and asserted in tests.
check-error-free-encoding stays off so every encode error is handled, even for safe types.
report-no-exported is on, to catch structs that would silently encode as {}.
This commit is contained in:
1 parent
e9c0efa446
commit
986000db44
26 files changed
+134
-45
No files matched your search
@@ -14,6 +14,7 @@ linters:
|
||||
- depguard
|
||||
- dogsled
|
||||
- durationcheck
|
||||
- errchkjson
|
||||
- errorlint
|
||||
- forbidigo
|
||||
- gocritic
|
||||
@@ -124,6 +125,8 @@ linters:
|
||||
errcheck:
|
||||
exclude-functions:
|
||||
- (*github.com/zeebo/xxh3.Hasher).Write
|
||||
errchkjson:
|
||||
report-no-exported: true
|
||||
gocritic:
|
||||
disable-all: true
|
||||
enabled-checks:
|
||||
|
||||
@@ -162,7 +162,10 @@ func (c *client) path(endpoint string) (string, error) {
|
||||
}
|
||||
|
||||
func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) {
|
||||
b, _ := json.Marshal(r.Body)
|
||||
b, err := json.Marshal(r.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encoding request body: %w", err)
|
||||
}
|
||||
uri, err := c.path(endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
+4
-1
@@ -94,7 +94,10 @@ func writeMissingList(w io.Writer, format string, mfs model.MediaFileCursor) err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
j, _ := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path})
|
||||
j, err := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(bw, "%s%s", sep, j)
|
||||
sep = ","
|
||||
}
|
||||
|
||||
+4
-1
@@ -247,7 +247,10 @@ func runList(ctx context.Context) {
|
||||
display[idx].Public = playlist.Public
|
||||
}
|
||||
|
||||
j, _ := json.Marshal(display)
|
||||
j, err := json.Marshal(display)
|
||||
if err != nil {
|
||||
log.Fatal(ctx, "Failed to encode playlists", err)
|
||||
}
|
||||
fmt.Printf("%s\n", j)
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -509,8 +509,8 @@ func usersToJSON(value string) (string, error) {
|
||||
names = append(names, u)
|
||||
}
|
||||
}
|
||||
b, _ := json.Marshal(names)
|
||||
return string(b), nil
|
||||
b, err := json.Marshal(names)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
// librariesToJSON accepts either a JSON array (starts with '[') or a
|
||||
@@ -535,8 +535,8 @@ func librariesToJSON(value string) (string, error) {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
b, _ := json.Marshal(ids)
|
||||
return string(b), nil
|
||||
b, err := json.Marshal(ids)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
var pluginRescanCmd = &cobra.Command{
|
||||
|
||||
+4
-1
@@ -469,7 +469,10 @@ func runUserList(ctx context.Context) {
|
||||
users[idx].Libraries = paths
|
||||
}
|
||||
|
||||
j, _ := json.Marshal(users)
|
||||
j, err := json.Marshal(users)
|
||||
if err != nil {
|
||||
log.Fatal(ctx, "Failed to encode users", err)
|
||||
}
|
||||
fmt.Printf("%s\n", j)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/utils/str"
|
||||
)
|
||||
|
||||
@@ -94,7 +95,10 @@ func encodeSteps(steps []TraceStep, sourcePath string) string {
|
||||
}
|
||||
out = append(out, storedStep{C: s.Candidate, O: s.Outcome, D: str.TruncateRunes(d, maxTraceDetail, "...")})
|
||||
}
|
||||
b, _ := json.Marshal(out) // []storedStep is all strings, so this cannot fail
|
||||
b, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
log.Error("Artwork: Could not encode resolution trace", err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
|
||||
@@ -134,7 +134,8 @@ func (ffs *FakeFS) UpdateTags(filePath string, newTags map[string]any, when ...t
|
||||
var tags map[string]any
|
||||
gomega.Expect(json.Unmarshal(f.Data, &tags)).To(gomega.Succeed())
|
||||
maps.Copy(tags, newTags)
|
||||
data, _ := json.Marshal(tags)
|
||||
data, err := json.Marshal(tags)
|
||||
gomega.Expect(err).ToNot(gomega.HaveOccurred())
|
||||
f.Data = data
|
||||
ffs.Touch(filePath, when...)
|
||||
}
|
||||
@@ -208,7 +209,8 @@ func File(tags ...map[string]any) *fstest.MapFile {
|
||||
if _, ok := ts[fakeFileInfoMode]; !ok {
|
||||
ts[fakeFileInfoMode] = fs.ModePerm
|
||||
}
|
||||
data, _ := json.Marshal(ts)
|
||||
data, err := json.Marshal(ts)
|
||||
gomega.Expect(err).ToNot(gomega.HaveOccurred())
|
||||
if _, ok := ts[fakeFileInfoSize]; !ok {
|
||||
ts[fakeFileInfoSize] = int64(len(data))
|
||||
}
|
||||
|
||||
@@ -26,7 +26,8 @@ func withProbe(mf *model.MediaFile) *model.MediaFile {
|
||||
BitDepth: gg.V(mf.BitDepth),
|
||||
Channels: mf.Channels,
|
||||
}
|
||||
data, _ := json.Marshal(probe)
|
||||
data, err := json.Marshal(probe)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
mf.ProbeData = string(data)
|
||||
return mf
|
||||
}
|
||||
|
||||
@@ -79,8 +79,13 @@ func (a *dbAlbum) PostMapArgs(args map[string]any) error {
|
||||
args["search_participants"] = strings.Join(participantNames, " ")
|
||||
args["search_normalized"] = str.NormalizeForFTS(a.Name, a.AlbumArtist)
|
||||
|
||||
args["tags"] = marshalTags(a.Album.Tags)
|
||||
args["participants"] = marshalParticipants(a.Album.Participants)
|
||||
var err error
|
||||
if args["tags"], err = marshalTags(a.Album.Tags); err != nil {
|
||||
return err
|
||||
}
|
||||
if args["participants"], err = marshalParticipants(a.Album.Participants); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
folderIDs, err := json.Marshal(a.Album.FolderIDs)
|
||||
if err != nil {
|
||||
|
||||
@@ -102,7 +102,10 @@ func (a *dbArtist) PostMapArgs(m map[string]any) error {
|
||||
for _, s := range a.Artist.SimilarArtists {
|
||||
sa = append(sa, dbSimilarArtist{ID: s.ID, Name: s.Name})
|
||||
}
|
||||
similarArtists, _ := json.Marshal(sa)
|
||||
similarArtists, err := json.Marshal(sa)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshalling similar artists: %w", err)
|
||||
}
|
||||
m["similar_artists"] = string(similarArtists)
|
||||
// When adding a derived column here, also add it to the scanner's artist Put column list
|
||||
// in phase_1_folders.go, or rescans will never update it (how search_normalized went stale).
|
||||
|
||||
@@ -250,7 +250,10 @@ func setupBenchData(b *testing.B, ctx context.Context, conn *dbx.DB, user model.
|
||||
primaryArtistName := fmt.Sprintf("Artist %04d", primaryArtistIdx)
|
||||
|
||||
participants := map[string][]map[string]string{"artist": artistEntries}
|
||||
participantsJSON, _ := json.Marshal(participants)
|
||||
participantsJSON, err := json.Marshal(participants)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := mfStmt.Exec(
|
||||
trackID,
|
||||
|
||||
@@ -74,8 +74,13 @@ func (m *dbMediaFile) PostMapArgs(args map[string]any) error {
|
||||
args["full_text"] = formatFullText(fullText...)
|
||||
args["search_participants"] = strings.Join(participantNames, " ")
|
||||
args["search_normalized"] = str.NormalizeForFTS(m.FullTitle(), m.Album, m.Artist, m.AlbumArtist)
|
||||
args["tags"] = marshalTags(m.MediaFile.Tags)
|
||||
args["participants"] = marshalParticipants(m.MediaFile.Participants)
|
||||
var err error
|
||||
if args["tags"], err = marshalTags(m.MediaFile.Tags); err != nil {
|
||||
return err
|
||||
}
|
||||
if args["participants"], err = marshalParticipants(m.MediaFile.Participants); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -47,15 +47,18 @@ func participantIDFilter(table string, artistID any, negate bool, roles []model.
|
||||
return Expr(table+".id"+op+sql+")", args...)
|
||||
}
|
||||
|
||||
func marshalParticipants(participants model.Participants) string {
|
||||
func marshalParticipants(participants model.Participants) (string, error) {
|
||||
dbParticipants := make(map[model.Role][]participant)
|
||||
for role, artists := range participants {
|
||||
for _, artist := range artists {
|
||||
dbParticipants[role] = append(dbParticipants[role], participant{ID: artist.ID, SubRole: artist.SubRole, Name: artist.Name})
|
||||
}
|
||||
}
|
||||
res, _ := json.Marshal(dbParticipants)
|
||||
return string(res)
|
||||
res, err := json.Marshal(dbParticipants)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshalling participants: %w", err)
|
||||
}
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func unmarshalParticipants(data string) (model.Participants, error) {
|
||||
|
||||
@@ -36,7 +36,7 @@ func unmarshalTags(data string) (model.Tags, error) {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func marshalTags(tags model.Tags) string {
|
||||
func marshalTags(tags model.Tags) (string, error) {
|
||||
dbTags := dbTags{}
|
||||
for name, values := range tags {
|
||||
for _, value := range values {
|
||||
@@ -44,8 +44,11 @@ func marshalTags(tags model.Tags) string {
|
||||
dbTags[name] = append(dbTags[name], dbTag{ID: t.ID, Value: value})
|
||||
}
|
||||
}
|
||||
res, _ := json.Marshal(dbTags)
|
||||
return string(res)
|
||||
res, err := json.Marshal(dbTags)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshalling tags: %w", err)
|
||||
}
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
// indexedTagNames are the tag types materialized into the <table>_tags join tables, so filtering by
|
||||
|
||||
@@ -98,7 +98,10 @@ func setupTestConfigPlugin(configJSON string) (*Manager, func(context.Context, t
|
||||
}
|
||||
defer instance.Close(ctx)
|
||||
|
||||
inputBytes, _ := json.Marshal(input)
|
||||
inputBytes, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, outputBytes, err := instance.Call("nd_test_config", inputBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -459,6 +459,6 @@ func (r *fakeSubsonicRouter) ServeHTTP(w http.ResponseWriter, req *http.Request)
|
||||
},
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(response)
|
||||
Expect(json.NewEncoder(w).Encode(response)).To(Succeed())
|
||||
}
|
||||
}
|
||||
@@ -517,7 +517,10 @@ func callTestUsersPlugin(ctx context.Context, manager *Manager, input testUsersI
|
||||
}
|
||||
defer instance.Close(ctx)
|
||||
|
||||
inputBytes, _ := json.Marshal(input)
|
||||
inputBytes, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, outputBytes, err := instance.Call("nd_test_users", inputBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
+16
-6
@@ -31,10 +31,12 @@ func adminContext(ctx context.Context) context.Context {
|
||||
return request.WithUser(ctx, model.User{IsAdmin: true})
|
||||
}
|
||||
|
||||
// marshalManifest marshals a manifest to JSON string, returning empty string on error.
|
||||
func marshalManifest(m *Manifest) string {
|
||||
b, _ := json.Marshal(m)
|
||||
return string(b)
|
||||
func marshalManifest(m *Manifest) (string, error) {
|
||||
b, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshalling manifest: %w", err)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// ComputeFileSHA256 computes the SHA-256 hash of a file without loading it into memory.
|
||||
@@ -55,11 +57,15 @@ func ComputeFileSHA256(path string) (string, error) {
|
||||
|
||||
// addPluginToDB adds a new plugin to the database as disabled.
|
||||
func (m *Manager) addPluginToDB(ctx context.Context, repo model.PluginRepository, name, path string, metadata *PluginMetadata) error {
|
||||
manifest, err := marshalManifest(metadata.Manifest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
newPlugin := &model.Plugin{
|
||||
ID: name,
|
||||
Path: path,
|
||||
Manifest: marshalManifest(metadata.Manifest),
|
||||
Manifest: manifest,
|
||||
SHA256: metadata.SHA256,
|
||||
Enabled: false,
|
||||
CreatedAt: now,
|
||||
@@ -76,6 +82,10 @@ func (m *Manager) addPluginToDB(ctx context.Context, repo model.PluginRepository
|
||||
// updatePluginInDB updates an existing plugin in the database after a file change.
|
||||
// If the plugin was enabled, it will be unloaded and disabled.
|
||||
func (m *Manager) updatePluginInDB(ctx context.Context, repo model.PluginRepository, dbPlugin *model.Plugin, path string, metadata *PluginMetadata) error {
|
||||
manifest, err := marshalManifest(metadata.Manifest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wasEnabled := dbPlugin.Enabled
|
||||
if wasEnabled {
|
||||
if err := m.unloadPlugin(dbPlugin.ID); err != nil {
|
||||
@@ -83,7 +93,7 @@ func (m *Manager) updatePluginInDB(ctx context.Context, repo model.PluginReposit
|
||||
}
|
||||
}
|
||||
dbPlugin.Path = path
|
||||
dbPlugin.Manifest = marshalManifest(metadata.Manifest)
|
||||
dbPlugin.Manifest = manifest
|
||||
dbPlugin.SHA256 = metadata.SHA256
|
||||
dbPlugin.Enabled = false
|
||||
dbPlugin.LastError = ""
|
||||
|
||||
@@ -46,6 +46,10 @@ func withBasePath(body []byte, key string, quotedInBundle bool) []byte {
|
||||
return body
|
||||
}
|
||||
// A JSON string is also a valid YAML double-quoted scalar, so one encoding escapes both formats.
|
||||
newURL, _ := json.Marshal(serverURL)
|
||||
newURL, err := json.Marshal(serverURL)
|
||||
if err != nil {
|
||||
log.Error("API v1: could not encode the server URL, serving the spec without the base path", err)
|
||||
return body
|
||||
}
|
||||
return bytes.Replace(body, old, append([]byte(key), newURL...), 1)
|
||||
}
|
||||
+10
-2
@@ -7,6 +7,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/navidrome/navidrome/log"
|
||||
)
|
||||
|
||||
type eventCtxKey string
|
||||
@@ -31,7 +33,10 @@ func (e *baseEvent) Name(evt Event) string {
|
||||
}
|
||||
|
||||
func (e *baseEvent) Data(evt Event) string {
|
||||
data, _ := json.Marshal(evt)
|
||||
data, err := json.Marshal(evt)
|
||||
if err != nil {
|
||||
log.Error("Error encoding event", "event", e.Name(evt), err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
@@ -84,6 +89,9 @@ func (rr *RefreshResource) Data(evt Event) string {
|
||||
return `{"*":"*"}`
|
||||
}
|
||||
r := evt.(*RefreshResource)
|
||||
data, _ := json.Marshal(r.resources)
|
||||
data, err := json.Marshal(r.resources)
|
||||
if err != nil {
|
||||
log.Error("Error encoding refresh event", err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
@@ -77,7 +77,11 @@ func (d *Discovery) ServeOn(ctx context.Context, conn net.PacketConn) {
|
||||
continue
|
||||
}
|
||||
info := discoveryInfo{Address: discoveryAddress(ctx, remote), Id: d.serverID(ctx), Name: serverName()}
|
||||
res, _ := json.Marshal(info)
|
||||
res, err := json.Marshal(info)
|
||||
if err != nil {
|
||||
log.Error(ctx, "Jellyfin API: could not encode auto-discovery response", err)
|
||||
continue
|
||||
}
|
||||
log.Debug(ctx, "Jellyfin API: answering auto-discovery request", "from", remote.String(), "address", info.Address)
|
||||
if _, err := conn.WriteTo(res, remote); err != nil {
|
||||
log.Debug(ctx, "Jellyfin API: could not answer auto-discovery request", "to", remote.String(), err)
|
||||
|
||||
@@ -138,7 +138,9 @@ func (api *Router) updatePlugin(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
_ = json.NewEncoder(w).Encode(errorResponse)
|
||||
if err := json.NewEncoder(w).Encode(errorResponse); err != nil {
|
||||
log.Error(ctx, "Error encoding enable plugin error response", "id", id, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
} else {
|
||||
@@ -186,7 +188,9 @@ func validateAndUpdateConfig(ctx context.Context, pm PluginManager, id, configJS
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
// Try to return structured validation errors if available
|
||||
response := map[string]any{"message": err.Error()}
|
||||
_ = json.NewEncoder(w).Encode(response)
|
||||
if encErr := json.NewEncoder(w).Encode(response); encErr != nil {
|
||||
log.Error(ctx, "Error encoding config validation response", "id", id, encErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -71,6 +71,8 @@ func writeQuickConnectResult(w http.ResponseWriter, r *http.Request, req quickco
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
default:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(quickConnectDevice{AppName: req.Device.App, AppVersion: req.Device.AppVersion, DeviceName: req.Device.Name})
|
||||
if err := json.NewEncoder(w).Encode(quickConnectDevice{AppName: req.Device.App, AppVersion: req.Device.AppVersion, DeviceName: req.Device.Name}); err != nil {
|
||||
log.Error(r.Context(), "Error encoding Quick Connect response", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -359,7 +359,7 @@ func sendResponseWithStatus(w http.ResponseWriter, r *http.Request, payload *res
|
||||
errResp := newResponse()
|
||||
errResp.Status = responses.StatusFailed
|
||||
errResp.Error = &responses.Error{Code: responses.ErrorGeneric, Message: "invalid callback parameter"}
|
||||
response, _ = json.Marshal(responses.JsonWrapper{Subsonic: *errResp})
|
||||
response, err = json.Marshal(responses.JsonWrapper{Subsonic: *errResp})
|
||||
break
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/javascript")
|
||||
|
||||
Vendored
+11
-4
@@ -5,6 +5,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -42,7 +43,10 @@ func NewHTTPClient(wrapped httpDoer, ttl time.Duration) *HTTPClient {
|
||||
}
|
||||
|
||||
func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
|
||||
key := c.serializeReq(req)
|
||||
key, err := c.serializeReq(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cached := true
|
||||
start := time.Now()
|
||||
respStr, err := c.cache.GetWithLoader(key, func(key string) (string, time.Duration, error) {
|
||||
@@ -67,7 +71,7 @@ func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
|
||||
return c.deserializeResponse(req, respStr)
|
||||
}
|
||||
|
||||
func (c *HTTPClient) serializeReq(req *http.Request) string {
|
||||
func (c *HTTPClient) serializeReq(req *http.Request) (string, error) {
|
||||
data := requestData{
|
||||
Method: req.Method,
|
||||
Header: req.Header,
|
||||
@@ -77,8 +81,11 @@ func (c *HTTPClient) serializeReq(req *http.Request) string {
|
||||
bodyData, _ := io.ReadAll(req.Body)
|
||||
data.Body = new(base64.StdEncoding.EncodeToString(bodyData))
|
||||
}
|
||||
j, _ := json.Marshal(&data)
|
||||
return string(j)
|
||||
j, err := json.Marshal(&data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encoding request cache key: %w", err)
|
||||
}
|
||||
return string(j), nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) deserializeReq(reqStr string) (*http.Request, error) {
|
||||
|
||||
Reference in new issue
Block a user