git/intake/main
internal/cli/interactive.go
451 lines13 KB last change raw · history
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
}