Debian Codegraph @

beetsplug/bareasc.py

raw
1 #
2 # This module is adapted from Fuzzy in accordance to the licence of
3 # that module
4
5 """Provides a bare-ASCII matching query."""
6
7 from __future__ import annotations
8
9 from typing import TYPE_CHECKING, Any, Protocol
10
11 from unidecode import unidecode
12
13 from beets import ui
14 from beets.dbcore.query import StringFieldQuery
15 from beets.plugins import BeetsPlugin
16 from beets.ui import print_
17
18 if TYPE_CHECKING:
19 from beets.dbcore.query import FieldQuery
20 from beets.library import Library
21
22
23 class BareascCLIOpts(Protocol):
24 album: bool
25
26
27 class BareascQuery(StringFieldQuery[str]):
28 """Compare items using bare ASCII, without accents etc."""
29
30 @classmethod
31 def string_match(cls, pattern: str, val: str) -> bool:
32 """Convert both pattern and string to plain ASCII before matching.
33
34 If pattern is all lower case, also convert string to lower case so
35 match is also case insensitive
36 """
37 # smartcase
38 if pattern.islower():
39 val = val.lower()
40 pattern = unidecode(pattern)
41 val = unidecode(val)
42 return pattern in val
43
44 def col_clause(self) -> tuple[str, list[str]]:
45 """Compare ascii version of the pattern."""
46 clause = f"unidecode({self.field})"
47 if self.pattern.islower():
48 clause = f"lower({clause})"
49
50 return rf"{clause} LIKE ? ESCAPE '\'", [f"%{unidecode(self.pattern)}%"]
51
52
53 class BareascPlugin(BeetsPlugin):
54 """Plugin to provide bare-ASCII option for beets matching."""
55
56 def __init__(self) -> None:
57 """Default prefix for selecting bare-ASCII matching is #."""
58 super().__init__()
59 self.config.add({"prefix": "#"})
60
61 def queries(self) -> dict[str, type[FieldQuery[Any]]]:
62 """Register bare-ASCII matching."""
63 prefix = self.config["prefix"].as_str()
64 return {prefix: BareascQuery}
65
66 def commands(self) -> list[ui.Subcommand]:
67 """Add bareasc command as unidecode version of 'list'."""
68 cmd = ui.Subcommand(
69 "bareasc", help="unidecode version of beet list command"
70 )
71 cmd.parser.set_usage(
72 cmd.parser.get_usage().rstrip()
73 + "\nExample: %prog -f '$album: $title' artist:beatles"
74 )
75 cmd.parser.add_all_common_options()
76 cmd.func = self.unidecode_list
77 return [cmd]
78
79 def unidecode_list(
80 self, lib: Library, opts: BareascCLIOpts, args: list[str]
81 ) -> None:
82 """Emulate normal 'list' command but with unidecode output."""
83 album = opts.album
84 # Copied from commands.py - list_items
85 if album:
86 for album_obj in lib.albums(args):
87 bare = unidecode(str(album_obj))
88 print_(bare)
89 else:
90 for item in lib.items(args):
91 bare = unidecode(str(item))
92 print_(bare)