Debian Codegraph @

beetsplug/fish.py

raw
1 """This plugin generates tab completions for Beets commands for the Fish shell
2 <https://fishshell.com/>, including completions for Beets commands, plugin
3 commands, and option flags. Also generated are completions for all the album
4 and track fields, suggesting for example `genres:` or `album:` when querying the
5 Beets database. Completions for the *values* of those fields are not generated
6 by default but can be added via the `-e` / `--extravalues` flag. For example:
7 `beet fish -e genres -e albumartist`
8 """
9
10 from __future__ import annotations
11
12 import os
13 from operator import attrgetter
14 from typing import TYPE_CHECKING, Any, Protocol
15
16 from beets import library, plugins, ui
17 from beets.plugins import BeetsPlugin
18 from beets.ui import commands
19
20 if TYPE_CHECKING:
21 from collections.abc import Iterable, Sequence
22
23 from beets.library import Library
24
25
26 class FishCLIOpts(Protocol):
27 extravalues: list[str] | None
28 noFields: bool # noqa: N815
29 output: str
30
31
32 BL_NEED2 = """complete -c beet -n '__fish_beet_needs_command' {} {}\n"""
33 BL_USE3 = """complete -c beet -n '__fish_beet_using_command {}' {} {}\n"""
34 BL_SUBS = """complete -c beet -n '__fish_at_level {} ""' {} {}\n"""
35 BL_EXTRA3 = """complete -c beet -n '__fish_beet_use_extra {}' {} {}\n"""
36
37 HEAD = """
38 function __fish_beet_needs_command
39 set cmd (commandline -opc)
40 if test (count $cmd) -eq 1
41 return 0
42 end
43 return 1
44 end
45
46 function __fish_beet_using_command
47 set cmd (commandline -opc)
48 set needle (count $cmd)
49 if test $needle -gt 1
50 if begin test $argv[1] = $cmd[2];
51 and not contains -- $cmd[$needle] $FIELDS; end
52 return 0
53 end
54 end
55 return 1
56 end
57
58 function __fish_beet_use_extra
59 set cmd (commandline -opc)
60 set needle (count $cmd)
61 if test $argv[2] = $cmd[$needle]
62 return 0
63 end
64 return 1
65 end
66 """
67
68
69 class FishPlugin(BeetsPlugin):
70 def commands(self) -> list[ui.Subcommand]:
71 cmd = ui.Subcommand("fish", help="generate Fish shell tab completions")
72 cmd.func = self.run
73 cmd.parser.add_option(
74 "-f",
75 "--noFields",
76 action="store_true",
77 default=False,
78 help="omit album/track field completions",
79 )
80 cmd.parser.add_option(
81 "-e",
82 "--extravalues",
83 action="append",
84 type="choice",
85 choices=list(library.Item.all_keys() | library.Album.all_keys()),
86 help="include specified field *values* in completions",
87 )
88 cmd.parser.add_option(
89 "-o",
90 "--output",
91 default="~/.config/fish/completions/beet.fish",
92 help=(
93 "where to save the script. default: ~/.config/fish/completions"
94 ),
95 )
96 return [cmd]
97
98 def run(self, lib: Library, opts: FishCLIOpts, args: list[str]) -> None:
99 # Gather the commands from Beets core and its plugins.
100 # Collect the album and track fields.
101 # If specified, also collect the values for these fields.
102 # Make a giant string of all the above, formatted in a way that
103 # allows Fish to do tab completion for the `beet` command.
104
105 completion_file_path = os.path.expanduser(opts.output)
106 completion_dir = os.path.dirname(completion_file_path)
107
108 if completion_dir != "":
109 os.makedirs(completion_dir, exist_ok=True)
110
111 nobasicfields = opts.noFields # Do not complete for album/track fields
112 extravalues = opts.extravalues # e.g., Also complete artists names
113 beetcmds = sorted(
114 (commands.default_commands + plugins.commands()),
115 key=attrgetter("name"),
116 )
117 fields = sorted(library.Album.all_keys() | library.Item.all_keys())
118 # Collect commands, their aliases, and their help text
119 cmd_names_help = []
120 for cmd in beetcmds:
121 names = list(cmd.aliases)
122 names.append(cmd.name)
123 for name in names:
124 cmd_names_help.append((name, cmd.help))
125 # Concatenate the string
126 totstring = f"{HEAD}\n"
127 totstring += get_cmds_list([name[0] for name in cmd_names_help])
128 totstring += "" if nobasicfields else get_standard_fields(fields)
129 totstring += get_extravalues(lib, extravalues) if extravalues else ""
130 totstring += "\n# ====== setup basic beet completion =====\n\n"
131 totstring += get_basic_beet_options()
132 totstring += "\n# ====== setup field completion for subcommands =====\n"
133 totstring += get_subcommands(cmd_names_help, nobasicfields, extravalues)
134 # Set up completion for all the command options
135 totstring += get_all_commands(beetcmds)
136
137 with open(completion_file_path, "w") as fish_file:
138 fish_file.write(totstring)
139
140
141 def _escape(name: str) -> str:
142 # Escape ? in fish
143 if name == "?":
144 name = f"\\{name}"
145 return name
146
147
148 def get_cmds_list(cmds_names: Iterable[str]) -> str:
149 # Make a list of all Beets core & plugin commands
150 return f"set CMDS {' '.join(cmds_names)}\n\n"
151
152
153 def get_standard_fields(fields: Iterable[str]) -> str:
154 # Make a list of album/track fields and append with ':'
155 return f"set FIELDS {' '.join(f'{field}:' for field in fields)}\n\n"
156
157
158 def get_extravalues(lib: Library, extravalues: Sequence[str]) -> str:
159 # Make a list of all values from an album/track field.
160 # 'beet ls albumartist: <TAB>' yields completions for ABBA, Beatles, etc.
161 word = ""
162 values_set = get_set_of_values_for_field(lib, extravalues)
163 for fld in extravalues:
164 extraname = f"{fld.upper()}S"
165 word += f"set {extraname} {' '.join(sorted(values_set[fld]))}\n\n"
166 return word
167
168
169 def get_set_of_values_for_field(
170 lib: Library, fields: Sequence[str]
171 ) -> dict[str, set[Any]]:
172 # Get unique values from a specified album/track field
173 fields_dict: dict[str, set[str]] = {}
174 for each in fields:
175 fields_dict[each] = set()
176 for item in lib.items():
177 for field in fields:
178 fields_dict[field].add(wrap(item[field]))
179 return fields_dict
180
181
182 def get_basic_beet_options() -> str:
183 return (
184 BL_NEED2.format("-l format-item", "-f -d 'print with custom format'")
185 + BL_NEED2.format("-l format-album", "-f -d 'print with custom format'")
186 + BL_NEED2.format(
187 "-s l -l library", "-F -r -d 'library database file to use'"
188 )
189 + BL_NEED2.format(
190 "-s d -l directory", "-F -r -d 'destination music directory'"
191 )
192 + BL_NEED2.format(
193 "-s v -l verbose", "-f -d 'print debugging information'"
194 )
195 + BL_NEED2.format(
196 "-s c -l config", "-F -r -d 'path to configuration file'"
197 )
198 + BL_NEED2.format(
199 "-s h -l help", "-f -d 'print this help message and exit'"
200 )
201 )
202
203
204 def get_subcommands(
205 cmd_name_and_help: Iterable[tuple[str, str]],
206 nobasicfields: bool,
207 extravalues: Iterable[str] | None,
208 ) -> str:
209 # Formatting for Fish to complete our fields/values
210 word = ""
211 for cmdname, cmdhelp in cmd_name_and_help:
212 cmdname = _escape(cmdname)
213
214 word += f"\n# ------ fieldsetups for {cmdname} -------\n"
215 word += BL_NEED2.format(
216 f"-a {cmdname}", f"-f -d {wrap(clean_whitespace(cmdhelp))}"
217 )
218
219 if nobasicfields is False:
220 word += BL_USE3.format(
221 cmdname, f"-a {wrap('$FIELDS')}", f"-d {wrap('fieldname')}"
222 )
223
224 if extravalues:
225 for f in extravalues:
226 setvar = wrap(f"${f.upper()}S")
227 word += " ".join(
228 BL_EXTRA3.format(
229 f"{cmdname} {f}:", f"-f -A -a {setvar}", f"-d {wrap(f)}"
230 ).split()
231 )
232 word += "\n"
233 return word
234
235
236 def get_all_commands(beetcmds: Sequence[ui.Subcommand]) -> str:
237 # Formatting for Fish to complete command options
238 word = ""
239 for cmd in beetcmds:
240 names = list(cmd.aliases)
241 names.append(cmd.name)
242 for name in names:
243 name = _escape(name)
244
245 word += f"\n\n\n# ====== completions for {name} =====\n"
246
247 for option in cmd.parser._get_all_options()[1:]:
248 cmd_l = (
249 f" -l {option._long_opts[0].replace('--', '')}"
250 if option._long_opts
251 else ""
252 )
253 cmd_s = (
254 f" -s {option._short_opts[0].replace('-', '')}"
255 if option._short_opts
256 else ""
257 )
258 cmd_need_arg = " -r " if option.nargs in [1] else ""
259 cmd_helpstr = (
260 f" -d {wrap(' '.join(option.help.split()))}"
261 if option.help
262 else ""
263 )
264 cmd_arglist = (
265 f" -a {wrap(' '.join(option.choices))}"
266 if option.choices
267 else ""
268 )
269
270 word += " ".join(
271 BL_USE3.format(
272 name,
273 f"{cmd_need_arg}{cmd_s}{cmd_l} {cmd_arglist}",
274 cmd_helpstr,
275 ).split()
276 )
277 word += "\n"
278
279 word = word + BL_USE3.format(
280 name, "-s h -l help", f"-d {wrap('print help')}"
281 )
282 return word
283
284
285 def clean_whitespace(word: str) -> str:
286 # Remove excess whitespace and tabs in a string
287 return " ".join(word.split())
288
289
290 def wrap(word: str) -> str:
291 # Need " or ' around strings but watch out if they're in the string
292 sptoken = '"'
293 if '"' in word and ("'") in word:
294 word.replace('"', sptoken)
295 return f'"{word}"'
296
297 tok = '"' if "'" in word else "'"
298 return f"{tok}{word}{tok}"