Debian Codegraph @

beetsplug/inline.py

raw
1 """Allows inline path template customization code in the config file."""
2
3 from __future__ import annotations
4
5 import itertools
6 import traceback
7 from typing import TYPE_CHECKING, Any
8
9 from beets import config
10 from beets.plugins import BeetsPlugin
11
12 if TYPE_CHECKING:
13 from collections.abc import Callable
14
15 from beets.library import LibModel
16
17 from ._typing import JSONDict
18
19
20 FUNC_NAME = "__INLINE_FUNC__"
21
22
23 class InlineError(Exception):
24 """Raised when a runtime error occurs in an inline expression."""
25
26 def __init__(self, code: str, exc: BaseException) -> None:
27 super().__init__(
28 f"error in inline path field code:\n{code}\n{type(exc).__name__}: {exc}"
29 )
30
31
32 def _compile_func(body: str, args: str = "") -> Callable[..., Any]:
33 """Given Python code for a function body, return a compiled
34 callable that invokes that code.
35 """
36 body = body.replace("\n", "\n ")
37 body = f"def {FUNC_NAME}({args}):\n {body}"
38 code = compile(body, "inline", "exec")
39 env: JSONDict = {}
40 eval(code, env)
41 return env[FUNC_NAME]
42
43
44 class InlinePlugin(BeetsPlugin):
45 def __init__(self) -> None:
46 super().__init__()
47
48 config.add(
49 {
50 "pathfields": {}, # Legacy name.
51 "item_fields": {},
52 "album_fields": {},
53 }
54 )
55
56 # Item fields.
57 for key, view in itertools.chain(
58 config["item_fields"].items(), config["pathfields"].items()
59 ):
60 self._log.debug("adding item field {}", key)
61 func = self.compile_inline(view.as_str(), False, key)
62 if func is not None:
63 self.template_fields[key] = func
64
65 # Album fields.
66 for key, view in config["album_fields"].items():
67 self._log.debug("adding album field {}", key)
68 func = self.compile_inline(view.as_str(), True, key)
69 if func is not None:
70 self.album_template_fields[key] = func
71
72 def compile_inline(
73 self, python_code: str, album: bool, field_name: str
74 ) -> Callable[[LibModel], Any] | None:
75 """Given a Python expression or function body, compile it as a path
76 field function. The returned function takes a single argument, an
77 Item, and returns a Unicode string. If the expression cannot be
78 compiled, then an error is logged and this function returns None.
79 """
80 # First, try compiling as a single function.
81 try:
82 code = compile(f"({python_code})", "inline", "eval")
83 except SyntaxError:
84 # Fall back to a function body.
85 try:
86 func = _compile_func(python_code, args="db_obj")
87 except SyntaxError:
88 self._log.error(
89 "syntax error in inline field definition:\n{}",
90 traceback.format_exc(),
91 )
92 return None
93 else:
94 is_expr = False
95 else:
96 is_expr = True
97
98 def _dict_for(obj: LibModel) -> JSONDict:
99 out = {}
100 for key in obj.keys(computed=False):
101 if key == field_name:
102 continue
103 out[key] = obj._get(key)
104
105 if album:
106 out["items"] = list(obj.items())
107 return out
108
109 if is_expr:
110 # For expressions, just evaluate and return the result.
111 def _expr_func(obj: LibModel) -> Any:
112 values = _dict_for(obj)
113 values["db_obj"] = obj
114 try:
115 return eval(code, values)
116 except Exception as exc:
117 raise InlineError(python_code, exc)
118
119 return _expr_func
120
121 # For function bodies, invoke the function with values as global
122 # variables.
123 def _func_func(obj: LibModel) -> Any:
124 old_globals = dict(func.__globals__)
125 func.__globals__.update(_dict_for(obj))
126 try:
127 return func(obj)
128 except Exception as exc:
129 raise InlineError(python_code, exc)
130 finally:
131 func.__globals__.clear()
132 func.__globals__.update(old_globals)
133
134 return _func_func