Turn the actual query into a macro

This commit is contained in:
Benson Chu 2026-04-04 13:38:11 -05:00
parent ddcbe8fbab
commit a5ccea6b33
3 changed files with 29 additions and 23 deletions

View file

@ -59,7 +59,10 @@ beetslabels:
# labels:
playlists:
- name: exercise
query: ["effortless"]
# and: "label:a label:b"
# or: "label:a , label:b"
# in the future? concat: ["label:a", "label:b"]
query: "label:effortless"
smartplaylist:
relative_to: ~/Music/0beets_playlists

View file

@ -16,7 +16,7 @@ Prefixes = dict[str, FieldQueryType]
import re
from .labels import HasLabelQuery, labels_command, LABELS_FIELD_NAME, LabelValueSort
from .playlists import initialize_playlists, InPlaylistQuery, PlaylistValueSort
from .playlists import initialize_playlists, expand_playlist_query, valid_playlist, PlaylistValueSort
class LabelValueSortsDict(dict):
"""Custom dict that returns LabelValueSort for any label:* key."""
@ -46,6 +46,22 @@ def parse_sorted_query_override(
"""Given a list of strings, create the `Query` and `Sort` that they
represent.
"""
# First, expand any playlist: macros
expanded_parts = []
for part in parts:
if part.startswith('playlist:') and not re.match(r"[+-]$", part):
playlist_name = part[len("playlist:"):]
if valid_playlist(playlist_name):
expanded_parts.extend(expand_playlist_query(playlist_name))
else:
# Unknown playlist, just let it go through
expanded_parts.append(part)
else:
expanded_parts.append(part)
parts = expanded_parts
# Separate query token and sort token.
query_parts = []
sort_parts = []
@ -94,7 +110,6 @@ class BeetsLabelsPlugin(BeetsPlugin):
def __init__(self):
super().__init__()
self.item_queries = {"label": HasLabelQuery}
self.item_queries = {"playlist": InPlaylistQuery}
playlists_config = self.config['playlists'].get()
initialize_playlists(playlists_config)

View file

@ -10,28 +10,16 @@ playlist_config = {}
def initialize_playlists(playlists):
for playlist in playlists:
playlist_config[playlist["name"]] = \
playlist["query"]
pl_name = playlist["name"]
query = [playlist["query"], ",", f"label:{pl_name}"]
playlist_config[pl_name] = query
class InPlaylistQuery(FieldQuery):
def __init__(self, _, pattern: str, __):
super().__init__(LABELS_FIELD_NAME, pattern, False)
def valid_playlist(playlist_name):
return playlist_name in playlist_config
@classmethod
def value_match(self, pattern, jsonstr):
if jsonstr is not None:
playlist = pattern
labels = json.loads(jsonstr)
if playlist in labels:
# This song has been explicitly added to the playlist
return True
for label in playlist_config[playlist]:
if label in labels:
return True
return False
def expand_playlist_query(playlist_name):
print(playlist_config[playlist_name])
return playlist_config[playlist_name]
class PlaylistValueSort(SlowFieldSort):
def __init__(self, field, ascending=True, case_insensitive=True):