Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow multiple plugins to provide getters for one field #5003

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions beets/dbcore/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,8 +430,12 @@ def _get(self, key, default: Any = None, raise_: bool = False):
"""
getters = self._getters()
if key in getters: # Computed.
return getters[key](self)
elif key in self._fields: # Fixed.
# Use the result of the first getter that returns a value.
for getter in getters[key]:
result = getter(self)
if result is not None:
return result
if key in self._fields: # Fixed.
if key in self._values_fixed:
return self._values_fixed[key]
else:
Expand Down
8 changes: 4 additions & 4 deletions beets/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,8 +662,8 @@ def _cached_album(self, album):
@classmethod
def _getters(cls):
getters = plugins.item_field_getters()
getters["singleton"] = lambda i: i.album_id is None
getters["filesize"] = Item.try_filesize # In bytes.
getters["singleton"] = [lambda i: i.album_id is None]
getters["filesize"] = [Item.try_filesize] # In bytes.
return getters

@classmethod
Expand Down Expand Up @@ -1242,8 +1242,8 @@ def _getters(cls):
# In addition to plugin-provided computed fields, also expose
# the album's directory as `path`.
getters = plugins.album_field_getters()
getters["path"] = Album.item_dir
getters["albumtotal"] = Album._albumtotal
getters["path"] = [Album.item_dir]
getters["albumtotal"] = [Album._albumtotal]
return getters

def items(self):
Expand Down
8 changes: 5 additions & 3 deletions beets/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

import beets
from beets import logging
from beets.util.dict_utils import merge_list_dicts

PLUGIN_NAMESPACE = "beetsplug"

Expand Down Expand Up @@ -305,8 +306,9 @@ def find_plugins():
return list(_instances.values())

load_plugins()
classes = sorted(_classes, key=lambda _class: _class.__name__)
plugins = []
for cls in _classes:
for cls in classes:
# Only instantiate each plugin class once.
if cls not in _instances:
_instances[cls] = cls()
Expand Down Expand Up @@ -451,7 +453,7 @@ def item_field_getters():
funcs = {}
for plugin in find_plugins():
if plugin.template_fields:
funcs.update(plugin.template_fields)
merge_list_dicts(plugin.template_fields, funcs)
return funcs


Expand All @@ -460,7 +462,7 @@ def album_field_getters():
funcs = {}
for plugin in find_plugins():
if plugin.album_template_fields:
funcs.update(plugin.album_template_fields)
merge_list_dicts(plugin.album_template_fields, funcs)
return funcs


Expand Down
15 changes: 15 additions & 0 deletions beets/util/dict_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Utility functions for working with dictionaries."""


def merge_list_dicts(source, target):
"""Merges the value or list from the source dict into target dict list.

If a list already exists for a given key in the target dict,
the new item is appended or the two lists are merged.
"""
for key, value in source.items():
value_list = value if isinstance(value, list) else [value]
if key in target:
target[key] = target[key] + value_list
else:
target[key] = value_list
5 changes: 2 additions & 3 deletions beetsplug/advancedrewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,12 @@ def rewriter(field, rules):
"""

def fieldfunc(item):
value = item._values_fixed[field]
for query, replacement in rules:
if query.match(item):
# Rewrite activated.
return replacement
# Not activated; return original value.
return value
# Not activated; return None.
return None

return fieldfunc

Expand Down
4 changes: 2 additions & 2 deletions beetsplug/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ def fieldfunc(item):
if pattern.match(value.lower()):
# Rewrite activated.
return replacement
# Not activated; return original value.
return value
# Not activated; return None.
return None

return fieldfunc

Expand Down
5 changes: 5 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,11 @@ Bug fixes:
a null path that can't be removed.
* Fix bug where empty artist and title fields would return None instead of an
empty list in the discord plugin. :bug:`4973`
* Fix a bug where it wasn't possible for multiple plugins to define replacement
functions for the same field.
For example, it wasn't possible to have both `rewrite` and `advancedrewrite`
rules for the same field.
:bug:`5002`

For packagers:

Expand Down
2 changes: 1 addition & 1 deletion test/test_dbcore.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ class DatabaseFixtureTwoModels(dbcore.Database):
class ModelFixtureWithGetters(dbcore.Model):
@classmethod
def _getters(cls):
return {"aComputedField": (lambda s: "thing")}
return {"aComputedField": [lambda s: "thing"]}

def _template_funcs(self):
return {}
Expand Down
2 changes: 1 addition & 1 deletion test/test_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -917,7 +917,7 @@ def setUp(self):
def field_getters():
getters = {}
for key, value in self._tv_map.items():
getters[key] = lambda _: value
getters[key] = [lambda _: value]
return getters

self.old_field_getters = plugins.item_field_getters
Expand Down
Loading