Debian Codegraph @

beetsplug/edit.py

raw
1 """Open metadata information in a text editor to let the user edit it."""
2
3 from __future__ import annotations
4
5 import codecs
6 import os
7 import shlex
8 import subprocess
9 from collections import Counter
10 from tempfile import NamedTemporaryFile
11 from typing import TYPE_CHECKING, Protocol, cast
12
13 import yaml
14
15 from beets import plugins, ui, util
16 from beets.dbcore import types
17 from beets.exceptions import UserError
18 from beets.importer import Action
19 from beets.library import Album, Item
20 from beets.util import PromptChoice
21
22 if TYPE_CHECKING:
23 from collections.abc import Container, Iterable, Sequence
24
25 from beets.importer import ImportSession, ImportTask
26 from beets.library import LibModel, Library
27 from beets.logging import BeetsLogger as Logger
28
29 from ._typing import JSONDict
30
31 # These "safe" types can avoid the format/parse cycle that most fields go
32 # through: they are safe to edit with native YAML types.
33 SAFE_TYPES = (
34 types.BaseFloat,
35 types.BaseInteger,
36 types.Boolean,
37 types.DelimitedString,
38 )
39
40 # Fixed fields that only exist on Item, not Album (e.g. title, track, path).
41 # Flexible attributes are deliberately excluded from this set: they aren't
42 # part of either model's fixed schema, so they can't be told apart by name
43 # alone and are left for the user to configure correctly.
44 ITEM_ONLY_FIELDS = Item._field_names - Album._field_names
45
46
47 class EditCLIOpts(Protocol):
48 album: bool
49 all: bool | None
50 field: list[str] | None
51
52
53 class ParseError(Exception):
54 """The modified file is unreadable. The user should be offered a chance to
55 fix the error.
56 """
57
58
59 def edit(filename: str, log: Logger) -> None:
60 """Open `filename` in a text editor."""
61 cmd = shlex.split(util.editor_command())
62 cmd.append(filename)
63 log.debug("invoking editor command: {!r}", cmd)
64 try:
65 subprocess.call(cmd)
66 except OSError as exc:
67 raise UserError(f"could not run editor command {cmd[0]!r}: {exc}")
68
69
70 def dump(arg: Sequence[JSONDict]) -> str:
71 """Dump a sequence of dictionaries as YAML for editing."""
72 return yaml.safe_dump_all(arg, allow_unicode=True, default_flow_style=False)
73
74
75 def load(s: str) -> list[JSONDict]:
76 """Read a sequence of YAML documents back to a list of dictionaries
77 with string keys.
78
79 Can raise a `ParseError`.
80 """
81 try:
82 out = []
83 for d in yaml.safe_load_all(s):
84 if not isinstance(d, dict):
85 raise ParseError(
86 f"each entry must be a dictionary; found {type(d).__name__}"
87 )
88
89 # Convert all keys to strings. They started out as strings,
90 # but the user may have inadvertently messed this up.
91 out.append({str(k): v for k, v in d.items()})
92
93 except yaml.YAMLError as e:
94 raise ParseError(f"invalid YAML: {e}")
95 return out
96
97
98 def _safe_value(obj: LibModel, key: str, value: str) -> bool:
99 """Check whether the `value` is safe to represent in YAML and trust as
100 returned from parsed YAML.
101
102 This ensures that values do not change their type when the user edits their
103 YAML representation.
104 """
105 if value is None:
106 return True
107 typ = obj._type(key)
108 return isinstance(typ, SAFE_TYPES) and isinstance(value, typ.model_type)
109
110
111 def flatten(obj: LibModel, fields: Container[str] | None) -> JSONDict:
112 """Represent `obj`, a `dbcore.Model` object, as a dictionary for
113 serialization. Only include the given `fields` if provided;
114 otherwise, include everything.
115
116 The resulting dictionary's keys are strings and the values are
117 safely YAML-serializable types.
118 """
119 # Format each value.
120 d = {}
121 for key in obj.keys():
122 value = obj[key]
123 if _safe_value(obj, key, value):
124 # A safe value that is faithfully representable in YAML.
125 d[key] = value
126 else:
127 # A value that should be edited as a string.
128 d[key] = obj.formatted()[key]
129
130 # Possibly filter field names.
131 if fields:
132 return {k: v for k, v in d.items() if k in fields}
133 return d
134
135
136 def apply_(obj: LibModel, data: JSONDict) -> None:
137 """Set the fields of a `dbcore.Model` object according to a
138 dictionary.
139
140 This is the opposite of `flatten`. The `data` dictionary should have
141 strings as values.
142 """
143 for key, value in data.items():
144 if _safe_value(obj, key, value):
145 # A safe value *stayed* represented as a safe type. Assign it
146 # directly.
147 obj[key] = value
148 else:
149 # Either the field was stringified originally or the user changed
150 # it from a safe type to an unsafe one. Parse it as a string.
151 obj.set_parse(key, str(value))
152
153
154 class EditPlugin(plugins.BeetsPlugin):
155 def __init__(self) -> None:
156 super().__init__()
157
158 self.config.add(
159 {
160 # The default fields to edit.
161 "albumfields": "album albumartist",
162 "itemfields": "track title artist album",
163 # Silently ignore any changes to these fields.
164 "ignore_fields": "id path",
165 }
166 )
167
168 self.register_listener(
169 "before_choose_candidate", self.before_choose_candidate_listener
170 )
171
172 def commands(self) -> list[ui.Subcommand]:
173 edit_command = ui.Subcommand("edit", help="interactively edit metadata")
174 edit_command.parser.add_option(
175 "-f",
176 "--field",
177 metavar="FIELD",
178 action="append",
179 help="edit this field also",
180 )
181 edit_command.parser.add_option(
182 "--all", action="store_true", dest="all", help="edit all fields"
183 )
184 edit_command.parser.add_album_option()
185 edit_command.func = self._edit_command
186 return [edit_command]
187
188 def _edit_command(
189 self, lib: Library, opts: EditCLIOpts, args: list[str]
190 ) -> None:
191 """The CLI command function for the `beet edit` command."""
192 # Get the objects to edit.
193 objs = (lib.albums if opts.album else lib.items)(args)
194 if not objs:
195 ui.print_("Nothing to edit.")
196 return
197
198 # Get the fields to edit.
199 if opts.all:
200 fields = None
201 else:
202 fields = self._get_fields(opts.album, opts.field)
203 self.edit(opts.album, objs, fields)
204
205 def _get_fields(self, album: bool, extra: list[str] | None) -> set[str]:
206 """Get the set of fields to edit."""
207 # Start with the configured base fields.
208 if album:
209 fields = self.config["albumfields"].as_str_seq()
210 else:
211 fields = self.config["itemfields"].as_str_seq()
212
213 # Add the requested extra fields.
214 if extra:
215 fields += extra
216
217 # Ensure we always have the `id` field for identification.
218 fields.append("id")
219
220 return set(fields)
221
222 def edit(
223 self,
224 album: bool,
225 objs: Sequence[LibModel],
226 fields: Container[str] | None,
227 ) -> None:
228 """The core editor function.
229
230 - `album`: A flag indicating whether we're editing Items or Albums.
231 - `objs`: The `Item`s or `Album`s to edit.
232 - `fields`: The set of field names to edit (or None to edit
233 everything).
234 """
235 # Present the YAML to the user and let them change it.
236 success = self.edit_objects(objs, fields)
237
238 # Save the new data.
239 if success:
240 self.save_changes(objs)
241
242 def edit_objects(
243 self, objs: Sequence[LibModel], fields: Container[str] | None
244 ) -> bool | None:
245 """Dump a set of Model objects to a file as text, ask the user
246 to edit it, and apply any changes to the objects.
247
248 Return a boolean indicating whether the edit succeeded.
249 """
250 # Get the content to edit as raw data structures.
251 old_data = [flatten(o, fields) for o in objs]
252 cur_str = dump(old_data)
253
254 # Loop until we have parseable data and the user confirms.
255 while True:
256 result = self._edit_yaml(cur_str)
257 if result is None:
258 return False
259 new_data, new_str = result
260
261 # Show the changes.
262 # If the objects are not on the DB yet, we need a copy of their
263 # original state for show_model_changes.
264 objs_old = [
265 obj.copy() if (obj.id is not None and obj.id < 0) else None
266 for obj in objs
267 ]
268 self.apply_data(objs, old_data, new_data)
269 changed = False
270 for obj, obj_old in zip(objs, objs_old):
271 changed |= ui.show_model_changes(obj, obj_old)
272 if not changed:
273 ui.print_("No changes to apply.")
274 return False
275
276 # For cancel/keep-editing, restore objects to their original
277 # in-memory state so temp edits don't leak into the session
278 choice = ui.input_options(("continue Editing", "apply", "cancel"))
279 if choice == "a": # Apply.
280 return True
281 if choice == "c": # Cancel.
282 self.apply_data(objs, new_data, old_data)
283 return False
284 if choice == "e": # Keep editing.
285 self.apply_data(objs, new_data, old_data)
286 cur_str = new_str
287 continue
288
289 def apply_data(
290 self,
291 objs: Sequence[LibModel],
292 old_data: Sequence[JSONDict],
293 new_data: Sequence[JSONDict],
294 ) -> None:
295 """Take potentially-updated data and apply it to a set of Model
296 objects.
297
298 Documents are matched to objects by their ``id`` field rather than
299 by position, so a reordered or otherwise misaligned document list
300 cannot cause one object's data to be applied to a different object.
301
302 The objects are not written back to the database, so the changes
303 are temporary.
304 """
305 if len(old_data) != len(new_data):
306 self._log.warning(
307 "number of objects changed from {} to {}",
308 len(old_data),
309 len(new_data),
310 )
311
312 obj_by_id = {o.id: o for o in objs}
313 old_by_id = {d.get("id"): d for d in old_data}
314 new_id_counts = Counter(d.get("id") for d in new_data)
315 ignore_fields = self.config["ignore_fields"].as_str_seq()
316 for new_dict in new_data:
317 new_id = new_dict.get("id")
318 if new_id_counts[new_id] > 1:
319 # Two or more documents claim the same id: either a document's
320 # id was edited to collide with another one, or the same
321 # document was duplicated. We can't tell which document is
322 # the "real" one, so ignore all of them.
323 self._log.warning(
324 "ignoring objects with duplicate id {}", new_id
325 )
326 continue
327
328 old_dict = old_by_id.get(new_id)
329 obj = obj_by_id.get(new_id)
330 if old_dict is None or obj is None:
331 self._log.warning("ignoring object whose id changed")
332 continue
333
334 # Prohibit any changes to forbidden fields to avoid
335 # clobbering `id` and such by mistake.
336 forbidden = False
337 for key in ignore_fields:
338 if old_dict.get(key) != new_dict.get(key):
339 self._log.warning("ignoring object whose {} changed", key)
340 forbidden = True
341 break
342 if forbidden:
343 continue
344
345 apply_(obj, new_dict)
346
347 def save_changes(self, objs: Sequence[LibModel]) -> None:
348 """Save a list of updated Model objects to the database."""
349 # Save to the database and possibly write tags.
350 for ob in objs:
351 if ob._dirty:
352 self._log.debug("saving changes to {}", ob)
353 ob.try_sync(ui.should_write(), ui.should_move())
354
355 # Methods for interactive importer execution.
356
357 def before_choose_candidate_listener(
358 self, session: ImportSession, task: ImportTask
359 ) -> list[PromptChoice]:
360 """Append an "Edit" choice and an "edit Candidates" choice (if
361 there are candidates) to the interactive importer prompt.
362 """
363 choices = [PromptChoice("d", "eDit", self.importer_edit)]
364 if task.candidates:
365 choices.append(
366 PromptChoice(
367 "c", "edit Candidates", self.importer_edit_candidate
368 )
369 )
370
371 return choices
372
373 def _importer_edit_album_header(self, task: ImportTask) -> JSONDict | None:
374 """Build the album-header YAML document for import editing.
375
376 Returns a dict of album-level fields, or ``None`` when the current
377 task is not an album import.
378 """
379 if not getattr(task, "is_album", False) or not task.items:
380 return None
381
382 album_fields = set(self.config["albumfields"].as_str_seq())
383 if not album_fields:
384 return None
385
386 # Drop fields that only exist on Item (title, track, path, ...);
387 # since the header is built from a single item and then applied to
388 # every item, an item-only field here would silently stamp that
389 # one item's value onto the whole album. Flexible fields are left
390 # alone so they can still be edited at the album level.
391 item_only_fields = album_fields & ITEM_ONLY_FIELDS
392 if item_only_fields:
393 self._log.warning(
394 "ignoring item-only fields configured in albumfields: {}",
395 ", ".join(sorted(item_only_fields)),
396 )
397 album_fields -= ITEM_ONLY_FIELDS
398 if not album_fields:
399 return None
400
401 first_item = task.items[0]
402 header = flatten(first_item, album_fields)
403 return header if header else None
404
405 def _importer_edit_apply_header(
406 self, items: Iterable[Item], header_data: JSONDict
407 ) -> None:
408 """Apply album-header changes to every item in the list."""
409 if not header_data:
410 return
411 for item in items:
412 apply_(item, header_data)
413
414 def _edit_yaml(self, old_str: str) -> tuple[list[JSONDict], str] | None:
415 """Open a temporary file with `old_str`, let the user edit it, and
416 return the parsed list of YAML documents.
417
418 Returns ``(parsed_data, edited_str)`` on success, or ``None`` if the
419 user aborted (no changes or unresolvable parse error).
420 """
421 with NamedTemporaryFile(
422 mode="w", suffix=".yaml", delete=False, encoding="utf-8"
423 ) as new:
424 new.write(old_str)
425
426 try:
427 while True:
428 edit(new.name, self._log)
429
430 with codecs.open(new.name, encoding="utf-8") as f:
431 new_str = f.read()
432 if new_str == old_str:
433 ui.print_("No changes; aborting.")
434 return None
435
436 try:
437 return load(new_str), new_str
438 except ParseError as e:
439 ui.print_(f"Could not read data: {e}")
440 if not ui.input_yn("Edit again to fix? (Y/n)", True):
441 return None
442 finally:
443 os.remove(new.name)
444
445 def importer_edit(
446 self, session: ImportSession, task: ImportTask
447 ) -> Action | None:
448 """Callback for invoking the functionality during an interactive
449 import session on the *original* item tags.
450 """
451 # Assign negative temporary ids to Items that are not in the database
452 # yet. By using negative values, no clash with items in the database
453 # can occur.
454 for i, obj in enumerate(task.items, start=1):
455 # The importer may set the id to None when re-importing albums.
456 if not obj._db or obj.id is None:
457 obj.id = -i
458
459 # Build the album header before deciding which fields to show for each
460 # track. Only fields actually present in the header should be omitted
461 # from the track documents.
462 header_data = self._importer_edit_album_header(task)
463 header_fields = set(header_data) if header_data is not None else set()
464 item_fields = set(self.config["itemfields"].as_str_seq())
465
466 # Track-level fields exclude any that are shown in the album header
467 # to avoid duplication.
468 track_fields = item_fields - header_fields
469 track_fields.add("id")
470
471 # Build the YAML document list.
472 old_track_data = [flatten(o, track_fields) for o in task.items]
473 all_old_data = []
474 if header_data is not None:
475 all_old_data.append(header_data)
476 all_old_data.extend(old_track_data)
477 has_header = header_data is not None
478 num_data_docs = 1 if has_header else 0
479
480 cur_str = dump(all_old_data)
481
482 while True:
483 result = self._edit_yaml(cur_str)
484 if result is None:
485 self._importer_edit_cleanup(task)
486 return None
487 new_all_data, new_str = result
488
489 expected_total = num_data_docs + len(task.items)
490 if len(new_all_data) != expected_total:
491 ui.print_(
492 f"Number of documents changed from {expected_total} to "
493 f"{len(new_all_data)}."
494 )
495 if ui.input_yn("Edit again to fix? (Y/n)", True):
496 continue
497 self._importer_edit_cleanup(task)
498 return None
499
500 # Split into album header and per-track documents. Every track
501 # document always has an `id` field (see `track_fields` above),
502 # while the header never does, so identify the header by the
503 # absence of `id` rather than by position. This keeps the split
504 # correct even if the user moves the header elsewhere in the
505 # file, since `apply_data` already matches track documents by
506 # id regardless of order.
507 if has_header:
508 new_header_data = [d for d in new_all_data if "id" not in d]
509 new_track_data = [d for d in new_all_data if "id" in d]
510 if len(new_header_data) != 1:
511 ui.print_(
512 "Could not identify the album header: exactly one "
513 "document must have no `id` field."
514 )
515 if ui.input_yn("Edit again to fix? (Y/n)", True):
516 continue
517 self._importer_edit_cleanup(task)
518 return None
519 else:
520 new_header_data = []
521 new_track_data = new_all_data
522
523 # Snapshot originals for diff display and restore.
524 objs_old = cast("list[Item]", [obj.copy() for obj in task.items])
525
526 # Apply header changes to every item.
527 if new_header_data:
528 self._importer_edit_apply_header(task.items, new_header_data[0])
529
530 # Apply per-track changes.
531 self.apply_data(task.items, old_track_data, new_track_data)
532
533 # Show the diff.
534 changed = False
535 for item, old_copy in zip(task.items, objs_old):
536 changed |= ui.show_model_changes(item, old_copy)
537
538 if not changed:
539 ui.print_("No changes to apply.")
540 self._importer_edit_cleanup(task)
541 return None
542
543 choice = ui.input_options(("continue Editing", "apply", "cancel"))
544 if choice == "a": # Apply.
545 self._importer_edit_cleanup(task)
546 return Action.RETAG
547 if choice == "c": # Cancel.
548 self._importer_edit_restore_from_copies(task, objs_old)
549 self._importer_edit_cleanup(task)
550 return None
551 if choice == "e": # Keep editing.
552 self._importer_edit_restore_from_copies(task, objs_old)
553 cur_str = new_str
554 continue
555
556 @staticmethod
557 def _importer_edit_cleanup(task: ImportTask) -> None:
558 """Remove temporary negative ids from task items."""
559 for obj in task.items:
560 if obj.id is not None and obj.id < 0:
561 obj.id = None
562
563 @staticmethod
564 def _importer_edit_restore_from_copies(
565 task: ImportTask, copies: Sequence[Item]
566 ) -> None:
567 """Restore items to their state before the last edit cycle.
568
569 ``copies`` must be a list of :class:`Item <beets.library.Item>` copies
570 taken *before* the changes were applied.
571 """
572 for i, item in enumerate(task.items):
573 if i < len(copies):
574 for key in item._fields:
575 item[key] = copies[i][key]
576
577 def importer_edit_candidate(
578 self, session: ImportSession, task: ImportTask
579 ) -> Action | None:
580 """Callback for invoking the functionality during an interactive
581 import session on a *candidate*. The candidate's metadata is
582 applied to the original items.
583 """
584 # Prompt the user for a candidate.
585 if task.candidates:
586 sel = ui.input_options((), numrange=(1, len(task.candidates)))
587 # Force applying the candidate on the items.
588 task.match = task.candidates[sel - 1]
589 task.apply_metadata()
590
591 return self.importer_edit(session, task)
592
593 return None