Debian Codegraph @

beetsplug/hook.py

raw
1 """Allows custom commands to be run when an event is emitted by beets"""
2
3 from __future__ import annotations
4
5 import os
6 import shlex
7 import string
8 import subprocess
9 from typing import TYPE_CHECKING, Any
10
11 from beets.events import ALL_EVENTS
12 from beets.plugins import BeetsPlugin
13
14 if TYPE_CHECKING:
15 from beets.events import EventType
16
17
18 class BytesToStrFormatter(string.Formatter):
19 """A variant of `string.Formatter` that converts `bytes` to `str`."""
20
21 def convert_field(self, value: Any, conversion: str | None) -> Any:
22 """Converts the provided value given a conversion type.
23
24 This method decodes the converted value using the formatter's coding.
25 """
26 converted = super().convert_field(value, conversion)
27
28 if isinstance(converted, bytes):
29 return os.fsdecode(converted)
30
31 return converted
32
33
34 class HookPlugin(BeetsPlugin):
35 """Allows custom commands to be run when an event is emitted by beets"""
36
37 def __init__(self) -> None:
38 super().__init__()
39
40 self.config.add({"hooks": []})
41
42 hooks = self.config["hooks"].get(list)
43
44 for hook_index in range(len(hooks)):
45 hook = self.config["hooks"][hook_index]
46
47 hook_event: EventType = hook["event"].as_choice(choices=ALL_EVENTS)
48 hook_command = hook["command"].as_str()
49
50 self.create_and_register_hook(hook_event, hook_command)
51
52 def create_and_register_hook(self, event: EventType, command: str) -> None:
53 def hook_function(**kwargs) -> None:
54 if command is None or len(command) == 0:
55 self._log.error('invalid command "{}"', command)
56 return
57
58 # For backwards compatibility, use a string formatter that decodes
59 # bytes (in particular, paths) to strings.
60 formatter = BytesToStrFormatter()
61 command_pieces = [
62 formatter.format(piece, event=event, **kwargs)
63 for piece in shlex.split(command)
64 ]
65
66 self._log.debug(
67 'running command "{}" for event {}',
68 " ".join(command_pieces),
69 event,
70 )
71
72 try:
73 subprocess.check_call(command_pieces)
74 except subprocess.CalledProcessError as exc:
75 self._log.error(
76 "hook for {} exited with status {.returncode}", event, exc
77 )
78 except OSError as exc:
79 self._log.error("hook for {} failed: {}", event, exc)
80
81 self.register_listener(event, hook_function) # type: ignore[arg-type]