package plan
import (
"errors"
"fmt"
"path/filepath"
"sort"
"strings"
"intake/internal/normalize"
"intake/internal/scan"
"intake/internal/sheet"
"intake/internal/tags"
)
type Issue struct {
Hard bool
Text string
}
type TrackPlan struct {
Source string
Title string
Artist string
Disc int
Number int
Target string
Ext string
Duration float64
Original string
Truncated bool
Tags []tags.Note
}
type Plan struct {
Album scan.Album
AlbumName string
AlbumTag string
AlbumArt string
CreditFromTags string
Artist string
Year string
VariousArt bool
AlbumDir string
ArtistDir string
ArchiveDir string
LibraryDir string
ArchiveRoot string
LibraryRoot string
// DiscPrefix and Width are the naming shape the plan was built with. An
// edit has to keep it: recomputing the padding from the tracks that are left
// would silently rename every file in an album whose highest-numbered track
// was just deleted.
DiscPrefix string
Width int
Tracks []TrackPlan
Issues []Issue
Dropped []string
Warnings []string
}
func (p Plan) Blocked() bool {
for _, i := range p.Issues {
if i.Hard {
return true
}
}
return false
}
const (
variousArtists = "Various Artists"
specialVA = "various-artists"
)
type resolved struct {
title string
disc int
track int
artist string
src string
orig string
dur float64
}
type DirKey struct {
Dir string
Credit string
Source string
}
// maxNameBytes is the longest name intake writes for a file or a directory.
// Filesystems cap a single path component at 255 bytes, and the archive is built
// inside a temporary directory whose name is the target's with a prefix and a
// random suffix, so the target has to leave room for that.
const maxNameBytes = 200
func Build(a scan.Album, archiveRoot, libraryRoot string, artistKey DirKey, discPrefix string) Plan {
p := Plan{Album: a, ArchiveRoot: archiveRoot, LibraryRoot: libraryRoot}
if len(a.Tracks) == 0 {
p.Issues = append(p.Issues, Issue{Hard: true, Text: "no readable audio tracks"})
return p
}
albumName, albumNameOK := commonValue(a, tags.FieldAlbum)
albumArtist, albumArtistOK := commonValue(a, tags.FieldAlbumArtist)
artist, artistOK := commonValue(a, tags.FieldArtist)
yearRaw, _ := commonValue(a, tags.FieldDate)
// Tracks that disagree on an album-level value are treated as not having
// agreed at all, but one mistagged track out of fifteen should not stop the
// album: a clear majority is used, and said out loud.
if !albumNameOK {
if v, n, total := dominantValue(a, tags.FieldAlbum); n*2 > total {
albumName, albumNameOK = v, true
p.Warnings = append(p.Warnings, fmt.Sprintf("tracks disagree on ALBUM; %d of %d say %q, using that", n, total, v))
}
}
if !albumArtistOK {
if v, n, total := dominantValue(a, tags.FieldAlbumArtist); n*2 > total {
albumArtist, albumArtistOK = v, true
p.Warnings = append(p.Warnings, fmt.Sprintf("tracks disagree on ALBUMARTIST; %d of %d say %q, using that", n, total, v))
}
}
if !albumArtistOK {
switch {
case artistOK:
albumArtist = artist
p.Warnings = append(p.Warnings, fmt.Sprintf("no ALBUMARTIST tag; using ARTIST %q", artist))
default:
if dominant, n, total := dominantArtist(a); n*2 > total {
albumArtist = dominant
p.Warnings = append(p.Warnings, fmt.Sprintf("no ALBUMARTIST tag and the artists differ; %d of %d tracks credit %q, using that", n, total, dominant))
} else if inferred, _, ok := splitDirName(a.Name); ok {
albumArtist = inferred
p.Warnings = append(p.Warnings, fmt.Sprintf("no artist tags at all; inferred artist %q from the directory name", inferred))
}
}
}
if !albumNameOK {
if _, inferred, ok := splitDirName(a.Name); ok {
albumName = inferred
p.Warnings = append(p.Warnings, fmt.Sprintf("no ALBUM tag; inferred %q from the directory name", inferred))
}
}
// Only when nothing above found an album artist does differing per-track
// artists mean a compilation. An album with guest tracks still has one album
// artist, and that is what ALBUMARTIST is for.
if strings.TrimSpace(albumArtist) == "" && differingArtists(a) {
p.VariousArt = true
albumArtist = variousArtists
p.Warnings = append(p.Warnings, "per-track artists differ and there is no album artist; filing under various-artists")
}
if strings.TrimSpace(albumArtist) == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: "album artist is unknown: no ALBUMARTIST/ARTIST tag and the directory name gives no hint"})
}
if strings.TrimSpace(albumName) == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: "album name is unknown: no ALBUM tag and the directory name gives no hint"})
}
// The archive holds lossless masters: every file intake writes is FLAC, and
// the tagging and artwork tools it drives are FLAC tools. A lossy source is a
// design decision rather than a half-working fallback, so it is refused here
// with something the user can act on, instead of failing much later inside
// metaflac with "does not appear to be a FLAC file".
notFLAC := map[string]bool{}
for _, t := range a.Tracks {
if ext := strings.ToLower(filepath.Ext(t.Path)); ext != ".flac" {
notFLAC[strings.TrimPrefix(ext, ".")] = true
}
}
if len(notFLAC) > 0 {
kinds := make([]string, 0, len(notFLAC))
for k := range notFLAC {
kinds = append(kinds, k)
}
sort.Strings(kinds)
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("the archive holds flac only, and this album contains %s; convert it to flac first, or file it by hand", strings.Join(kinds, ", "))})
}
// One audio file beside a cue sheet is usually a whole album the cue
// describes as many tracks. intake does not split on cue sheets, so filing it
// silently would leave the user with an album whose track list is wrong.
if len(a.Tracks) == 1 && a.Dir != "" {
if cues, _ := filepath.Glob(filepath.Join(a.Dir, "*.cue")); len(cues) > 0 {
p.Warnings = append(p.Warnings, fmt.Sprintf("a cue sheet is present (%s) and there is only one audio file; intake does not split on cue sheets, so this will be filed as a single track", filepath.Base(cues[0])))
}
}
p.AlbumName = albumName
p.AlbumTag = albumName
p.AlbumArt = albumArtist
p.CreditFromTags = albumArtist
p.Year = tags.NormalizeYear(yearRaw)
if yearRaw != "" && p.Year == "" {
p.Warnings = append(p.Warnings, fmt.Sprintf("could not read a year from DATE=%q", yearRaw))
}
dropped := map[string]bool{}
for _, t := range a.Tracks {
for _, d := range tags.Dropped(t.Tags) {
dropped[d] = true
}
}
for d := range dropped {
p.Dropped = append(p.Dropped, d)
}
sort.Strings(p.Dropped)
var items []resolved
maxTrack := 0
missingNumbers := 0
for _, t := range a.Tracks {
base := filepath.Base(t.Path)
fDisc, fTrack, fTitle := scan.FromFilename(base)
title, ok := tags.Get(t.Tags, tags.FieldTitle)
if !ok || strings.TrimSpace(title) == "" {
title = fTitle
if title != "" {
p.Warnings = append(p.Warnings, fmt.Sprintf("%s: no TITLE tag; using the file name %q", base, title))
}
}
original := title
num := 0
if v, ok := tags.Get(t.Tags, tags.FieldTrackNumber); ok {
fmt.Sscanf(strings.TrimSpace(v), "%d", &num)
}
if num == 0 && fTrack > 0 {
num = fTrack
p.Warnings = append(p.Warnings, fmt.Sprintf("%s: no TRACKNUMBER tag; inferring track %d from the file name", base, num))
}
if num == 0 {
missingNumbers++
}
disc := 0
if v, ok := tags.Get(t.Tags, tags.FieldDiscNumber); ok {
fmt.Sscanf(strings.TrimSpace(v), "%d", &disc)
}
if disc == 0 && fDisc > 0 {
disc = fDisc
}
if disc == 0 && t.DiscHint > 0 {
// Last resort, and only when the tags and the file name both said
// nothing: the folder the file sits in, for rips arranged as CD1,
// CD2 with no disc tags at all.
disc = t.DiscHint
}
if disc == 0 {
disc = 1
}
trArtist, _ := tags.Get(t.Tags, tags.FieldArtist)
if strings.TrimSpace(trArtist) == "" {
trArtist = albumArtist
}
if num > maxTrack {
maxTrack = num
}
if strings.TrimSpace(title) == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("%s: no usable title (tag and file name are empty)", base)})
}
items = append(items, resolved{title: title, disc: disc, track: num, artist: trArtist, src: t.Path, orig: original, dur: t.Duration})
}
if missingNumbers > 0 {
p.Warnings = append(p.Warnings, fmt.Sprintf("%d track(s) have no track number; they will be numbered in file order", missingNumbers))
used := map[int]bool{}
for _, it := range items {
if it.track > 0 {
used[it.track] = true
}
}
next := 1
for i := range items {
if items[i].track != 0 {
continue
}
for used[next] {
next++
}
items[i].track = next
used[next] = true
next++
}
for _, it := range items {
if it.track > maxTrack {
maxTrack = it.track
}
}
}
width := normalize.PadWidth(maxTrack)
p.Width = width
p.DiscPrefix = discPrefix
tracksOnDisc := map[int]int{}
for _, it := range items {
tracksOnDisc[it.disc]++
}
discTotal := len(tracksOnDisc)
withDisc := useDiscPrefix(discPrefix, discTotal)
if !withDisc && discTotal > 1 {
p.Warnings = append(p.Warnings, fmt.Sprintf("disc_prefix is %q but this album has %d discs, so tracks on different discs will share numbers", discPrefix, discTotal))
}
var pairs, bySource [][2]string
for _, it := range items {
target := normalize.TrackFile(it.disc, it.track, width, it.title, filepath.Ext(it.src), withDisc)
pairs = append(pairs, [2]string{it.orig, target})
bySource = append(bySource, [2]string{filepath.Base(it.src), target})
}
noteCollisions(&p, pairs, bySource)
for _, it := range items {
name := normalize.TrackFile(it.disc, it.track, width, it.title, filepath.Ext(it.src), withDisc)
truncated := false
if n, cut := normalize.Truncate(name, maxNameBytes); cut {
p.Warnings = append(p.Warnings, fmt.Sprintf("target name was too long and has been shortened: %s -> %s", name, n))
name, truncated = n, true
}
tp := TrackPlan{
Source: it.src,
Title: it.title,
Artist: it.artist,
Disc: it.disc,
Number: it.track,
Target: name,
Ext: filepath.Ext(it.src),
Duration: it.dur,
Original: it.orig,
Truncated: truncated,
}
trackTotal := tracksOnDisc[it.disc]
tp.Tags = []tags.Note{
{Field: tags.FieldTrackNumber, Value: fmt.Sprintf("%d", it.track)},
{Field: tags.FieldTrackTotal, Value: fmt.Sprintf("%d", trackTotal)},
{Field: tags.FieldLegacyTrackTotal, Value: fmt.Sprintf("%d", trackTotal)},
{Field: tags.FieldDiscNumber, Value: fmt.Sprintf("%d", it.disc)},
{Field: tags.FieldDiscTotal, Value: fmt.Sprintf("%d", discTotal)},
{Field: tags.FieldLegacyDiscTotal, Value: fmt.Sprintf("%d", discTotal)},
{Field: tags.FieldTitle, Value: strings.TrimSpace(it.title)},
{Field: tags.FieldAlbum, Value: strings.TrimSpace(albumName)},
{Field: tags.FieldArtist, Value: strings.TrimSpace(it.artist)},
{Field: tags.FieldAlbumArtist, Value: strings.TrimSpace(albumArtist)},
}
if p.Year != "" {
tp.Tags = append(tp.Tags, tags.Note{Field: tags.FieldDate, Value: p.Year})
}
p.Tracks = append(p.Tracks, tp)
}
albumDir := normalize.DirName(p.AlbumName)
if albumDir == "" {
albumDir = normalize.Name(p.AlbumName)
}
if short, cut := normalize.Truncate(albumDir, maxNameBytes); cut {
p.Warnings = append(p.Warnings, fmt.Sprintf("album folder name was too long and has been shortened: %s -> %s", albumDir, short))
albumDir = short
}
if albumDir == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("album name %q has no ASCII folder name; open the editor to supply one", p.AlbumName)})
}
p.AlbumDir = albumDir
artistDir := artistKey.Dir
if artistDir == "" {
artistDir = normalize.DirName(p.AlbumArt)
}
if short, cut := normalize.Truncate(artistDir, maxNameBytes); cut {
p.Warnings = append(p.Warnings, fmt.Sprintf("artist folder name was too long and has been shortened: %s -> %s", artistDir, short))
artistDir = short
}
p.ArtistDir = artistDir
if artistDir == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("album artist %q has no ASCII folder name; open the editor to supply one", p.AlbumArt)})
}
if artistDir != "" && albumDir != "" {
p.ArchiveDir = filepath.Join(archiveRoot, artistDir, albumDir)
p.LibraryDir = filepath.Join(libraryRoot, artistDir, albumDir)
}
return p
}
func quoteAll(in []string) []string {
out := make([]string, 0, len(in))
for _, s := range in {
out = append(out, fmt.Sprintf("%q", s))
}
return out
}
func splitDirName(dir string) (artist, album string, ok bool) {
name := strings.TrimSpace(dir)
for _, open := range []string{"[", "("} {
if i := strings.Index(name, open); i > 0 {
closeCh := map[string]string{"[": "]", "(": ")"}[open]
if j := strings.Index(name, closeCh); j > i && strings.TrimSpace(name[j+1:]) == "" {
name = strings.TrimSpace(name[:i])
}
}
}
name = strings.TrimSpace(strings.TrimSuffix(name, "- flac"))
name = strings.TrimSpace(strings.TrimSuffix(name, "- FLAC"))
name = strings.TrimSpace(name)
if name == "" {
return "", "", false
}
if a, rest, found := strings.Cut(name, " - "); found {
a, rest = strings.TrimSpace(a), strings.TrimSpace(rest)
if a != "" && rest != "" {
return a, rest, true
}
}
return "", "", false
}
// noteCollisions records the names in a plan that cannot coexist.
//
// The first kind is two different titles collapsing to the same normalised text,
// which is worth stopping for because the title is the only human-readable part
// of a file name. The second is two tracks whose whole target is the same string,
// which the first check cannot see when they also share a track number, because
// it groups by title and folds repeats of a title together. That one is not a
// naming nuisance but a lost track: the copy truncates and replaces, so the album
// is filed one track short and every later check still passes.
func noteCollisions(p *Plan, titles, sources [][2]string) {
for _, c := range normalize.DetectCollisions(titles) {
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("two different titles normalise to the same name %q (from %s); rename one before continuing",
c.Target, strings.Join(quoteAll(c.Causes), " and "))})
}
for _, c := range normalize.TargetClashes(sources) {
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("%s would be written twice, from %s; give the tracks different numbers or titles, in their tags or in the staged file names",
c.Target, strings.Join(quoteAll(c.Causes), " and "))})
}
}
// titlePairs and sourcePairs are the two views noteCollisions needs: what the
// tracks are called, and which files they came from.
func titlePairs(tracks []TrackPlan) [][2]string {
out := make([][2]string, 0, len(tracks))
for _, t := range tracks {
out = append(out, [2]string{t.Title, t.Target})
}
return out
}
func sourcePairs(tracks []TrackPlan) [][2]string {
out := make([][2]string, 0, len(tracks))
for _, t := range tracks {
out = append(out, [2]string{filepath.Base(t.Source), t.Target})
}
return out
}
// Sheet returns the editable description of this plan: everything intake is
// about to write, in a form a person can change in $EDITOR.
func (p Plan) Sheet() sheet.Sheet {
tracks := make([]sheet.Track, 0, len(p.Tracks))
for i, t := range p.Tracks {
artist := ""
if v, ok := tags.Get(t.Tags, tags.FieldArtist); ok && strings.TrimSpace(v) != strings.TrimSpace(p.AlbumArt) {
artist = strings.TrimSpace(v)
}
tracks = append(tracks, sheet.Track{
ID: i + 1,
Title: t.Title,
Artist: artist,
Disc: t.Disc,
Number: t.Number,
Source: filepath.Base(t.Source),
Derived: t.Target,
})
}
return sheet.Sheet{
Album: p.AlbumName,
AlbumArtist: p.AlbumArt,
ArtistDir: p.ArtistDir,
AlbumDir: p.AlbumDir,
Year: p.Year,
Tracks: tracks,
}
}
// ApplySheet rewrites the plan from an edited sheet and returns it to a state
// that can be filed: targets rebuilt, totals recounted, and every issue that was
// about a name worked out again from what the sheet now says.
//
// Tracks the sheet no longer mentions are dropped from the album. That is what
// makes "delete the block" mean something -- the old editor's comment claimed a
// deleted line left the file out, and it did not: the track was still filed,
// under the name intake had already chosen for it.
func (p *Plan) ApplySheet(s sheet.Sheet) error {
before := p.Tracks
kept := make([]TrackPlan, 0, len(s.Tracks))
for _, st := range s.Tracks {
if st.ID < 1 || st.ID > len(before) {
return fmt.Errorf("track %d is not in this album (it has %d tracks)", st.ID, len(before))
}
tp := before[st.ID-1]
tp.Disc = st.Disc
tp.Number = st.Number
tp.Title = strings.TrimSpace(st.Title)
tp.Artist = strings.TrimSpace(st.Artist)
if tp.Artist == "" {
tp.Artist = strings.TrimSpace(s.AlbumArtist)
}
kept = append(kept, tp)
}
if len(kept) == 0 {
return errors.New("no tracks left; the album would have nothing in it")
}
oldAlbum, oldArt := p.AlbumName, p.AlbumArt
p.AlbumName = strings.TrimSpace(s.Album)
p.AlbumTag = p.AlbumName
p.AlbumArt = strings.TrimSpace(s.AlbumArtist)
p.CreditFromTags = p.AlbumArt
// A folder that still holds the name intake derived it from follows a
// rename; one that was typed on purpose does not. Correcting "Boards of
// Canad" to "Boards of Canada" should not leave the album sitting in
// "boards-of-canad", and deliberately naming a folder something other than
// the album should not be undone a moment later.
albumDir := strings.TrimSpace(s.AlbumDir)
if albumDir == "" || normalize.DirName(albumDir) == normalize.DirName(oldAlbum) {
albumDir = p.AlbumName
}
artistDir := strings.TrimSpace(s.ArtistDir)
if artistDir == "" || normalize.DirName(artistDir) == normalize.DirName(oldArt) {
artistDir = p.AlbumArt
}
p.AlbumDir = normalize.DirName(albumDir)
if p.AlbumDir == "" {
p.AlbumDir = normalize.Name(albumDir)
}
p.ArtistDir = normalize.DirName(artistDir)
if p.ArtistDir == "" {
p.ArtistDir = normalize.Name(artistDir)
}
p.Year = tags.NormalizeYear(s.Year)
if strings.TrimSpace(s.Year) != "" && p.Year == "" {
p.Warnings = append(p.Warnings, fmt.Sprintf("could not read a year from %q", s.Year))
}
// A dropped or renumbered track changes the totals, and a stale TRACKTOTAL
// is worse than none: players use it to tell a complete album from a
// half-finished download.
maxTrack := 0
for i := range kept {
if kept[i].Number > maxTrack {
maxTrack = kept[i].Number
}
}
width := normalize.PadWidth(maxTrack)
if p.Width > width {
width = p.Width
}
discs := map[int]bool{}
for _, t := range kept {
discs[t.Disc] = true
}
withDisc := useDiscPrefix(p.DiscPrefix, len(discs))
for i := range kept {
name := kept[i].Title
override := strings.TrimSpace(s.Tracks[i].File)
if override != "" {
name = strings.ReplaceAll(filepath.Base(override), string(filepath.Separator), "-")
if name == "." || name == ".." {
return fmt.Errorf("track %d would be written to %q", s.Tracks[i].ID, name)
}
if filepath.Ext(name) == "" {
name += kept[i].Ext
}
kept[i].Target = name
kept[i].Title = titleFromFile(name)
} else {
kept[i].Target = normalize.TrackFile(kept[i].Disc, kept[i].Number, width, kept[i].Title, kept[i].Ext, withDisc)
}
if n, cut := normalize.Truncate(kept[i].Target, maxNameBytes); cut {
kept[i].Target = n
kept[i].Truncated = true
} else {
kept[i].Truncated = false
}
}
p.Tracks = kept
p.retotal()
for i := range p.Tracks {
t := &p.Tracks[i]
t.Tags = setTag(t.Tags, tags.FieldTrackNumber, fmt.Sprintf("%d", t.Number))
t.Tags = setTag(t.Tags, tags.FieldDiscNumber, fmt.Sprintf("%d", t.Disc))
t.Tags = setTag(t.Tags, tags.FieldTitle, t.Title)
t.Tags = setTag(t.Tags, tags.FieldAlbum, p.AlbumName)
t.Tags = setTag(t.Tags, tags.FieldArtist, t.Artist)
t.Tags = setTag(t.Tags, tags.FieldAlbumArtist, p.AlbumArt)
t.Tags = setTag(t.Tags, tags.FieldDate, p.Year)
}
p.rebuildPaths()
p.reassessAfterEdit()
noteCollisions(p, titlePairs(p.Tracks), sourcePairs(p.Tracks))
return nil
}
// retotal recounts the per-disc track totals and the disc total.
func (p *Plan) retotal() {
perDisc := map[int]int{}
for _, t := range p.Tracks {
perDisc[t.Disc]++
}
for i := range p.Tracks {
t := &p.Tracks[i]
n := fmt.Sprintf("%d", perDisc[t.Disc])
t.Tags = setTag(t.Tags, tags.FieldTrackTotal, n)
t.Tags = setTag(t.Tags, tags.FieldLegacyTrackTotal, n)
d := fmt.Sprintf("%d", len(perDisc))
t.Tags = setTag(t.Tags, tags.FieldDiscTotal, d)
t.Tags = setTag(t.Tags, tags.FieldLegacyDiscTotal, d)
}
}
// setTag replaces a tag, adds it, or removes it when the value is empty.
func setTag(notes []tags.Note, field, value string) []tags.Note {
for i := range notes {
if strings.EqualFold(notes[i].Field, field) {
if value == "" {
return append(notes[:i], notes[i+1:]...)
}
notes[i].Value = value
return notes
}
}
if value == "" {
return notes
}
return append(notes, tags.Note{Field: field, Value: value})
}
// titleFromFile is the reverse of the naming rule, for a hand-typed file name.
func titleFromFile(name string) string {
s := strings.TrimSuffix(name, filepath.Ext(name))
if i := strings.IndexByte(s, '_'); i >= 0 {
s = s[i+1:]
}
return strings.TrimSpace(strings.ReplaceAll(s, "-", " "))
}
// reassessAfterEdit works out the name issues again from what the plan now says,
// rather than from what the tags originally said. Clearing and re-adding is the
// point: an issue that the edit fixed has to disappear, or the album stays
// blocked by a complaint about metadata that is no longer there.
func (p *Plan) reassessAfterEdit() {
for _, text := range []string{
"album name is unknown",
"album name is empty",
"album artist is unknown",
"album artist is empty",
"no ASCII folder name",
"no usable title",
"normalise to the same name",
"would be written twice",
} {
p.Issues = removeIssues(p.Issues, text)
}
if p.AlbumName == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: "the album has no name; put one in the album sheet"})
}
if p.AlbumArt == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: "the album has no artist; put one in the album sheet"})
}
if p.AlbumDir == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("album name %q has no ASCII folder name; put one in the album sheet", p.AlbumName)})
}
if p.ArtistDir == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("album artist %q has no ASCII folder name; put one in the album sheet", p.AlbumArt)})
}
for _, t := range p.Tracks {
if strings.TrimSpace(t.Title) == "" {
p.Issues = append(p.Issues, Issue{Hard: true, Text: fmt.Sprintf("%s: no usable title; put one in the album sheet", filepath.Base(t.Source))})
}
}
}
// BuildWithArtist builds the plan again with the artist folder that was
// resolved (or chosen) rather than the one the tags implied.
func BuildWithArtist(a scan.Album, archiveRoot, libraryRoot string, key DirKey, discPrefix string) Plan {
p := Build(a, archiveRoot, libraryRoot, key, discPrefix)
if key.Dir != "" {
p.ArtistDir = key.Dir
}
if strings.TrimSpace(key.Credit) != "" {
p.AlbumArt = key.Credit
p.CreditFromTags = key.Credit
for i := range p.Tracks {
p.Tracks[i].Tags = setTag(p.Tracks[i].Tags, tags.FieldAlbumArtist, key.Credit)
if v, ok := tags.Get(p.Tracks[i].Tags, tags.FieldArtist); !ok || strings.TrimSpace(v) == "" {
p.Tracks[i].Tags = setTag(p.Tracks[i].Tags, tags.FieldArtist, key.Credit)
}
}
}
p.rebuildPaths()
noteCollisions(&p, titlePairs(p.Tracks), sourcePairs(p.Tracks))
return p
}
func (p *Plan) rebuildPaths() {
if p.AlbumDir == "" {
p.AlbumDir = normalize.DirName(p.AlbumName)
if p.AlbumDir == "" {
p.AlbumDir = normalize.Name(p.AlbumName)
}
}
if p.ArtistDir == "" {
p.ArtistDir = normalize.DirName(p.AlbumArt)
}
if p.ArchiveRoot == "" || p.LibraryRoot == "" {
return
}
if p.ArtistDir != "" && p.AlbumDir != "" {
p.ArchiveDir = filepath.Join(p.ArchiveRoot, p.ArtistDir, p.AlbumDir)
p.LibraryDir = filepath.Join(p.LibraryRoot, p.ArtistDir, p.AlbumDir)
}
}
func removeIssues(in []Issue, contains string) []Issue {
out := make([]Issue, 0, len(in))
for _, i := range in {
if !strings.Contains(i.Text, contains) {
out = append(out, i)
}
}
return out
}
func commonValue(a scan.Album, field string) (string, bool) {
var value string
found := false
for _, t := range a.Tracks {
v, ok := tags.Get(t.Tags, field)
if !ok || strings.TrimSpace(v) == "" {
return "", false
}
if !found {
value, found = v, true
continue
}
if v != value {
return "", false
}
}
return value, found
}
// dominantArtist returns the most common non-empty ARTIST across an album's
// tracks, how many tracks carry it, and how many carry any artist at all.
//
// This is how an album with guest tracks is told apart from a compilation when
// there is no ALBUMARTIST to say so. Matching whole credit strings is deliberate:
// "Deadmau5 + Imogen Heap" is a different credit from "Deadmau5", and a solo
// album with two features still has a clear majority. Splitting credits on a
// separator would mean guessing whether it is "+", "&", "feat." or "with".
func dominantArtist(a scan.Album) (string, int, int) {
return dominantValue(a, tags.FieldArtist)
}
// dominantValue returns the most common non-empty value of a field, how many
// tracks carry it, and how many carry any value at all. Ties break
// alphabetically so the result does not depend on map order.
func dominantValue(a scan.Album, field string) (string, int, int) {
counts := map[string]int{}
total := 0
for _, t := range a.Tracks {
v, ok := tags.Get(t.Tags, field)
v = strings.TrimSpace(v)
if !ok || v == "" {
continue
}
counts[v]++
total++
}
best, n := "", 0
for v, c := range counts {
if c > n || (c == n && v < best) {
best, n = v, c
}
}
return best, n, total
}
// differingArtists reports whether the tracks credit more than one artist.
func differingArtists(a scan.Album) bool {
first := ""
for _, t := range a.Tracks {
v, ok := tags.Get(t.Tags, tags.FieldArtist)
v = strings.TrimSpace(v)
if !ok || v == "" {
continue
}
if first == "" {
first = v
continue
}
if v != first {
return true
}
}
return false
}
// useDiscPrefix decides whether target names carry the disc number. "auto" only
// carries it when there is more than one disc, where it is the only thing
// separating two tracks that share a number.
func useDiscPrefix(mode string, discs int) bool {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "never":
return false
case "auto":
return discs > 1
default:
return true
}
}