"Modify" for non-string values

Added the possibility to modify float, integer e bool values (using explicitly true/false)
This commit is contained in:
Lucas Duailibe 2013-05-05 20:22:38 -03:00
parent 9d6e25175e
commit c7f4b8a095
2 changed files with 25 additions and 2 deletions

View file

@ -159,6 +159,28 @@ ITEM_DEFAULT_FIELDS = ARTIST_DEFAULT_FIELDS + ALBUM_DEFAULT_FIELDS + \
# Special path format key.
PF_KEY_DEFAULT = 'default'
# Convert 'true' and 'false' to correspondent boolean
def _str_to_bool(value):
if value.lower() == 'true':
return True
if value.lower() == 'false':
return False
raise ValueError('could not convert string to bool: {0}'.format(value))
# Mapping the correspondent Python constructor to SQLite field types
TYPE_MAPPING = {
'int': int,
'bool': _str_to_bool,
'real': float,
}
# Convert a string (from user input) to the correct Python type
def _convert_type(fields, key, value):
sqlite_type = [f[1] for f in fields if f[0] == key][0]
if value and sqlite_type in TYPE_MAPPING:
python_type = TYPE_MAPPING[sqlite_type]
return python_type(value)
return value
# Logger.
log = logging.getLogger('beets')
@ -642,7 +664,7 @@ class AnyFieldQuery(CollectionQuery):
if subq.match(item):
return True
return False
class MutableCollectionQuery(CollectionQuery):
"""A collection query whose subqueries may be modified after the
query is initialized.

View file

@ -989,13 +989,14 @@ default_commands.append(version_cmd)
def modify_items(lib, mods, query, write, move, album, confirm):
"""Modifies matching items according to key=value assignments."""
# Parse key=value specifications into a dictionary.
fields = library.ALBUM_FIELDS if album else library.ITEM_FIELDS
allowed_keys = library.ALBUM_KEYS if album else library.ITEM_KEYS_WRITABLE
fsets = {}
for mod in mods:
key, value = mod.split('=', 1)
if key not in allowed_keys:
raise ui.UserError('"%s" is not a valid field' % key)
fsets[key] = value
fsets[key] = library._convert_type(fields, key, value)
# Get the items to modify.
items, albums = _do_query(lib, query, album, False)