Debian Codegraph @

beetsplug/info.py

raw
1 """Shows file metadata."""
2
3 from __future__ import annotations
4
5 import os
6 from typing import TYPE_CHECKING, Any, Literal, Protocol
7
8 import mediafile
9
10 from beets import ui
11 from beets.library import Item
12 from beets.plugins import BeetsPlugin
13 from beets.util import displayable_path, normpath, syspath
14
15 if TYPE_CHECKING:
16 from collections.abc import Callable, Iterable, Iterator, Sequence
17
18 from beets.library import LibModel, Library
19
20 from ._typing import JSONDict
21
22 DataEmitter = Callable[
23 [Literal["*"] | list[str]], tuple[JSONDict, LibModel]
24 ]
25
26
27 class InfoCLIOpts(Protocol):
28 album: bool
29 format: str | None
30 included_keys: list[str]
31 keys_only: bool | None
32 library: bool | None
33 summarize: bool | None
34
35
36 def tag_data(
37 lib: Library, args: Iterable[str], album: bool = False
38 ) -> Iterator[DataEmitter]:
39 query = []
40 for arg in args:
41 path = normpath(arg)
42 if os.path.isfile(syspath(path)):
43 yield tag_data_emitter(path)
44 else:
45 query.append(arg)
46
47 if query:
48 for item in lib.items(query):
49 yield tag_data_emitter(item.path)
50
51
52 def tag_fields() -> set[str]:
53 fields = set(mediafile.MediaFile.readable_fields())
54 fields.add("art")
55 return fields
56
57
58 def tag_data_emitter(path: bytes) -> DataEmitter:
59 def emitter(
60 included_keys: Literal["*"] | list[str],
61 ) -> tuple[JSONDict, LibModel]:
62 fields: set[str] | list[str]
63 if included_keys == "*":
64 fields = tag_fields()
65 else:
66 fields = included_keys
67 if "images" in fields:
68 # We can't serialize the image data.
69 fields.remove("images")
70 mf = mediafile.MediaFile(syspath(path))
71 tags: JSONDict = {}
72 for field in fields:
73 if field == "art":
74 tags[field] = mf.art is not None
75 else:
76 tags[field] = getattr(mf, field, None)
77
78 # create a temporary Item to take advantage of __format__
79 item = Item.from_path(syspath(path))
80
81 return tags, item
82
83 return emitter
84
85
86 def library_data(
87 lib: Library, args: Sequence[str], album: bool = False
88 ) -> Iterator[DataEmitter]:
89 for item in lib.albums(args) if album else lib.items(args):
90 yield library_data_emitter(item)
91
92
93 def library_data_emitter(model: LibModel) -> DataEmitter:
94 def emitter(
95 included_keys: Literal["*"] | list[str],
96 ) -> tuple[JSONDict, LibModel]:
97 data = dict(model.formatted(included_keys=included_keys))
98
99 return data, model
100
101 return emitter
102
103
104 def update_summary(summary: JSONDict, tags: JSONDict) -> JSONDict:
105 for key, value in tags.items():
106 if key not in summary:
107 summary[key] = value
108 elif summary[key] != value:
109 summary[key] = "[various]"
110 return summary
111
112
113 def print_data(
114 data: JSONDict, item: LibModel | None = None, fmt: str | None = None
115 ) -> None:
116 """Print, with optional formatting, the fields of a single element.
117
118 If no format string `fmt` is passed, the entries on `data` are printed one
119 in each line, with the format 'field: value'. If `fmt` is not `None`, the
120 `item` is printed according to `fmt`, using the `Item.__format__`
121 machinery.
122 """
123 if fmt:
124 # use fmt specified by the user
125 ui.print_(format(item, fmt))
126 return
127
128 path = displayable_path(item.path) if item else None
129 formatted = {}
130 for key, value in data.items():
131 if isinstance(value, list):
132 formatted[key] = "; ".join(value)
133 if value is not None:
134 formatted[key] = value
135
136 if len(formatted) == 0:
137 return
138
139 maxwidth = max(len(key) for key in formatted)
140
141 if path:
142 ui.print_(displayable_path(path))
143
144 for field in sorted(formatted):
145 value = formatted[field]
146 if isinstance(value, list):
147 value = "; ".join(value)
148 ui.print_(f"{field:>{maxwidth}}: {value}")
149
150
151 def print_data_keys(data: JSONDict, item: LibModel | None = None) -> None:
152 """Print only the keys (field names) for an item."""
153 path = displayable_path(item.path) if item else None
154 formatted = []
155 for key, value in data.items():
156 formatted.append(key)
157
158 if len(formatted) == 0:
159 return
160
161 if path:
162 ui.print_(displayable_path(path))
163
164 for field in sorted(formatted):
165 ui.print_(f" {field}")
166
167
168 class InfoPlugin(BeetsPlugin):
169 def commands(self) -> list[ui.Subcommand]:
170 cmd = ui.Subcommand("info", help="show file metadata")
171 cmd.func = self.run
172 cmd.parser.add_album_option()
173 cmd.parser.add_option(
174 "-l",
175 "--library",
176 action="store_true",
177 help="show library fields instead of tags",
178 )
179 cmd.parser.add_option(
180 "-s",
181 "--summarize",
182 action="store_true",
183 help="summarize the tags of all files",
184 )
185 cmd.parser.add_option(
186 "-i",
187 "--include-keys",
188 default=[],
189 action="append",
190 dest="included_keys",
191 help="comma separated list of keys to show",
192 )
193 cmd.parser.add_option(
194 "-k", "--keys-only", action="store_true", help="show only the keys"
195 )
196 cmd.parser.add_format_option(target="item")
197 return [cmd]
198
199 def run(self, lib: Library, opts: InfoCLIOpts, args: list[str]) -> None:
200 """Print tag info or library data for each file referenced by args.
201
202 Main entry point for the `beet info ARGS...` command.
203
204 If an argument is a path pointing to an existing file, then the tags
205 of that file are printed. All other arguments are considered
206 queries, and for each item matching all those queries the tags from
207 the file are printed.
208
209 If `opts.summarize` is true, the function merges all tags into one
210 dictionary and only prints that. If two files have different values
211 for the same tag, the value is set to '[various]'
212 """
213 if opts.library or opts.album:
214 data_collector = library_data
215 else:
216 data_collector = tag_data
217
218 included_keys = []
219 for keys in opts.included_keys:
220 included_keys.extend(keys.split(","))
221 # Drop path even if user provides it multiple times
222 included_keys = [k for k in included_keys if k != "path"]
223
224 first = True
225 summary: dict[str, Any] = {}
226 for data_emitter in data_collector(lib, args, album=opts.album):
227 try:
228 data, item = data_emitter(included_keys or "*")
229 except (mediafile.UnreadableFileError, OSError) as ex:
230 self._log.error("cannot read file: {}", ex)
231 continue
232
233 if opts.summarize:
234 update_summary(summary, data)
235 else:
236 if not first:
237 ui.print_()
238 if opts.keys_only:
239 print_data_keys(data, item)
240 else:
241 fmt = [opts.format][0] if opts.format else None
242 print_data(data, item, fmt)
243 first = False
244
245 if opts.summarize:
246 print_data(summary)