Debian Codegraph @

beetsplug/substitute.py

raw
1 """The substitute plugin module.
2
3 Uses user-specified substitution rules to canonicalize names for path formats.
4 """
5
6 import re
7
8 from beets.plugins import BeetsPlugin
9
10
11 class Substitute(BeetsPlugin):
12 """The substitute plugin class.
13
14 Create a template field function that substitute the given field with the
15 given substitution rules. ``rules`` must be a list of (pattern,
16 replacement) pairs.
17 """
18
19 def tmpl_substitute(self, text: str) -> str:
20 """Do the actual replacing."""
21 if text:
22 for pattern, replacement in self.substitute_rules:
23 text = pattern.sub(replacement, text)
24 return text
25 return ""
26
27 def __init__(self) -> None:
28 """Initialize the substitute plugin.
29
30 Get the configuration, register template function and create list of
31 substitute rules.
32 """
33 super().__init__()
34 self.template_funcs["substitute"] = self.tmpl_substitute
35 self.substitute_rules = [
36 (re.compile(key, flags=re.IGNORECASE), value)
37 for key, value in self.config.flatten().items()
38 ]