chore(lint): enable godoclint start-with-name (#6498)

This commit is contained in:
Deluan Quintão 2026-11-17 20:38:14 -05:00 committed by GitHub
parent 110567aaca
commit 798305ef09
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
68 changed files with 156 additions and 117 deletions

View File

@ -21,6 +21,7 @@ linters:
- ginkgolinter
- gocritic
- gocyclo
- godoclint
- goprintffuncname
- gosec
- misspell
@ -136,6 +137,14 @@ linters:
force-succeed: true
force-tonot: true
validate-async-intervals: true
godoclint:
# a doc comment that names another symbol (left behind by a move or a paste) is a bug
default: none
enable:
- start-with-name
options:
start-with-name:
include-unexported: true
gocritic:
disable-all: true
enabled-checks:

View File

@ -246,7 +246,7 @@ func parseASFAttributes(rawAttrs map[string][]string, tags map[string][]string)
}
}
// These are the only roles we support, based on Picard's tag map:
// tiplMapping lists the only roles we support, based on Picard's tag map:
// https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html
var tiplMapping = map[string]string{
"arranger": "arranger",

View File

@ -243,8 +243,8 @@ var (
artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`)
artistIgnoredImage = "2a96cbd8b46e442fc41c2b86b821562f" // Last.fm artist placeholder image name
// Not a RetryLaterError on purpose: parking the agent would also stall its API-backed
// methods, which the page block does not affect.
// errNoArtistPage is not a RetryLaterError on purpose: parking the agent would also stall its
// API-backed methods, which the page block does not affect.
errNoArtistPage = errors.New("no artist image in Last.fm page")
)

View File

@ -449,6 +449,7 @@ func startPluginManager(ctx context.Context) func() error {
}
// TODO: Implement some struct tags to map flags to viper
func init() {
cobra.OnInitialize(func() {
conf.InitConfig(cfgFile, true)

View File

@ -728,7 +728,7 @@ func asWrittenInConfigFile(keys []string) []string {
})
}
// Matches keys and section headers in all supported config formats.
// configFileKeyRx matches keys and section headers in all supported config formats.
var configFileKeyRx = regexp.MustCompile(`(?m)^\s*\[?\s*"?([\w.]+)"?\s*[]=:]`)
// configKeys maps every accepted option name, lowercased, to its canonical spelling,

View File

@ -212,13 +212,11 @@ var (
var HTTPUserAgent = "Navidrome/" + Version + " - https://github.com/navidrome"
var (
VariousArtists = "Various Artists"
// TODO This will be dynamic when using disambiguation
VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU"
UnknownAlbum = "[Unknown Album]"
UnknownArtist = "[Unknown Artist]"
// TODO This will be dynamic when using disambiguation
UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist))
VariousArtists = "Various Artists"
VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU" // TODO This will be dynamic when using disambiguation
UnknownAlbum = "[Unknown Album]"
UnknownArtist = "[Unknown Artist]"
UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist)) // TODO This will be dynamic when using disambiguation
VariousArtistsMbzId = "89ad4ac3-39f7-470e-963a-56509c546377"
ArtistJoiner = " • "

View File

@ -6,7 +6,7 @@ import (
)
var (
// This will be set in build time. If not, version will be set to "dev"
// gitTag will be set in build time. If not, version will be set to "dev"
gitTag string
gitSha string
)

View File

@ -61,7 +61,7 @@ func (a *archiver) ZipArtist(ctx context.Context, id string, format string, bitr
return a.zipAlbums(ctx, id, format, bitrate, out, filter, model.Artist{ID: id}.CoverArtID())
}
// rootArt, when set, is added to the archive root.
// zipAlbums writes the songs matching filters to out. rootArt, when set, is added to the archive root.
func (a *archiver) zipAlbums(ctx context.Context, id string, format string, bitrate int, out io.Writer, filters squirrel.Sqlizer, rootArt model.ArtworkID) error {
mfs, err := a.ds.MediaFile().GetAll(ctx, model.QueryOptions{Filters: filters, Sort: "album"})
if err != nil {
@ -112,8 +112,8 @@ func createZipWriter(out io.Writer, format string, bitrate int) *zip.Writer {
return z
}
// Tried in order; the first one whose values are distinct across the clashing albums wins.
// One album may have an empty value: it keeps the plain name, which the others can't clash with.
// albumDisambiguators are tried in order; the first one whose values are distinct across the clashing
// albums wins. One album may have an empty value: it keeps the plain name, which the others can't clash with.
var albumDisambiguators = []func(model.MediaFile) string{
func(mf model.MediaFile) string { return mf.Tags.First(model.TagAlbumVersion) },
func(mf model.MediaFile) string {
@ -346,7 +346,7 @@ func (a *archiver) readCoverArt(ctx context.Context, artID model.ArtworkID) ([]b
return io.ReadAll(img)
}
// Resizing may re-encode the image, so the type comes from its bytes.
// coverArtExtension takes the type from the image bytes, because resizing may re-encode the image.
func coverArtExtension(data []byte) string {
switch http.DetectContentType(data) {
case "image/jpeg":

View File

@ -200,7 +200,7 @@ func (d *discArtworkReader) fromDiscSubtitle(ctx context.Context, subtitle strin
}
}
// filepath.Match's '\' escape is excluded on purpose: treating it as a metachar
// globMetaChars excludes filepath.Match's '\' escape on purpose: treating it as a metachar
// would misalign the literal-prefix extraction in extractDiscNumber.
const globMetaChars = "*?["

View File

@ -10,14 +10,14 @@ import (
)
const (
// 4 bits per channel: coarse enough that near-identical pixels land together, fine enough that
// bits per channel: 4 is coarse enough that near-identical pixels land together, fine enough that
// distinct colours stay apart.
bits = 4
nBins = 1 << (3 * bits)
// Only the heaviest bins can win, and merging is O(n^2) over whatever survives.
// maxBins caps the bins kept: only the heaviest can win, and merging is O(n^2) over whatever survives.
maxBins = 64
// Oklab distance below which two bins are the same colour to the eye. Merging matters because a
// gradient splits across adjacent bins and would otherwise lose to a smaller flat region.
// mergeDist is the Oklab distance below which two bins are the same colour to the eye. Merging matters
// because a gradient splits across adjacent bins and would otherwise lose to a smaller flat region.
mergeDist = 0.10
)

View File

@ -180,8 +180,9 @@ func chainFetchesExternal(priority string) bool {
return false
}
// Album and artist fetches stop here when the resolver is local-only, rather than at each point in
// the chain walk; resolvePlaylist gates the third network path, the m3u image URL, itself.
// fetchExternalAlbum and fetchExternalArtist are where album and artist fetches stop when the resolver is
// local-only, rather than at each point in the chain walk; resolvePlaylist gates the third network path,
// the m3u image URL, itself.
func (r *resolver) fetchExternalAlbum(ctx context.Context, al model.Album) (io.ReadCloser, string, error) {
if r.ext == nil {
return nil, "", nil

View File

@ -56,7 +56,7 @@ func fromExternalFile(ctx context.Context, libFS fs.FS, files []string, pattern
}
}
// These regexes are used to match the picture type in the file, in the order they are listed.
// picTypeRegexes match the picture type in the file, in the order they are listed.
var picTypeRegexes = []*regexp.Regexp{
regexp.MustCompile(`(?i).*cover.*front.*|.*front.*cover.*`),
regexp.MustCompile(`(?i).*front.*`),

View File

@ -230,7 +230,7 @@ func pack(w, h int, hasAlpha bool, lx, ly int,
return hash
}
// NRGBA, not RGBA: ThumbHash requires non-premultiplied RGB and the pipeline hands us a
// toNRGBA returns NRGBA, not RGBA: ThumbHash requires non-premultiplied RGB and the pipeline hands us a
// premultiplied *image.RGBA, which draw.Draw un-premultiplies on the way in.
func toNRGBA(img image.Image) *image.NRGBA {
// Conservative: a sub-image re-slices Pix so the loops would read it correctly too, but the

View File

@ -18,6 +18,7 @@ func userName(ctx context.Context) string {
// BFR We should only access files through the `storage.Storage` interface. This will require changing how
// TagLib and ffmpeg access files
var AbsolutePath = func(ctx context.Context, ds model.DataStore, libId int, path string) string {
libPath, err := ds.Library().GetPath(ctx, libId)
if err != nil {

View File

@ -19,8 +19,8 @@ import (
const (
maxSeeds = 5
// Subsonic passes the client's count through unbounded, and it ends up as a SQL limit. 500 is
// what the widest caller (similarAlbums, limit*5) legitimately asks for.
// maxSimilarSongs caps the client's count, which Subsonic passes through unbounded and ends up as a SQL
// limit. 500 is what the widest caller (similarAlbums, limit*5) legitimately asks for.
maxSimilarSongs = 500
)

View File

@ -552,7 +552,7 @@ func bitDepthToSampleFmt(bitDepth int) string {
}
}
// Path will always be an absolute path
// createFFmpegCommand expects path to always be an absolute path
func createFFmpegCommand(cmd, path string, maxBitRate, offset int) []string {
var args []string
for _, s := range fixCmd(cmd) {

View File

@ -310,9 +310,9 @@ func (s *maintenanceService) refreshStatsAsync(ctx context.Context, affectedAlbu
})
}
// Wait waits for all background goroutines to complete.
// wait waits for all background goroutines to complete.
// WARNING: This method is ONLY for testing. Never call this in production code.
// Calling Wait() in production will block until ALL background operations complete
// Calling wait() in production will block until ALL background operations complete
// and may cause race conditions with new operations starting.
func (s *maintenanceService) wait() {
s.wg.Wait()

View File

@ -117,7 +117,7 @@ type prometheusMetrics struct {
pluginRequestDuration *prometheus.SummaryVec
}
// Prometheus' metrics requires initialization. But not more than once
// getPrometheusMetrics initializes Prometheus' metrics, which must not happen more than once
var getPrometheusMetrics = sync.OnceValue(func() *prometheusMetrics {
quartilesToEstimate := map[float64]float64{0.5: 0.05, 0.75: 0.025, 0.9: 0.01, 0.99: 0.001}

View File

@ -72,7 +72,7 @@ func (j *Executor) wait() {
_ = j.out.Close()
}
// Path will always be an absolute path
// createMPVCommand expects filename to always be an absolute path
func createMPVCommand(deviceName string, filename string, socketName string) []string {
// Parse the template structure using shell parsing to handle quoted arguments
templateArgs, err := shellquote.Split(conf.Server().MPVCmdTemplate)
@ -102,7 +102,7 @@ func createMPVCommand(deviceName string, filename string, socketName string) []s
return templateArgs
}
// This is a 1:1 copy of the stuff in ffmpeg.go, need to be unified.
// mpvCommand is a 1:1 copy of the stuff in ffmpeg.go, need to be unified.
func mpvCommand() (string, error) {
mpvOnce.Do(func() {
if conf.Server().MPVPath != "" {

View File

@ -76,7 +76,7 @@ func (t *MpvTrack) String() string {
return fmt.Sprintf("Name: %s, Socket: %s", t.MediaFile.Path, t.IPCSocketName)
}
// Used to control the playback volume. A float value between 0.0 and 1.0.
// SetVolume controls the playback volume. A float value between 0.0 and 1.0.
func (t *MpvTrack) SetVolume(value float32) {
// mpv's volume as described in the --volume parameter:
// Set the startup volume. 0 means silence, 100 means no volume reduction or amplification.

View File

@ -29,7 +29,7 @@ func (pd *Queue) String() string {
return fmt.Sprintf("#Items: %d, idx: %d, files: %s", len(pd.Items), pd.Index, filenames.String())
}
// returns the current mediafile or nil
// Current returns the current mediafile or nil
func (pd *Queue) Current() *model.MediaFile {
if pd.Index == -1 {
return nil
@ -42,7 +42,7 @@ func (pd *Queue) Current() *model.MediaFile {
return &pd.Items[pd.Index]
}
// returns the whole queue
// Get returns the whole queue
func (pd *Queue) Get() model.MediaFiles {
return pd.Items
}
@ -55,13 +55,13 @@ func (pd *Queue) IsEmpty() bool {
return len(pd.Items) < 1
}
// set is similar to a clear followed by a add, but will not change the currently playing track.
// Set is similar to a clear followed by an add, but will not change the currently playing track.
func (pd *Queue) Set(items model.MediaFiles) {
pd.Clear()
pd.Items = append(pd.Items, items...)
}
// adding mediafiles to the queue
// Add appends mediafiles to the queue
func (pd *Queue) Add(items model.MediaFiles) {
pd.Items = append(pd.Items, items...)
if pd.Index == -1 && len(pd.Items) > 0 {
@ -69,13 +69,13 @@ func (pd *Queue) Add(items model.MediaFiles) {
}
}
// empties whole queue
// Clear empties the whole queue
func (pd *Queue) Clear() {
pd.Index = -1
pd.Items = nil
}
// idx Zero-based index of the song to skip to or remove.
// Remove removes the song at idx, a zero-based index.
func (pd *Queue) Remove(idx int) {
current := pd.Current()
backupID := ""
@ -119,18 +119,18 @@ func (pd *Queue) getMediaFileIndexByID(id string) (int, error) {
return -1, fmt.Errorf("ID not found in playlist: %s", id)
}
// Sets the index to a new, valid value inside the Items. Values lower than zero are going to be zero,
// values above will be limited by number of items.
// SetIndex sets the index to a new, valid value inside the Items. Values lower than zero are going to be
// zero, values above will be limited by number of items.
func (pd *Queue) SetIndex(idx int) {
pd.Index = max(0, min(idx, len(pd.Items)-1))
}
// Are we at the last track?
// IsAtLastElement reports whether we are at the last track.
func (pd *Queue) IsAtLastElement() bool {
return (pd.Index + 1) >= len(pd.Items)
}
// Goto next index
// IncreaseIndex moves to the next index, unless at the last track.
func (pd *Queue) IncreaseIndex() {
if !pd.IsAtLastElement() {
pd.SetIndex(pd.Index + 1)

View File

@ -19,7 +19,7 @@ import (
const timeout = 10 * time.Minute
// Initiate is unauthenticated, so the number of live requests must be bounded.
// maxPending bounds the number of live requests, because Initiate is unauthenticated.
const maxPending = 1000
var (
@ -197,7 +197,7 @@ func newSecret() string {
return hex.EncodeToString(b)
}
// Users often type the code in groups ("123 456").
// normalizeCode removes whitespace: users often type the code in groups ("123 456").
func normalizeCode(code string) string {
return strings.Join(strings.Fields(code), "")
}

View File

@ -532,7 +532,7 @@ func (p *playTracker) incPlay(ctx context.Context, track *model.MediaFile, times
})
}
// Take this verdict before incPlay mutates what a filter reads, and independently of
// isFilteredOut must take its verdict before incPlay mutates what a filter reads, and independently of
// which scrobblers are active: it can be stored on a session and dispatched much later.
// Any parse or query failure fails open, because filtering must not break scrobbling.
func (p *playTracker) isFilteredOut(ctx context.Context, t *model.MediaFile) bool {

View File

@ -34,8 +34,8 @@ var embedMigrations embed.FS
const migrationsFolder = "migrations"
// sql.Register panics if called twice, so guard it: the singleton instance can be reset
// (tests/benchmarks) and rebuilt, but the driver is process-global and registers only once.
// registerDriverOnce guards sql.Register, which panics if called twice: the singleton instance can be
// reset (tests/benchmarks) and rebuilt, but the driver is process-global and registers only once.
var registerDriverOnce sync.Once
func Db() *sql.DB {

View File

@ -126,9 +126,10 @@ create index folder_parent_id on folder(parent_id);
`)
}
// Use paths from `media_file` table to populate `folder` table. The `folder` table must contain all paths, including
// the ones that do not contain any media_file. We can get all paths from the media_file table to populate a
// fstest.MapFS{}, and then walk the filesystem to insert all folders into the DB, including empty parent ones.
// upSupportNewScanner_PopulateTableFolder uses paths from `media_file` table to populate `folder` table.
// The `folder` table must contain all paths, including the ones that do not contain any media_file. We can
// get all paths from the media_file table to populate a fstest.MapFS{}, and then walk the filesystem to
// insert all folders into the DB, including empty parent ones.
func upSupportNewScanner_PopulateTableFolder(ctx context.Context, tx *sql.Tx) execFunc {
return func() error {
// First, get all folder paths from media_file table

View File

@ -13,10 +13,10 @@ func init() {
goose.AddMigrationContext(upBackfillArtistSearchNormalized, downBackfillArtistSearchNormalized)
}
// The FTS5 migration back-filled artist.search_normalized with a SQL approximation that
// cannot transliterate atomic letters (Ø, æ, ß, ...), and the scanner never rewrote the
// column, leaving artists like "GØGGS" unfindable by ASCII searches. Recompute it in Go;
// the artist_fts update trigger re-indexes every row that changes.
// upBackfillArtistSearchNormalized recomputes artist.search_normalized in Go. The FTS5 migration
// back-filled it with a SQL approximation that cannot transliterate atomic letters (Ø, æ, ß, ...),
// and the scanner never rewrote the column, leaving artists like "GØGGS" unfindable by ASCII
// searches. The artist_fts update trigger re-indexes every row that changes.
func upBackfillArtistSearchNormalized(ctx context.Context, tx *sql.Tx) error {
notice(ctx, tx, "Rebuilding artist search index data. This may take a moment on large libraries.")

View File

@ -11,7 +11,8 @@ import (
"github.com/navidrome/navidrome/log"
)
// Use this in migrations that need to communicate something important (breaking changes, forced reindexes, etc...)
// notice is for migrations that need to communicate something important (breaking changes, forced
// reindexes, etc...)
func notice(ctx context.Context, tx *sql.Tx, msg string) {
if isDBInitialized(ctx, tx) {
line := strings.Repeat("*", len(msg)+8)
@ -19,7 +20,7 @@ func notice(ctx context.Context, tx *sql.Tx, msg string) {
}
}
// Call this in migrations that requires a full rescan
// forceFullRescan is for migrations that require a full rescan
func forceFullRescan(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT OR REPLACE into property (id, value) values ('%s', '1');
@ -64,8 +65,8 @@ func createExecuteFunc(ctx context.Context, tx *sql.Tx) execStmtFunc {
}
}
// Hack way to add a new `not null` column to a table, setting the initial value for existing rows based on a
// SQL expression. It is done in 3 steps:
// createAddColumnFunc is a hack to add a new `not null` column to a table, setting the initial value for
// existing rows based on a SQL expression. It is done in 3 steps:
// 1. Add the column as nullable. Due to the way SQLite manipulates the DDL in memory, we need to add extra padding
// to the default value to avoid truncating it when changing the column to not null
// 2. Update the column with the initial value

View File

@ -144,8 +144,9 @@ func optimizeAt(ctx context.Context, db *sql.DB, now time.Time) error {
return nil
}
// One ANALYZE per index (whole table if WITHOUT ROWID or lacking a non-partial index) yields the
// same sqlite_stat1 rows as a full ANALYZE, but frees the write lock between steps.
// analyzeTargetsSQL picks one ANALYZE target per index (whole table if WITHOUT ROWID or lacking a
// non-partial index). That yields the same sqlite_stat1 rows as a full ANALYZE, but frees the write lock
// between steps.
const analyzeTargetsSQL = `
SELECT i.name FROM sqlite_schema i JOIN pragma_table_list t ON t.schema = 'main' AND t.name = i.tbl_name
WHERE i.type = 'index' AND t.wr = 0 AND EXISTS (SELECT 1 FROM pragma_index_list(t.name) l WHERE l.partial = 0)

View File

@ -117,7 +117,8 @@ const (
ArtworkPriorityBump = 100
)
// Delete* takes the rows to remove; Purge* finds them itself and reports how many went.
// ArtworkRepository stores the artwork images. Delete* takes the rows to remove; Purge* finds them itself
// and reports how many went.
type ArtworkRepository interface {
GetImage(ctx context.Context, hash string) (*Artwork, error)
PutImage(ctx context.Context, a *Artwork) error

View File

@ -1,6 +1,7 @@
package criteria
// Conjunctions need to implement this interface, to allow Criteria to extract child playlist references recursively
// conjunction must be implemented by Conjunctions, to allow Criteria to extract child playlist references
// recursively
type conjunction interface {
ChildPlaylistIds() []string
ChildPlaylistPaths() []string

View File

@ -6,6 +6,7 @@ import (
)
// TODO: Should the type be encoded in the ID?
func GetEntityByID(ctx context.Context, ds DataStore, id string) (any, error) {
entity, _, err := getEntity(ctx, ds, id)
return entity, err

View File

@ -12,22 +12,24 @@ import (
"github.com/navidrome/navidrome/utils/str"
)
// support the standard [mm:ss.mm], as well as [hh:*] and [*.mmm]
// timeRegexString supports the standard [mm:ss.mm], as well as [hh:*] and [*.mmm]
const timeRegexString = `\[([0-9]{1,2}:)?([0-9]{1,2}):([0-9]{1,2})(\.[0-9]{1,3})?\]`
var (
// Should either be at the beginning of file, or beginning of line
// syncRegex only matches at the beginning of file, or beginning of line
syncRegex = regexp.MustCompile(`(^|\n)\s*` + timeRegexString)
timeRegex = regexp.MustCompile(timeRegexString)
lrcIdRegex = regexp.MustCompile(`\[(ar|ti|offset|lang):([^]]+)]`)
// Non-standard background-vocal tag: [bg: <mm:ss.mm>word...] attaches to the preceding line
// bgTagRegex matches the non-standard background-vocal tag: [bg: <mm:ss.mm>word...] attaches to the
// preceding line
bgTagRegex = regexp.MustCompile(`^\[bg:(.*)]$`)
// Any other [name:value] line is a tag we don't support (e.g. [al:], [by:]) and must be skipped whole
// unknownTagRegex matches any other [name:value] line, a tag we don't support (e.g. [al:], [by:]) that
// must be skipped whole
unknownTagRegex = regexp.MustCompile(`^\[[A-Za-z][^]:]*:[^]]*]`)
// Enhanced LRC: inline word-level timing markers like <00:12.34>
// enhancedLRCTimeString matches Enhanced LRC inline word-level timing markers like <00:12.34>
enhancedLRCTimeString = `<([0-9]{1,2}:)?([0-9]{1,2}):([0-9]{1,2})(\.[0-9]{1,3})?>`
enhancedLRCRegex = regexp.MustCompile(enhancedLRCTimeString)
)

View File

@ -141,7 +141,7 @@ func nullableFloat(value string) *float64 {
return &v
}
// Used for tracks and discs
// tuple is used for tracks and discs
func (md Metadata) tuple(key model.TagName) (int, int) {
tag := md.first(key)
if tag == "" {
@ -170,7 +170,7 @@ func (md Metadata) date(tagName model.TagName) Date {
return Date(md.first(tagName))
}
// date tries to parse a date from a tag, it tries to get at least the year. See the tests for examples.
// parseDate tries to parse a date from a tag, it tries to get at least the year. See the tests for examples.
func parseDate(filePath string, tagName model.TagName, tagValue string) string {
if len(tagValue) < 4 {
return ""

View File

@ -121,6 +121,7 @@ func (md Metadata) albumID(mf model.MediaFile, pidConf string) string {
}
// BFR Must be configurable?
func (md Metadata) artistID(name string) string {
mf := model.MediaFile{AlbumArtist: name}
return computePID(mf, md, "albumartistid", "", false, id.NewHash)

View File

@ -198,7 +198,8 @@ func normalizeChildPathRule(rule map[string]any, referencingPlaylistPath string)
return normalized
}
// filepath.IsAbs rejects a bare leading separator on Windows, but that is how Unix spells absolute.
// isAbsPlaylistRef also accepts a bare leading separator: filepath.IsAbs rejects it on Windows, but that is
// how Unix spells absolute.
func isAbsPlaylistRef(path string) bool {
return filepath.IsAbs(path) || os.IsPathSeparator(path[0])
}

View File

@ -224,6 +224,7 @@ func (r *albumRepository) Put(ctx context.Context, al *model.Album) error {
}
// TODO Move external metadata to a separated table
func (r *albumRepository) UpdateExternalInfo(ctx context.Context, al *model.Album) error {
_, err := r.put(ctx, al.ID, &dbAlbum{Album: al}, "description", "small_image_url", "medium_image_url", "large_image_url", "external_url", "external_info_updated_at")
return err

View File

@ -12,8 +12,8 @@ import (
"github.com/pocketbase/dbx"
)
// Keeps the id IN-list under SQLite's bound-parameter limit; a whole multiple of artworkBatchSize
// so a page re-chunks into even hydration batches.
// artworkChunkSize keeps the id IN-list under SQLite's bound-parameter limit; a whole multiple of
// artworkBatchSize so a page re-chunks into even hydration batches.
const artworkChunkSize = artworkBatchSize * 3
// streamByIDs yields rows in id chunks through the caller's hydrating fetch. Resolving ids first

View File

@ -14,11 +14,11 @@ import (
"github.com/pocketbase/dbx"
)
// Keeps each multi-row insert under SQLite's bind-variable limit (at most 7 vars per row).
// enqueueChunkSize keeps each multi-row insert under SQLite's bind-variable limit (at most 7 vars per row).
const enqueueChunkSize = 100
// Every insert writes these, in this order; the INSERT..SELECT forms must project them to match.
// DequeueBatch also selects exactly these, to leave the drain's rows free of the trace it never reads.
// enqueueColumns are written by every insert, in this order; the INSERT..SELECT forms must project them to
// match. DequeueBatch also selects exactly these, to leave the drain's rows free of the trace it never reads.
var enqueueColumns = []string{"item_kind", "item_id", "image_type", "priority", "attempts", "retry_at", "enqueued_at"}
type artworkQueueRepository struct {
@ -92,7 +92,8 @@ func (r *artworkQueueRepository) EnqueueIfMissing(ctx context.Context, items ...
return nil
}
// DO NOTHING is deliberate: a recheck must not bump the priority or retry_at of an already-queued item.
// skipIfQueued uses DO NOTHING on purpose: a recheck must not bump the priority or retry_at of an
// already-queued item.
const skipIfQueued = ` ON CONFLICT (item_kind, item_id, image_type) DO NOTHING`
// insertIfNotQueued inserts the rows selected by the given SQL, optionally prefixed by a CTE.

View File

@ -378,7 +378,7 @@ func (c smartPlaylistCriteria) inList(values map[string]any, negate bool) (squir
return squirrel.Expr("media_file.id IN ("+subSQL+")", subArgs...), nil
}
// Filesystems disagree on the Unicode form of a name, so match the path in NFC and NFD.
// pathVariants returns the path in NFC and NFD, because filesystems disagree on the Unicode form of a name.
func pathVariants(path string) []string {
variants := []string{path}
if alt := norm.NFC.String(path); alt != path {

View File

@ -93,7 +93,7 @@ func naturalSort(col string) string {
return fmt.Sprintf("(%s collate %s)", col, db.NaturalCollation)
}
// Convert the order_* columns to a collated sort expression, falling back to the
// mapSortOrder converts the order_* columns to a collated sort expression, falling back to the
// sort_* column when those are preferred. Example:
// order_album_name -> (coalesce(nullif(sort_album_name,”),order_album_name) collate nocase)
// It finds order column names anywhere in the substring

View File

@ -133,8 +133,8 @@ ON CONFLICT (user_id, library_id) DO NOTHING;`,
return nil
}
// StoreMusicFolder is a temporary method to store the music folder path from the config in the DB
// TODO Remove this method when we have a proper UI to add libraries
// This is a temporary method to store the music folder path from the config in the DB
func (r *libraryRepository) StoreMusicFolder(ctx context.Context) error {
changed := And{Eq{"id": model.DefaultLibraryID}, NotEq{"path": conf.Server().MusicFolder}}
// An UPDATE takes the write lock even when nothing matches, and a startup scan may be holding it

View File

@ -39,7 +39,8 @@ type SQLStore struct {
artworkQueue func() model.ArtworkQueueRepository
}
// Repositories are built on first use, so a transaction store only pays for the ones its block touches.
// newSQLStore builds repositories on first use, so a transaction store only pays for the ones its block
// touches.
func newSQLStore(db dbx.Builder) *SQLStore {
return &SQLStore{
db: db,

View File

@ -191,7 +191,8 @@ func (r *playerRepository) Delete(ctx context.Context, ids ...string) error {
return r.deleteOwnedAll(ctx, ids...)
}
// Keys are long random strings, not user-chosen passwords, so a fast unsalted hash is enough and keeps lookups indexed.
// hashAPIKey uses a fast unsalted hash: keys are long random strings, not user-chosen passwords, so that is
// enough and keeps lookups indexed.
func hashAPIKey(key string) string {
sum := sha256.Sum256([]byte(key))
return hex.EncodeToString(sum[:])

View File

@ -23,7 +23,8 @@ func (r *playlistRepository) refreshSmartPlaylist(ctx context.Context, pls *mode
return r.refreshSmartPlaylistTree(ctx, pls, map[string]struct{}{})
}
// The visited set stops playlists that reference each other from recursing forever.
// refreshSmartPlaylistTree uses the visited set to stop playlists that reference each other from
// recursing forever.
func (r *playlistRepository) refreshSmartPlaylistTree(ctx context.Context, pls *model.Playlist, visited map[string]struct{}) bool {
if _, seen := visited[pls.ID]; seen {
log.Trace(ctx, "Skipping already visited smart playlist", "playlist", pls.Name, "id", pls.ID)

View File

@ -169,6 +169,7 @@ func (r sqlRepository) applyOptions(sq SelectBuilder, options ...model.QueryOpti
}
// TODO Change all sortMappings to have a consistent case
func (r sqlRepository) sortMapping(sort string) string {
if mapping, _, ok := r.lookupSortMapping(sort); ok {
return mapping

View File

@ -12,7 +12,7 @@ import (
"github.com/pocketbase/dbx"
)
// Format of a tag in the DB
// dbTag is the format of a tag in the DB
type dbTag struct {
ID string `json:"id"`
Value string `json:"value"`

View File

@ -449,7 +449,7 @@ func (r *userRepository) initPasswordEncryptionKey(ctx context.Context) error {
return nil
}
// encrypts u.NewPassword
// encryptPassword encrypts u.NewPassword
func (r *userRepository) encryptPassword(ctx context.Context, u *model.User) error {
encPassword, err := utils.Encrypt(ctx, encKey, u.NewPassword)
if err != nil {
@ -460,7 +460,7 @@ func (r *userRepository) encryptPassword(ctx context.Context, u *model.User) err
return nil
}
// decrypts u.Password
// decryptPassword decrypts u.Password
func (r *userRepository) decryptPassword(ctx context.Context, u *model.User) error {
plaintext, err := utils.Decrypt(ctx, encKey, u.Password)
if err != nil {

View File

@ -310,7 +310,7 @@ func isDirReadable(ctx context.Context, fsys fs.FS, dirPath string) bool {
return true
}
// List of special directories to ignore
// ignoredDirs lists special directories to ignore
var ignoredDirs = []string{
"$RECYCLE.BIN",
"#snapshot",

View File

@ -67,7 +67,8 @@ func problemRecoverer(next http.Handler) http.Handler {
var routableMethods = []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete}
// Looks routes up on mux itself: chi's RouteContext().Routes points at the parent router when mounted.
// allowedMethods looks routes up on mux itself: chi's RouteContext().Routes points at the parent router
// when mounted.
func allowedMethods(mux chi.Routes, req *http.Request) []string {
path := routePath(req)
var allowed []string

View File

@ -24,7 +24,8 @@ type Broker interface {
const (
keepAliveFrequency = 15 * time.Second
// The timeout must be higher than the keepAliveFrequency, or the lack of activity will cause the channel to close.
// writeTimeOut must be higher than the keepAliveFrequency, or the lack of activity will cause the channel
// to close.
writeTimeOut = keepAliveFrequency + 5*time.Second
bufferSize = 1
)

View File

@ -14,7 +14,8 @@ import (
"github.com/navidrome/navidrome/model/id"
)
// Keeps reads out of the transaction: SQLite fails a write that follows a read at once, without waiting for the lock
// initialSetup keeps reads out of the transaction: SQLite fails a write that follows a read at once,
// without waiting for the lock
func initialSetup(ctx context.Context, ds model.DataStore) error {
if err := ds.Library().StoreMusicFolder(ctx); err != nil {
return err
@ -33,7 +34,7 @@ func initialSetup(ctx context.Context, ds model.DataStore) error {
}, "initial setup")
}
// If the Dev Admin user is not present, create it
// createInitialAdminUser creates the Dev Admin user if it is not present
func createInitialAdminUser(ctx context.Context, ds model.DataStore, initialPassword string) error {
users := ds.User()
c, err := users.CountAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"user_name": consts.DevInitialUserName}})

View File

@ -89,7 +89,8 @@ func (d *Discovery) ServeOn(ctx context.Context, conn net.PacketConn) {
}
}
// Behind a unix socket nothing listens on Port, so only a BaseURL host gives clients an address.
// hasAdvertisableAddress is false behind a unix socket with no BaseURL host: nothing listens on Port
// there, so only a BaseURL host gives clients an address.
func hasAdvertisableAddress() bool {
return conf.Server().BaseHost != "" || !strings.HasPrefix(conf.Server().Address, "unix:")
}
@ -100,7 +101,8 @@ func discoveryAddress(ctx context.Context, remote net.Addr) string {
return publicurl.AbsoluteURL(request.WithServerAddress(ctx, scheme, host), consts.URLPathJellyfinAPI, nil)
}
// On a multi-homed host, only the interface that routes to the requester is reachable by it.
// localIPFor returns the configured Address when it is a specific IP. Otherwise it picks the interface that
// routes to the requester, since on a multi-homed host only that one is reachable by it.
func localIPFor(remote net.Addr) string {
if ip := parseIP(conf.Server().Address); ip.IsValid() && !ip.IsUnspecified() {
return ip.String()

View File

@ -21,7 +21,7 @@ func sortName(sortTag, orderName, displayName string) string {
return cmp.Or(orderName, displayName)
}
// Jellyfin wire times are ticks: 100ns units, i.e. 10,000 per millisecond.
// ticksPerMillis converts Jellyfin wire times, which are ticks: 100ns units, i.e. 10,000 per millisecond.
const ticksPerMillis = 10_000
func TicksFromSeconds(sec float32) int64 { return int64(float64(sec) * 1000 * ticksPerMillis) }
@ -56,7 +56,7 @@ func premiereDate(date string, year int) *string {
return &s
}
// Dates use .NET's round-trip layout, 7 fractional digits and all: Manet rejects plain RFC3339.
// jellyfinDateLayout is .NET's round-trip layout, 7 fractional digits and all: Manet rejects plain RFC3339.
const jellyfinDateLayout = "2006-01-02T15:04:05.0000000Z07:00"
// JellyfinDate formats t as the date string clients expect, or "" for the zero time so the

View File

@ -371,8 +371,9 @@ func (api *Router) movePlaylistItem(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
// Clients probe these before offering edits. Navidrome has no per-playlist ACL, so CanEdit carries
// only editability; ownership is enforced on write, and a lookup error 404s to prevent probing.
// getPlaylistUsers answers the probe clients make before offering edits. Navidrome has no per-playlist
// ACL, so CanEdit carries only editability; ownership is enforced on write, and a lookup error 404s to
// prevent probing.
func (api *Router) getPlaylistUsers(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id, ok := itemIDParam(w, r, "playlistId")

View File

@ -27,7 +27,8 @@ func (api *Router) quickConnectEnabled(w http.ResponseWriter, r *http.Request) {
api.ok(w, r, conf.Server().Jellyfin.QuickConnect)
}
// Initiate is unauthenticated and its fields are kept for minutes, so their size must be bounded.
// maxQuickConnectField bounds the field size: Initiate is unauthenticated and its fields are kept for
// minutes.
const maxQuickConnectField = 512
func (api *Router) quickConnectInitiate(w http.ResponseWriter, r *http.Request) {

View File

@ -23,8 +23,8 @@ var similarWait = 10 * time.Second
const (
defaultSimilarLimit = 20
maxSimilarLimit = 100
// A mix is a playback queue, not a "related items" list: Finamp's Radio Mix asks for 250, so the
// Similar ceiling would truncate it. Real Jellyfin builds mixes from a 200-track genre query.
// maxInstantMixLimit is above the Similar ceiling: a mix is a playback queue, not a "related items"
// list, and Finamp's Radio Mix asks for 250. Real Jellyfin builds mixes from a 200-track genre query.
maxInstantMixLimit = 500
)

View File

@ -36,11 +36,12 @@ func (api *Router) serverID(ctx context.Context) string {
return resolveServerID(ctx, api.ds, &api.serverIDVal)
}
// Package-level: the Router and Discovery are separate objects and must not persist different ids.
// serverIDMu is package-level: the Router and Discovery are separate objects and must not persist
// different ids.
var serverIDMu sync.Mutex
// Clients cache ServerId across sessions, so it is persisted. Only a successful read or write is
// cached: a transient failure yields a temporary id and retries on the next call.
// resolveServerID persists the ServerId, because clients cache it across sessions. Only a successful read
// or write is cached: a transient failure yields a temporary id and retries on the next call.
func resolveServerID(ctx context.Context, ds model.DataStore, cached *string) string {
serverIDMu.Lock()
defer serverIDMu.Unlock()

View File

@ -12,7 +12,7 @@ import (
"github.com/navidrome/navidrome/model"
)
// User-library association endpoints (admin only)
// addUserLibraryRoute adds the user-library association endpoints (admin only)
func (api *Router) addUserLibraryRoute(r chi.Router) {
r.Route("/user/{id}/library", func(r chi.Router) {
r.Use(parseUserIDMiddleware)
@ -23,7 +23,7 @@ func (api *Router) addUserLibraryRoute(r chi.Router) {
type userIDKey struct{}
// Middleware to parse user ID from URL
// parseUserIDMiddleware parses the user ID from the URL
func parseUserIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "id")

View File

@ -247,7 +247,7 @@ func (api *Router) addInsightsRoute(r chi.Router) {
})
}
// Middleware to ensure only admin users can access endpoints
// adminOnlyMiddleware ensures only admin users can access endpoints
func adminOnlyMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := request.UserFrom(r.Context())

View File

@ -41,7 +41,7 @@ func (api *Router) rescanPlugins(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
// Middleware to check if plugins feature is enabled
// pluginsEnabledMiddleware checks if the plugins feature is enabled
func pluginsEnabledMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !conf.Server().Plugins.Enabled {

View File

@ -29,7 +29,7 @@ func IndexWithShare(ds model.DataStore, fs fs.FS, shareInfo *model.Share) http.H
return serveIndex(ds, fs, shareInfo)
}
// Injects the config in the `index.html` template
// serveIndex injects the config in the `index.html` template
func serveIndex(ds model.DataStore, fs fs.FS, shareInfo *model.Share) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c, err := ds.User().CountAll(r.Context())

View File

@ -222,7 +222,7 @@ func (s *Server) mountAuthenticationRoutes() chi.Router {
})
}
// Serve UI app assets
// mountRootRedirector redirects the root path to the UI app
func (s *Server) mountRootRedirector() {
r := s.router
// Redirect root to UI URL

View File

@ -239,14 +239,14 @@ func (api *Router) routes() http.Handler {
return r
}
// Add a Subsonic handler
// h adds a Subsonic handler
func h(r chi.Router, path string, f handler) {
hr(r, path, func(_ http.ResponseWriter, r *http.Request) (*responses.Subsonic, error) {
return f(r)
})
}
// Add a Subsonic handler that requires an http.ResponseWriter (ex: stream, getCoverArt...)
// hr adds a Subsonic handler that requires an http.ResponseWriter (ex: stream, getCoverArt...)
func hr(r chi.Router, path string, f handlerRaw) {
handle := func(w http.ResponseWriter, r *http.Request) {
res, err := f(w, r)
@ -267,7 +267,8 @@ func hr(r chi.Router, path string, f handlerRaw) {
addHandler(r, path, handle)
}
// Add a handler that returns 501 - Not implemented. Used to signal that an endpoint is not implemented yet
// h501 adds a handler that returns 501 - Not implemented. Used to signal that an endpoint is not
// implemented yet
func h501(r chi.Router, paths ...string) {
for _, path := range paths {
handle := func(w http.ResponseWriter, r *http.Request) {
@ -279,7 +280,7 @@ func h501(r chi.Router, paths ...string) {
}
}
// Add a handler that returns 410 - Gone. Used to signal that an endpoint will not be implemented
// h410 adds a handler that returns 410 - Gone. Used to signal that an endpoint will not be implemented
func h410(r chi.Router, paths ...string) {
for _, path := range paths {
handle := func(w http.ResponseWriter, r *http.Request) {

View File

@ -170,7 +170,7 @@ func (r *clientInfoRequest) validate() error {
return nil
}
// Only support songs for now
// validMediaTypes only supports songs for now
var validMediaTypes = []string{
"song",
}

View File

@ -23,7 +23,8 @@ func StubResolver(records map[string]string) *net.Resolver {
}
}
// net.Pipe is not a PacketConn, so the resolver sends one query framed with a 2-byte length prefix.
// serveStubDNS answers one query. net.Pipe is not a PacketConn, so the resolver sends it framed with a
// 2-byte length prefix.
func serveStubDNS(conn net.Conn, records map[string]string) {
defer conn.Close()
var size [2]byte

View File

@ -307,6 +307,7 @@ func (m *MockMediaFileRepo) DeleteAllMissing(_ context.Context) (int64, error) {
}
// REST repository methods
func (m *MockMediaFileRepo) Count(ctx context.Context, _ ...rest.QueryOptions) (int64, error) {
return m.CountAll(ctx)
}
@ -331,6 +332,7 @@ func (m *MockMediaFileRepo) Search(ctx context.Context, q string, options ...mod
}
// Cross-library move detection mock methods
func (m *MockMediaFileRepo) FindRecentFilesByMBZTrackID(_ context.Context, missing model.MediaFile, since time.Time) (model.MediaFiles, error) {
if m.Err {
return nil, errors.New("error")

View File

@ -151,6 +151,7 @@ func (m *MockPluginRepo) CountAll(_ context.Context, qo ...model.QueryOptions) (
}
// REST repository methods
func (m *MockPluginRepo) Count(_ context.Context, _ ...rest.QueryOptions) (int64, error) {
if !m.Permitted {
return 0, rest.ErrPermissionDenied

View File

@ -142,7 +142,7 @@ func LinesFrom(reader io.Reader) iter.Seq[string] {
}
}
// From https://stackoverflow.com/a/41433698
// scanLines is based on https://stackoverflow.com/a/41433698
func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil