Debian Codegraph @

beetsplug/limit.py

raw
1 """Adds head/tail functionality to list/ls.
2
3 1. Implemented as `lslimit` command with `--head` and `--tail` options. This is
4 the idiomatic way to use this plugin.
5 2. Implemented as query prefix `<` for head functionality only. This is the
6 composable way to use the plugin (plays nicely with anything that uses the
7 query language).
8 """
9
10 from __future__ import annotations
11
12 from collections import deque
13 from itertools import islice
14 from typing import TYPE_CHECKING, Protocol
15
16 from beets.dbcore import FieldQuery
17 from beets.plugins import BeetsPlugin
18 from beets.ui import Subcommand, print_
19 from beets.util.deprecation import deprecate_for_user
20
21 if TYPE_CHECKING:
22 from collections.abc import Iterable
23
24 from beets.library import LibModel, Library
25
26 from ._typing import JSONDict
27
28
29 class LsLimitCLIOpts(Protocol):
30 album: bool
31 head: int | None
32 tail: int | None
33
34
35 def lslimit(lib: Library, opts: LsLimitCLIOpts, args: list[str]) -> None:
36 """Query command with head/tail."""
37
38 if (opts.head is not None) and (opts.tail is not None):
39 raise ValueError("Only use one of --head and --tail")
40 if (opts.head or opts.tail or 0) < 0:
41 raise ValueError("Limit value must be non-negative")
42
43 objs: Iterable[LibModel]
44 if opts.album:
45 objs = lib.albums(args)
46 else:
47 objs = lib.items(args)
48
49 if opts.head is not None:
50 objs = islice(objs, opts.head)
51 elif opts.tail is not None:
52 objs = deque(objs, opts.tail)
53
54 for obj in objs:
55 print_(format(obj))
56
57
58 lslimit_cmd = Subcommand("lslimit", help="query with optional head or tail")
59
60 lslimit_cmd.parser.add_option(
61 "--head", action="store", type="int", default=None
62 )
63
64 lslimit_cmd.parser.add_option(
65 "--tail", action="store", type="int", default=None
66 )
67
68 lslimit_cmd.parser.add_all_common_options()
69 lslimit_cmd.func = lslimit
70
71
72 class LimitPlugin(BeetsPlugin):
73 """Query limit functionality via command and query prefix."""
74
75 def __init__(self, *args, **kwargs) -> None:
76 super().__init__(*args, **kwargs)
77 deprecate_for_user(
78 self._log, "LimitPlugin ('limit')", "'beet ls -l <number>'"
79 )
80
81 def commands(self) -> list[Subcommand]:
82 """Expose `lslimit` subcommand."""
83 return [lslimit_cmd]
84
85 def queries(self) -> JSONDict:
86 class HeadQuery(FieldQuery):
87 """This inner class pattern allows the query to track state."""
88
89 n = 0
90 N = None
91
92 def __init__(self, *args, **kwargs) -> None:
93 """Force the query to be slow so that 'value_match' is called."""
94 super().__init__(*args, **kwargs)
95 self.fast = False
96
97 @classmethod
98 def value_match(cls, pattern: str, value: str) -> bool:
99 if cls.N is None:
100 cls.N = int(pattern)
101 if cls.N < 0:
102 raise ValueError("Limit value must be non-negative")
103 cls.n += 1
104 return cls.n <= cls.N
105
106 return {"<": HeadQuery}