mirror of
https://github.com/beetbox/beets.git
synced 2025-12-24 17:43:52 +01:00
Implement __format__ on Album and Item
Cut the need to format manually (and often incorrectly) when logging by implementing the __format__ magic method (see PEP 3101) on LibModel (the parent class of Album & Item). Based on a discussion in PR #1262
This commit is contained in:
parent
258b63c566
commit
73d200184b
2 changed files with 37 additions and 0 deletions
|
|
@ -247,6 +247,21 @@ class LibModel(dbcore.Model):
|
|||
super(LibModel, self).add(lib)
|
||||
plugins.send('database_change', lib=self._db)
|
||||
|
||||
def __format__(self, spec):
|
||||
if not spec:
|
||||
spec = beets.config[self._format_config_key].get(unicode)
|
||||
result = self.evaluate_template(spec)
|
||||
if isinstance(spec, bytes):
|
||||
return result.encode('utf8')
|
||||
else:
|
||||
return result
|
||||
|
||||
def __str__(self):
|
||||
return format(self).encode('utf8')
|
||||
|
||||
def __unicode__(self):
|
||||
return format(self)
|
||||
|
||||
|
||||
class FormattedItemMapping(dbcore.db.FormattedMapping):
|
||||
"""Add lookup for album-level fields.
|
||||
|
|
@ -383,6 +398,8 @@ class Item(LibModel):
|
|||
|
||||
_sorts = {'artist': SmartArtistSort}
|
||||
|
||||
_format_config_key = 'list_format_item'
|
||||
|
||||
@classmethod
|
||||
def _getters(cls):
|
||||
getters = plugins.item_field_getters()
|
||||
|
|
@ -791,6 +808,8 @@ class Album(LibModel):
|
|||
"""List of keys that are set on an album's items.
|
||||
"""
|
||||
|
||||
_format_config_key = 'list_format_album'
|
||||
|
||||
@classmethod
|
||||
def _getters(cls):
|
||||
# In addition to plugin-provided computed fields, also expose
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# This file is part of beets.
|
||||
# Copyright 2015, Adrian Sampson.
|
||||
#
|
||||
|
|
@ -1087,6 +1088,23 @@ class TemplateTest(_common.LibTestCase):
|
|||
self.album.store()
|
||||
self.assertEqual(self.i.evaluate_template('$foo'), 'baz')
|
||||
|
||||
def test_album_and_item_format(self):
|
||||
config['list_format_album'] = u'foö $foo'
|
||||
album = beets.library.Album()
|
||||
album.foo = 'bar'
|
||||
album.tagada = 'togodo'
|
||||
self.assertEqual(u"{0}".format(album), u"foö bar")
|
||||
self.assertEqual(u"{0:$tagada}".format(album), u"togodo")
|
||||
self.assertEqual(unicode(album), u"foö bar")
|
||||
self.assertEqual(str(album), b"fo\xc3\xb6 bar")
|
||||
|
||||
config['list_format_item'] = 'bar $foo'
|
||||
item = beets.library.Item()
|
||||
item.foo = 'bar'
|
||||
item.tagada = 'togodo'
|
||||
self.assertEqual("{0}".format(item), "bar bar")
|
||||
self.assertEqual("{0:$tagada}".format(item), "togodo")
|
||||
|
||||
|
||||
class UnicodePathTest(_common.LibTestCase):
|
||||
def test_unicode_path(self):
|
||||
|
|
|
|||
Loading…
Reference in a new issue