package cli
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"intake/internal/artist"
"intake/internal/normalize"
"intake/internal/plan"
"intake/internal/scan"
"intake/internal/sheet"
)
func (a *App) artistIndex(credit string) (*artist.Index, error) {
ix := artist.NewIndex()
root := a.Cfg.Archive()
if entries, err := os.ReadDir(root); err == nil {
for _, e := range entries {
if e.IsDir() && !strings.HasPrefix(e.Name(), ".") {
ix.AddDir(e.Name())
}
}
}
if j, err := a.journal(); err == nil {
for _, rec := range j.Albums {
if rec.ArchiveDir == "" {
continue
}
if rel, err := filepath.Rel(root, rec.ArchiveDir); err == nil {
if parts := strings.Split(rel, string(filepath.Separator)); len(parts) > 0 {
ix.AddDir(parts[0])
}
}
}
}
if err := ix.LoadAliases(artist.AliasPath(a.Cfg.Root)); err != nil {
fmt.Fprintf(a.Err, "warning: could not read artist aliases: %v\n", err)
}
return ix, nil
}
func (a *App) resolveArtist(al scan.Album, credit string, various bool, editorArtist string) (plan.DirKey, string, error) {
if various {
return plan.DirKey{Dir: artist.VariousArtists, Credit: credit, Source: "various"}, credit, nil
}
if strings.TrimSpace(editorArtist) != "" {
a.logf("artist folder: %s (from the editor)", editorArtist)
return plan.DirKey{Dir: editorArtist, Credit: credit, Source: "editor"}, credit, nil
}
if strings.TrimSpace(credit) == "" {
return plan.DirKey{Dir: "unknown-artist", Credit: "", Source: "placeholder"}, "", nil
}
ix, err := a.artistIndex(credit)
if err != nil {
return plan.DirKey{}, credit, err
}
artists, isCollab := artist.Split(credit)
primary := credit
if len(artists) > 0 {
primary = artists[0]
}
if isCollab {
choice, err := a.askCollab(credit, artists)
if err != nil {
return plan.DirKey{}, credit, err
}
if choice != "" && choice != primary {
key := normalize.DirName(choice)
if key == "" {
return plan.DirKey{}, credit, fmt.Errorf("collaboration choice %q has no usable directory name", choice)
}
a.rememberAlias(ix, credit, key)
return plan.DirKey{Dir: key, Credit: choice, Source: "collab"}, choice, nil
}
}
if dir, ok := ix.Alias[strings.TrimSpace(credit)]; ok && dir != "" {
a.logf("artist folder: %s (from artists.toml)", dir)
return plan.DirKey{Dir: dir, Credit: credit, Source: "alias"}, credit, nil
}
m := ix.Resolve(primary)
if len(m.Dirs) == 0 {
return plan.DirKey{}, credit, fmt.Errorf("could not derive a folder name for artist %q; add an entry to artists.toml", primary)
}
best := m.Dirs[0]
if best.ExactAlias || best.ExactDir || best.RomanizedMatch {
a.logf("artist folder: %s (%s)", best.Dir, describeMatch(best))
return plan.DirKey{Dir: best.Dir, Credit: primary, Source: describeMatch(best)}, primary, nil
}
// A fuzzy match is a guess that two names which merely look alike are the
// same artist, and an unattended run must not act on a guess. "Blur" and
// "Blue" score 75%; "The Cure" and "The Cult" score 75%; "RTL Artist" and
// "Art Artist" score 80%. Taking one of those files the album under a
// different artist's folder: nothing downstream notices, because a folder
// name is never verified against the ALBUMARTIST tag, and once
// rememberAlias has written it down every later album by that artist follows
// it there. Creating the folder the credit actually names is visible in a
// directory listing and costs one line of artists.toml when the two really
// are the same artist, so that is what an unattended run does instead.
//
// A person sitting in front of the prompt is still shown the candidates and
// may pick one; see askArtist, whose default is now the new folder.
if best.Fuzzy && a.Yes {
fresh := normalize.DirName(primary)
if fresh == "" {
fresh = "unknown-artist"
}
a.logf("artist folder: %s (new)", fresh)
a.logf("note: %q is %.0f%% similar to the existing folder %q, which was NOT used.", primary, best.Score*100, best.Dir)
a.logf(" if they are the same artist, add this line to %s and file again:", artist.AliasPath(a.Cfg.Root))
a.logf(" %s = %q", artist.TOMLKey(primary), best.Dir)
return plan.DirKey{Dir: fresh, Credit: primary, Source: "new"}, primary, nil
}
if best.Score == 0 && best.Dir == normalize.DirName(primary) {
a.logf("artist folder: %s (new)", best.Dir)
a.rememberAlias(ix, credit, best.Dir)
return plan.DirKey{Dir: best.Dir, Credit: primary, Source: "new"}, primary, nil
}
if m.NeedsUser {
if a.Yes {
a.logf("artist folder: unknown-artist (no readable name for %q; fix it in the editor)", primary)
return plan.DirKey{Dir: "unknown-artist", Credit: primary, Source: "placeholder"}, "", nil
}
fmt.Fprintf(a.Out, "artist %q cannot be romanised automatically.\n", primary)
fmt.Fprintf(a.Out, "folder name under archive/ [%s] ", normalize.DirName(primary))
_ = os.Stdout.Sync()
line, _ := bufio.NewReader(a.In).ReadString('\n')
key := normalize.DirName(line)
if key == "" {
key = "unknown-artist"
}
a.logf("artist folder: %s (entered by you)", key)
if key != credit {
a.rememberAlias(ix, credit, key)
}
a.logf("note: folder %q, while ALBUMARTIST stays %q", key, credit)
return plan.DirKey{Dir: key, Credit: credit, Source: "entered"}, "", nil
}
if a.Yes {
a.logf("artist folder: %s (%s, auto-selected)", best.Dir, describeMatch(best))
a.rememberAlias(ix, credit, best.Dir)
return plan.DirKey{Dir: best.Dir, Credit: primary, Source: describeMatch(best)}, primary, nil
}
key, err := a.askArtist(m)
if err != nil {
return plan.DirKey{}, credit, err
}
a.rememberAlias(ix, credit, key)
return plan.DirKey{Dir: key, Credit: primary, Source: "chosen"}, primary, nil
}
func describeMatch(c artist.Candidate) string {
switch {
case c.ExactAlias:
return "from artists.toml"
case c.ExactDir:
return "existing folder"
case c.RomanizedMatch:
return "romanised match"
case c.Fuzzy:
return fmt.Sprintf("fuzzy match %.0f%%", c.Score*100)
default:
return "new"
}
}
func (a *App) askCollab(credit string, parts []string) (string, error) {
a.logf("")
a.logf("This release has more than one credited artist: %s", credit)
for i, p := range parts {
a.logf(" [%d] %s", i+1, p)
}
a.logf(" [c] keep the whole collaboration as its own folder")
fmt.Fprintf(a.Out, "file it under which artist? [Enter = %s] ", parts[0])
_ = os.Stdout.Sync()
line, err := bufio.NewReader(a.In).ReadString('\n')
if err != nil && line == "" {
return parts[0], nil
}
line = strings.TrimSpace(line)
switch {
case line == "":
return parts[0], nil
case strings.EqualFold(line, "c"):
return credit, nil
default:
if n, err := strconv.Atoi(line); err == nil && n >= 1 && n <= len(parts) {
return parts[n-1], nil
}
if strings.TrimSpace(line) != "" {
return line, nil
}
}
return parts[0], nil
}
func (a *App) askArtist(m artist.Match) (string, error) {
a.logf("")
a.logf("artist %q could belong to an existing folder:", m.Credit)
type row struct {
dir string
count int
fuzzy bool
score float64
}
var rows []row
seen := map[string]bool{}
for _, c := range m.Dirs {
if seen[c.Dir] {
continue
}
seen[c.Dir] = true
rows = append(rows, row{c.Dir, a.albumCount(c.Dir), c.Fuzzy, c.Score})
if len(rows) >= 8 {
break
}
}
// The default is what a bare Enter takes, so it must not be the one entry
// that is only a guess. Listing a fuzzy folder is useful -- the person
// reading it may know that "Blur" really is "Blue" -- but choosing it has to
// be deliberate, which is also what an unattended run does by never taking
// one at all.
def := normalize.DirName(m.Credit)
for _, r := range rows {
if !r.fuzzy {
def = r.dir
break
}
}
if def == "" {
def = rows[0].dir
}
for i, r := range rows {
rel := ""
if r.count > 0 {
rel = fmt.Sprintf(" (%d album(s))", r.count)
}
reason := ""
switch {
case !r.fuzzy:
reason = " different name, or already decided"
default:
reason = fmt.Sprintf(" looks %.0f%% alike; only a guess", r.score*100)
}
a.logf(" [%d] %s%s%s", i+1, r.dir, rel, reason)
}
a.logf(" [n] create a new folder")
a.logf(" [t] type a different name")
fmt.Fprintf(a.Out, "choose [Enter = %s] ", def)
_ = os.Stdout.Sync()
line, err := bufio.NewReader(a.In).ReadString('\n')
if err != nil && line == "" {
return def, nil
}
line = strings.TrimSpace(line)
switch {
case line == "":
return def, nil
case strings.EqualFold(line, "n"):
fmt.Fprintf(a.Out, "new folder name [%s] ", normalize.DirName(m.Credit))
name, _ := bufio.NewReader(a.In).ReadString('\n')
name = normalize.DirName(name)
if name == "" {
return normalize.DirName(m.Credit), nil
}
return name, nil
case strings.EqualFold(line, "t"):
fmt.Fprintf(a.Out, "folder name: ")
name, _ := bufio.NewReader(a.In).ReadString('\n')
name = normalize.DirName(name)
if name == "" {
return def, nil
}
return name, nil
default:
if n, err := strconv.Atoi(line); err == nil && n >= 1 && n <= len(rows) {
return rows[n-1].dir, nil
}
if key := normalize.DirName(line); key != "" {
return key, nil
}
}
return def, nil
}
func (a *App) albumCount(dir string) int {
j, err := a.journal()
if err != nil {
return 0
}
n := 0
for _, rec := range j.Albums {
if rec.ArchiveDir == "" {
continue
}
if rel, err := filepath.Rel(a.Cfg.Archive(), rec.ArchiveDir); err == nil {
if parts := strings.Split(rel, string(filepath.Separator)); len(parts) > 1 && parts[0] == dir {
n++
}
}
}
return n
}
func (a *App) rememberAlias(ix *artist.Index, credit, dir string) {
ix.SetAlias(credit, dir)
if a.DryRun {
a.logf("dry run: would remember %q in %s", credit, artist.AliasPath(a.Cfg.Root))
return
}
if err := ix.SaveAliases(artist.AliasPath(a.Cfg.Root)); err != nil {
fmt.Fprintf(a.Err, "warning: could not save artist aliases: %v\n", err)
}
}
func (a *App) openEditor(path string) bool {
editor := a.Cfg.EditorCommand()
if editor == "" {
return false
}
cmd := exec.Command("sh", "-c", editor+" "+shellQuote(path))
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
if _, ok := err.(*exec.Error); ok {
return false
}
}
return true
}
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// editSheet opens the whole album in $EDITOR: every field intake is about to
// write, in one file, and applies whatever comes back.
//
// This replaced an editor that could only change the two folder names and the
// text after each track number. Everything else -- the album title, the album
// artist, the year, the disc and track numbers, the artist on one track -- was
// decided from the tags and could only be put right by retagging the files.
func (a *App) editSheet(p *plan.Plan) (*sheet.Sheet, error) {
current := p.Sheet()
path := filepath.Join(a.Cfg.StateDir, "sheet.txt")
if a.Cfg.StateDir == "" {
dir, err := os.MkdirTemp("", "intake-sheet-")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
path = filepath.Join(dir, "sheet.txt")
} else {
if err := os.MkdirAll(a.Cfg.StateDir, 0o755); err != nil {
return nil, err
}
}
if err := os.WriteFile(path, []byte(sheet.Render(current)), 0o644); err != nil {
return nil, err
}
a.logf("")
if p.Blocked() {
a.logf("This album needs you. Everything about it is editable:")
for _, i := range p.Issues {
if i.Hard {
a.logf(" ! %s", i.Text)
}
}
} else {
a.logf("Editing the album sheet.")
}
a.logf("Opening your editor on:")
a.logf(" %s", path)
_ = os.Stdout.Sync()
if !a.openEditor(path) {
return nil, fmt.Errorf("could not launch an editor (set $EDITOR or the editor setting in config); the album still needs you")
}
edited, err := os.ReadFile(path)
if err != nil {
return nil, err
}
next, err := sheet.Parse(string(edited), current)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if err := p.ApplySheet(next); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
// Kept, so that a second run on the same album starts from the same place
// rather than from the tags again.
if saved, err := a.sheetStore().Save(p.Album.Dir, string(edited)); err != nil {
fmt.Fprintf(a.Err, "warning: could not save the album sheet: %v\n", err)
} else if saved != "" {
a.logf("saved to %s", saved)
}
return &next, nil
}
// sheetStore is where an album's edits are kept between runs.
func (a *App) sheetStore() sheet.Store {
return sheet.Store{Dir: filepath.Join(a.Cfg.StateDir, "review")}
}
// sheetFixable reports whether everything blocking an album is something a
// person can put right in the album sheet. An album of mp3s is blocked too, and
// opening an editor for it would only waste a round trip: the sheet cannot turn
// a lossy file into a lossless one.
func sheetFixable(p plan.Plan) bool {
var blocked bool
for _, i := range p.Issues {
if !i.Hard {
continue
}
blocked = true
t := i.Text
switch {
case strings.Contains(t, "album name is unknown"),
strings.Contains(t, "album artist is unknown"),
strings.Contains(t, "no ASCII folder name"),
strings.Contains(t, "no usable title"),
strings.Contains(t, "normalise to the same name"),
strings.Contains(t, "would be written twice"):
default:
return false
}
}
return blocked
}