Debian Codegraph @

beetsplug/the.py

raw
1 """Moves patterns in path formats (suitable for moving articles)."""
2
3 import re
4
5 from beets.plugins import BeetsPlugin
6
7 __author__ = "[email protected]"
8 __version__ = "1.1"
9
10 PATTERN_THE = "^the\\s"
11 PATTERN_A = "^[a][n]?\\s"
12 FORMAT = "{}, {}"
13
14
15 class ThePlugin(BeetsPlugin):
16 patterns: list[str]
17
18 def __init__(self) -> None:
19 super().__init__()
20
21 self.template_funcs["the"] = self.the_template_func
22
23 self.config.add(
24 {
25 "the": True,
26 "a": True,
27 "format": "{}, {}",
28 "strip": False,
29 "patterns": [],
30 }
31 )
32
33 self.patterns = self.config["patterns"].as_str_seq()
34 for p in self.patterns:
35 if p:
36 try:
37 re.compile(p)
38 except re.error:
39 self._log.error("invalid pattern: {}", p)
40 else:
41 if not (p.startswith("^") or p.endswith("$")):
42 self._log.warning(
43 'warning: "{}" will not match string start/end', p
44 )
45 if self.config["a"]:
46 self.patterns = [PATTERN_A, *self.patterns]
47 if self.config["the"]:
48 self.patterns = [PATTERN_THE, *self.patterns]
49 if not self.patterns:
50 self._log.warning("no patterns defined!")
51
52 def unthe(self, text: str, pattern: str) -> str:
53 """Moves pattern in the path format string or strips it
54
55 text -- text to handle
56 pattern -- regexp pattern (case ignore is already on)
57 strip -- if True, pattern will be removed
58 """
59 if text:
60 m = re.compile(pattern, flags=re.IGNORECASE)
61 try:
62 t = m.findall(text)[0]
63 except IndexError:
64 return text
65 else:
66 r = re.sub(m, "", text).strip()
67 if self.config["strip"]:
68 return r
69 fmt = self.config["format"].as_str()
70 return fmt.format(r, t.strip()).strip()
71 else:
72 return ""
73
74 def the_template_func(self, text: str) -> str:
75 if not self.patterns:
76 return text
77 if text:
78 for p in self.patterns:
79 r = self.unthe(text, p)
80 if r != text:
81 self._log.debug('"{}" -> "{}"', text, r)
82 break
83 return r
84 return ""