desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Ensure that all string attributes on this object, and the constituent `TrackInfo` objects, are decoded to Unicode.'
def decode(self, codec='utf-8'):
for fld in ['album', 'artist', 'albumtype', 'label', 'artist_sort', 'catalognum', 'script', 'language', 'country', 'albumstatus', 'albumdisambig', 'artist_credit', 'media']: value = getattr(self, fld) if isinstance(value, bytes): setattr(self, fld, value.decode(codec, 'ignore')) if s...
'Ensure that all string attributes on this object are decoded to Unicode.'
def decode(self, codec='utf-8'):
for fld in ['title', 'artist', 'medium', 'artist_sort', 'disctitle', 'artist_credit', 'media']: value = getattr(self, fld) if isinstance(value, bytes): setattr(self, fld, value.decode(codec, 'ignore'))
'A dictionary from keys to floating-point weights.'
@LazyClassProperty def _weights(cls):
weights_view = config['match']['distance_weights'] weights = {} for key in weights_view.keys(): weights[key] = weights_view[key].as_number() return weights
'Return a weighted and normalized distance across all penalties.'
@property def distance(self):
dist_max = self.max_distance if dist_max: return (self.raw_distance / self.max_distance) return 0.0
'Return the maximum distance penalty (normalization factor).'
@property def max_distance(self):
dist_max = 0.0 for (key, penalty) in self._penalties.items(): dist_max += (len(penalty) * self._weights[key]) return dist_max
'Return the raw (denormalized) distance.'
@property def raw_distance(self):
dist_raw = 0.0 for (key, penalty) in self._penalties.items(): dist_raw += (sum(penalty) * self._weights[key]) return dist_raw
'Return a list of (key, dist) pairs, with `dist` being the weighted distance, sorted from highest to lowest. Does not include penalties with a zero value.'
def items(self):
list_ = [] for key in self._penalties: dist = self[key] if dist: list_.append((key, dist)) return sorted(list_, key=(lambda key_and_dist: ((- key_and_dist[1]), key_and_dist[0])))
'Returns the weighted distance for a named penalty.'
def __getitem__(self, key):
dist = (sum(self._penalties[key]) * self._weights[key]) dist_max = self.max_distance if dist_max: return (dist / dist_max) return 0.0
'Adds all the distance penalties from `dist`.'
def update(self, dist):
if (not isinstance(dist, Distance)): raise ValueError(u'`dist` must be a Distance object, not {0}'.format(type(dist))) for (key, penalties) in dist._penalties.items(): self._penalties.setdefault(key, []).extend(penalties)
'Returns True if `value1` is equal to `value2`. `value1` may be a compiled regular expression, in which case it will be matched against `value2`.'
def _eq(self, value1, value2):
if isinstance(value1, re._pattern_type): return bool(value1.match(value2)) return (value1 == value2)
'Adds a distance penalty. `key` must correspond with a configured weight setting. `dist` must be a float between 0.0 and 1.0, and will be added to any existing distance penalties for the same key.'
def add(self, key, dist):
if (not (0.0 <= dist <= 1.0)): raise ValueError(u'`dist` must be between 0.0 and 1.0, not {0}'.format(dist)) self._penalties.setdefault(key, []).append(dist)
'Adds a distance penalty of 1.0 if `value` doesn\'t match any of the values in `options`. If an option is a compiled regular expression, it will be considered equal if it matches against `value`.'
def add_equality(self, key, value, options):
if (not isinstance(options, (list, tuple))): options = [options] for opt in options: if self._eq(opt, value): dist = 0.0 break else: dist = 1.0 self.add(key, dist)
'Adds a distance penalty of 1.0 if `expr` evaluates to True, or 0.0.'
def add_expr(self, key, expr):
if expr: self.add(key, 1.0) else: self.add(key, 0.0)
'Adds a distance penalty of 1.0 for each number of difference between `number1` and `number2`, or 0.0 when there is no difference. Use this when there is no upper limit on the difference between the two numbers.'
def add_number(self, key, number1, number2):
diff = abs((number1 - number2)) if diff: for i in range(diff): self.add(key, 1.0) else: self.add(key, 0.0)
'Adds a distance penalty that corresponds to the position at which `value` appears in `options`. A distance penalty of 0.0 for the first option, or 1.0 if there is no matching option. If an option is a compiled regular expression, it will be considered equal if it matches against `value`.'
def add_priority(self, key, value, options):
if (not isinstance(options, (list, tuple))): options = [options] unit = (1.0 / (len(options) or 1)) for (i, opt) in enumerate(options): if self._eq(opt, value): dist = (i * unit) break else: dist = 1.0 self.add(key, dist)
'Adds a distance penalty for `number1` as a ratio of `number2`. `number1` is bound at 0 and `number2`.'
def add_ratio(self, key, number1, number2):
number = float(max(min(number1, number2), 0)) if number2: dist = (number / number2) else: dist = 0.0 self.add(key, dist)
'Adds a distance penalty based on the edit distance between `str1` and `str2`.'
def add_string(self, key, str1, str2):
dist = string_dist(str1, str2) self.add(key, dist)
'Log msg.format(*args, **kwargs)'
def _log(self, level, msg, args, exc_info=None, extra=None, **kwargs):
m = self._LogMessage(msg, args, kwargs) return super(StrFormatLogger, self)._log(level, m, (), exc_info, extra)
'Set the level on the current thread + the default value for all threads.'
def set_global_level(self, level):
self.default_level = level self.setLevel(level)
'Perform one-time plugin setup.'
def __init__(self, name=None):
self.name = (name or self.__module__.split('.')[(-1)]) self.config = beets.config[self.name] if (not self.template_funcs): self.template_funcs = {} if (not self.template_fields): self.template_fields = {} if (not self.album_template_fields): self.album_template_fields = {} ...
'Should return a list of beets.ui.Subcommand objects for commands that should be added to beets\' CLI.'
def commands(self):
return ()
'Return a list of functions that should be called as importer pipelines stages. The callables are wrapped versions of the functions in `self.import_stages`. Wrapping provides some bookkeeping for the plugin: specifically, the logging level is adjusted to WARNING.'
def get_import_stages(self):
return [self._set_log_level_and_params(logging.WARNING, import_stage) for import_stage in self.import_stages]
'Wrap `func` to temporarily set this plugin\'s logger level to `base_log_level` + config options (and restore it to its previous value after the function returns). Also determines which params may not be sent for backwards-compatibility.'
def _set_log_level_and_params(self, base_log_level, func):
argspec = inspect.getargspec(func) @wraps(func) def wrapper(*args, **kwargs): assert (self._log.level == logging.NOTSET) verbosity = beets.config['verbose'].get(int) log_level = max(logging.DEBUG, (base_log_level - (10 * verbosity))) self._log.setLevel(log_level) try:...
'Should return a dict mapping prefixes to Query subclasses.'
def queries(self):
return {}
'Should return a Distance object to be added to the distance for every track comparison.'
def track_distance(self, item, info):
return beets.autotag.hooks.Distance()
'Should return a Distance object to be added to the distance for every album-level comparison.'
def album_distance(self, items, album_info, mapping):
return beets.autotag.hooks.Distance()
'Should return a sequence of AlbumInfo objects that match the album whose items are provided.'
def candidates(self, items, artist, album, va_likely):
return ()
'Should return a sequence of TrackInfo objects that match the item provided.'
def item_candidates(self, item, artist, title):
return ()
'Return an AlbumInfo object or None if no matching release was found.'
def album_for_id(self, album_id):
return None
'Return a TrackInfo object or None if no matching release was found.'
def track_for_id(self, track_id):
return None
'Add a field that is synchronized between media files and items. When a media field is added ``item.write()`` will set the name property of the item\'s MediaFile to ``item[name]`` and save the changes. Similarly ``item.read()`` will set ``item[name]`` to the value of the name property of the media file. ``descriptor`` ...
def add_media_field(self, name, descriptor):
from beets import library mediafile.MediaFile.add_field(name, descriptor) library.Item._media_fields.add(name)
'Add a function as a listener for the specified event.'
def register_listener(self, event, func):
wrapped_func = self._set_log_level_and_params(logging.WARNING, func) cls = self.__class__ if ((cls.listeners is None) or (cls._raw_listeners is None)): cls._raw_listeners = defaultdict(list) cls.listeners = defaultdict(list) if (func not in cls._raw_listeners[event]): cls._raw_li...
'Decorator that registers a path template function. The function will be invoked as ``%name{}`` from path format strings.'
@classmethod def template_func(cls, name):
def helper(func): if (cls.template_funcs is None): cls.template_funcs = {} cls.template_funcs[name] = func return func return helper
'Decorator that registers a path template field computation. The value will be referenced as ``$name`` from path format strings. The function must accept a single parameter, the Item being formatted.'
@classmethod def template_field(cls, name):
def helper(func): if (cls.template_fields is None): cls.template_fields = {} cls.template_fields[name] = func return func return helper
'Create a path query. `pattern` must be a path, either to a file or a directory. `case_sensitive` can be a bool or `None`, indicating that the behavior should depend on the filesystem.'
def __init__(self, field, pattern, fast=True, case_sensitive=None):
super(PathQuery, self).__init__(field, pattern, fast) if (case_sensitive is None): path = util.bytestring_path(util.normpath(pattern)) case_sensitive = beets.util.case_sensitive(path) self.case_sensitive = case_sensitive if (not case_sensitive): pattern = pattern.lower() self...
'Try to guess whether a unicode query part is a path query. Condition: separator precedes colon and the file exists.'
@classmethod def is_path_query(cls, query_part):
colon = query_part.find(':') if (colon != (-1)): query_part = query_part[:colon] return (((os.sep in query_part) or (os.altsep and (os.altsep in query_part))) and os.path.exists(syspath(normpath(query_part))))
'Create a path type object. `nullable` controls whether the type may be missing, i.e., None.'
def __init__(self, nullable=False):
self.nullable = nullable
'Create an exception describing an operation on the file at `path` with the underlying (chained) exception `reason`.'
def __init__(self, path, reason):
super(FileOperationError, self).__init__(path, reason) self.path = path self.reason = reason
'Get a string representing the error. Describes both the underlying reason and the file path in question.'
def text(self):
return u'{0}: {1}'.format(util.displayable_path(self.path), six.text_type(self.reason))
'Get the value for a key, either from the album or the item. Raise a KeyError for invalid keys.'
def _get(self, key):
if (self.for_path and (key in self.album_keys)): return self._get_formatted(self.album, key) elif (key in self.model_keys): return self._get_formatted(self.model, key) elif (key in self.album_keys): return self._get_formatted(self.album, key) else: raise KeyError(key)
'Get the value for a key. Certain unset values are remapped.'
def __getitem__(self, key):
value = self._get(key) if ((key == 'artist') and (not value)): return self._get('albumartist') elif ((key == 'albumartist') and (not value)): return self._get('artist') else: return value
'Creates a new item from the media file at the specified path.'
@classmethod def from_path(cls, path):
i = cls(album_id=None) i.read(path) i.mtime = i.current_mtime() return i
'Set the item\'s value for a standard field or a flexattr.'
def __setitem__(self, key, value):
if (key == 'path'): if isinstance(value, six.text_type): value = bytestring_path(value) elif isinstance(value, BLOB_TYPE): value = bytes(value) if (key in MediaFile.fields()): self.mtime = 0 super(Item, self).__setitem__(key, value)
'Set all key/value pairs in the mapping. If mtime is specified, it is not reset (as it might otherwise be).'
def update(self, values):
super(Item, self).update(values) if ((self.mtime == 0) and ('mtime' in values)): self.mtime = values['mtime']
'Get the Album object that this item belongs to, if any, or None if the item is a singleton or is not associated with a library.'
def get_album(self):
if (not self._db): return None return self._db.get_album(self)
'Read the metadata from the associated file. If `read_path` is specified, read metadata from that file instead. Updates all the properties in `_media_fields` from the media file. Raises a `ReadError` if the file could not be read.'
def read(self, read_path=None):
if (read_path is None): read_path = self.path else: read_path = normpath(read_path) try: mediafile = MediaFile(syspath(read_path)) except UnreadableFileError as exc: raise ReadError(read_path, exc) for key in self._media_fields: value = getattr(mediafile, key)...
'Write the item\'s metadata to a media file. All fields in `_media_fields` are written to disk according to the values on this object. `path` is the path of the mediafile to write the data to. It defaults to the item\'s path. `tags` is a dictionary of additional metadata the should be written to the file. (These tags n...
def write(self, path=None, tags=None):
if (path is None): path = self.path else: path = normpath(path) item_tags = dict(self) item_tags = {k: v for (k, v) in item_tags.items() if (k in self._media_fields)} if (tags is not None): item_tags.update(tags) plugins.send('write', item=self, path=path, tags=item_tags)...
'Calls `write()` but catches and logs `FileOperationError` exceptions. Returns `False` an exception was caught and `True` otherwise.'
def try_write(self, path=None, tags=None):
try: self.write(path, tags) return True except FileOperationError as exc: log.error(u'{0}', exc) return False
'Synchronize the item with the database and, possibly, updates its tags on disk and its path (by moving the file). `write` indicates whether to write new tags into the file. Similarly, `move` controls whether the path should be updated. In the latter case, files are *only* moved when they are inside their library\'s di...
def try_sync(self, write, move, with_album=True):
if write: self.try_write() if move: if (self._db and (self._db.directory in util.ancestry(self.path))): log.debug(u'moving {0} to synchronize path', util.displayable_path(self.path)) self.move(with_album=with_album) self.store()
'Moves or copies the item\'s file, updating the path value if the move succeeds. If a file exists at ``dest``, then it is slightly modified to be unique.'
def move_file(self, dest, copy=False, link=False, hardlink=False):
if (not util.samefile(self.path, dest)): dest = util.unique_path(dest) if copy: util.copy(self.path, dest) plugins.send('item_copied', item=self, source=self.path, destination=dest) elif link: util.link(self.path, dest) plugins.send('item_linked', item=self, source=se...
'Returns the current mtime of the file, rounded to the nearest integer.'
def current_mtime(self):
return int(os.path.getmtime(syspath(self.path)))
'Get the size of the underlying file in bytes. If the file is missing, return 0 (and log a warning).'
def try_filesize(self):
try: return os.path.getsize(syspath(self.path)) except (OSError, Exception) as exc: log.warning(u'could not get filesize: {0}', exc) return 0
'Removes the item. If `delete`, then the associated file is removed from disk. If `with_album`, then the item\'s album (if any) is removed if it the item was the last in the album.'
def remove(self, delete=False, with_album=True):
super(Item, self).remove() if with_album: album = self.get_album() if (album and (not album.items())): album.remove(delete, False) plugins.send('item_removed', item=self) if delete: util.remove(self.path) util.prune_dirs(os.path.dirname(self.path), self._db.di...
'Move the item to its designated location within the library directory (provided by destination()). Subdirectories are created as needed. If the operation succeeds, the item\'s path field is updated to reflect the new location. If `copy` is true, moving the file is copied rather than moved. Similarly, `link` creates a ...
def move(self, copy=False, link=False, hardlink=False, basedir=None, with_album=True, store=True):
self._check_db() dest = self.destination(basedir=basedir) util.mkdirall(dest) old_path = self.path self.move_file(dest, copy, link, hardlink) if store: self.store() if with_album: album = self.get_album() if album: album.move_art(copy) if store...
'Returns the path in the library directory designated for the item (i.e., where the file ought to be). fragment makes this method return just the path fragment underneath the root library directory; the path is also returned as Unicode instead of encoded as a bytestring. basedir can override the library\'s base directo...
def destination(self, fragment=False, basedir=None, platform=None, path_formats=None):
self._check_db() platform = (platform or sys.platform) basedir = (basedir or self._db.directory) path_formats = (path_formats or self._db.path_formats) for (query, path_format) in path_formats: if (query == PF_KEY_DEFAULT): continue (query, _) = parse_query_string(query, ...
'Returns an iterable over the items associated with this album.'
def items(self):
return self._db.items(dbcore.MatchQuery('album_id', self.id))
'Removes this album and all its associated items from the library. If delete, then the items\' files are also deleted from disk, along with any album art. The directories containing the album are also removed (recursively) if empty. Set with_items to False to avoid removing the album\'s items.'
def remove(self, delete=False, with_items=True):
super(Album, self).remove() if delete: artpath = self.artpath if artpath: util.remove(artpath) if with_items: for item in self.items(): item.remove(delete, False)
'Move or copy any existing album art so that it remains in the same directory as the items.'
def move_art(self, copy=False, link=False, hardlink=False):
old_art = self.artpath if (not old_art): return new_art = self.art_destination(old_art) if (new_art == old_art): return new_art = util.unique_path(new_art) log.debug(u'moving album art {0} to {1}', util.displayable_path(old_art), util.displayable_path(new_art)) ...
'Moves (or copies) all items to their destination. Any album art moves along with them. basedir overrides the library base directory for the destination. By default, the album is stored to the database, persisting any modifications to its metadata. If `store` is true however, the album is not stored automatically, and ...
def move(self, copy=False, link=False, hardlink=False, basedir=None, store=True):
basedir = (basedir or self._db.directory) if store: self.store() items = list(self.items()) for item in items: item.move(copy, link, hardlink, basedir=basedir, with_album=False, store=store) self.move_art(copy, link, hardlink) if store: self.store()
'Returns the directory containing the album\'s first item, provided that such an item exists.'
def item_dir(self):
item = self.items().get() if (not item): raise ValueError(u'empty album') return os.path.dirname(item.path)
'Return the total number of tracks on all discs on the album'
def _albumtotal(self):
if ((self.disctotal == 1) or (not beets.config['per_disc_numbering'])): return self.items()[0].tracktotal counted = [] total = 0 for item in self.items(): if (item.disc in counted): continue total += item.tracktotal counted.append(item.disc) if (len(co...
'Returns a path to the destination for the album art image for the album. `image` is the path of the image that will be moved there (used for its extension). The path construction uses the existing path of the album\'s items, so the album must contain at least one item or item_dir must be provided.'
def art_destination(self, image, item_dir=None):
image = bytestring_path(image) item_dir = (item_dir or self.item_dir()) filename_tmpl = Template(beets.config['art_filename'].as_str()) subpath = self.evaluate_template(filename_tmpl, True) if beets.config['asciify_paths']: subpath = util.asciify_path(subpath, beets.config['path_sep_replace'...
'Sets the album\'s cover art to the image at the given path. The image is copied (or moved) into place, replacing any existing art. Sends an \'art_set\' event with `self` as the sole argument.'
def set_art(self, path, copy=True):
path = bytestring_path(path) oldart = self.artpath artdest = self.art_destination(path) if (oldart and samefile(path, oldart)): return elif samefile(path, artdest): self.artpath = path return if (oldart == artdest): util.remove(oldart) artdest = util.unique_pa...
'Update the database with the album information. The album\'s tracks are also updated. :param fields: The fields to be stored. If not specified, all fields will be.'
def store(self, fields=None):
track_updates = {} for key in self.item_keys: if (key in self._dirty): track_updates[key] = self[key] with self._db.transaction(): super(Album, self).store(fields) if track_updates: for item in self.items(): for (key, value) in track_updates.it...
'Synchronize the album and its items with the database. Optionally, also write any new tags into the files and update their paths. `write` indicates whether to write tags to the item files, and `move` controls whether files (both audio and album art) are moved.'
def try_sync(self, write, move):
self.store() for item in self.items(): item.try_sync(write, move)
'Add the :class:`Item` or :class:`Album` object to the library database. Return the object\'s new id.'
def add(self, obj):
obj.add(self) self._memotable = {} return obj.id
'Create a new album consisting of a list of items. The items are added to the database if they don\'t yet have an ID. Return a new :class:`Album` object. The list items must not be empty.'
def add_album(self, items):
if (not items): raise ValueError(u'need at least one item') values = dict(((key, items[0][key]) for key in Album.item_keys)) album = Album(self, **values) with self.transaction(): album.add(self) for item in items: item.album_id = album.id if (...
'Parse a query and fetch. If a order specification is present in the query string the `sort` argument is ignored.'
def _fetch(self, model_cls, query, sort=None):
try: parsed_sort = None if isinstance(query, six.string_types): (query, parsed_sort) = parse_query_string(query, model_cls) elif isinstance(query, (list, tuple)): (query, parsed_sort) = parse_query_parts(query, model_cls) except dbcore.query.InvalidQueryArgumentVa...
'Get a :class:`Sort` object for albums from the config option.'
@staticmethod def get_default_album_sort():
return dbcore.sort_from_strings(Album, beets.config['sort_album'].as_str_seq())
'Get a :class:`Sort` object for items from the config option.'
@staticmethod def get_default_item_sort():
return dbcore.sort_from_strings(Item, beets.config['sort_item'].as_str_seq())
'Get :class:`Album` objects matching the query.'
def albums(self, query=None, sort=None):
return self._fetch(Album, query, (sort or self.get_default_album_sort()))
'Get :class:`Item` objects matching the query.'
def items(self, query=None, sort=None):
return self._fetch(Item, query, (sort or self.get_default_item_sort()))
'Fetch an :class:`Item` by its ID. Returns `None` if no match is found.'
def get_item(self, id):
return self._get(Item, id)
'Given an album ID or an item associated with an album, return an :class:`Album` object for the album. If no such album exists, returns `None`.'
def get_album(self, item_or_id):
if isinstance(item_or_id, int): album_id = item_or_id else: album_id = item_or_id.album_id if (album_id is None): return None return self._get(Album, album_id)
'Parametrize the functions. If `item` or `lib` is None, then some functions (namely, ``aunique``) will always evaluate to the empty string.'
def __init__(self, item=None, lib=None):
self.item = item self.lib = lib
'Returns a dictionary containing the functions defined in this object. The keys are function names (as exposed in templates) and the values are Python functions.'
def functions(self):
out = {} for key in self._func_names: out[key[len(self._prefix):]] = getattr(self, key) return out
'Convert a string to lower case.'
@staticmethod def tmpl_lower(s):
return s.lower()
'Covert a string to upper case.'
@staticmethod def tmpl_upper(s):
return s.upper()
'Convert a string to title case.'
@staticmethod def tmpl_title(s):
return s.title()
'Get the leftmost characters of a string.'
@staticmethod def tmpl_left(s, chars):
return s[0:_int_arg(chars)]
'Get the rightmost characters of a string.'
@staticmethod def tmpl_right(s, chars):
return s[(- _int_arg(chars)):]
'If ``condition`` is nonempty and nonzero, emit ``trueval``; otherwise, emit ``falseval`` (if provided).'
@staticmethod def tmpl_if(condition, trueval, falseval=u''):
try: int_condition = _int_arg(condition) except ValueError: if (condition.lower() == 'false'): return falseval else: condition = int_condition if condition: return trueval else: return falseval
'Translate non-ASCII characters to their ASCII equivalents.'
@staticmethod def tmpl_asciify(s):
return util.asciify_path(s, beets.config['path_sep_replace'].as_str())
'Format a time value using `strftime`.'
@staticmethod def tmpl_time(s, fmt):
cur_fmt = beets.config['time_format'].as_str() return time.strftime(fmt, time.strptime(s, cur_fmt))
'Generate a string that is guaranteed to be unique among all albums in the library who share the same set of keys. A fields from "disam" is used in the string if one is sufficient to disambiguate the albums. Otherwise, a fallback opaque value is used. Both "keys" and "disam" should be given as whitespace-separated list...
def tmpl_aunique(self, keys=None, disam=None, bracket=None):
if ((not self.item) or (not self.lib)): return u'' if (self.item.album_id is None): return u'' memokey = ('aunique', keys, disam, self.item.album_id) memoval = self.lib._memotable.get(memokey) if (memoval is not None): return memoval keys = (keys or 'albumartist album'...
'Gets the item(s) from x to y in a string separated by something and join then with something :param s: the string :param count: The number of items included :param skip: The number of items skipped :param sep: the separator. Usually is \'; \' (default) or \'/ \' :param join_str: the string which will join the items, d...
@staticmethod def tmpl_first(s, count=1, skip=0, sep=u'; ', join_str=u'; '):
skip = int(skip) count = (skip + int(count)) return join_str.join(s.split(sep)[skip:count])
'If field exists return trueval or the field (default) otherwise, emit return falseval (if provided). :param field: The name of the field :param trueval: The string if the condition is true :param falseval: The string if the condition is false :return: The string, based on condition'
def tmpl_ifdef(self, field, trueval=u'', falseval=u''):
if self.item.formatted().get(field): return (trueval if trueval else self.item.formatted().get(field)) else: return falseval
'Add a -a/--album option to match albums instead of tracks. If used then the format option can auto-detect whether we\'re setting the format for items or albums. Sets the album property on the options extracted from the CLI.'
def add_album_option(self, flags=('-a', '--album')):
album = optparse.Option(action='store_true', help=u'match albums instead of tracks', *flags) self.add_option(album) self._album_flags = set(flags)
'Internal callback that sets the correct format while parsing CLI arguments.'
def _set_format(self, option, opt_str, value, parser, target=None, fmt=None, store_true=False):
if store_true: setattr(parser.values, option.dest, True) if fmt: value = fmt elif value: (value,) = decargs([value]) else: value = u'' parser.values.format = value if target: config[target._format_config_key].set(value) elif self._album_flags: ...
'Add a -p/--path option to display the path instead of the default format. By default this affects both items and albums. If add_album_option() is used then the target will be autodetected. Sets the format property to u\'$path\' on the options extracted from the CLI.'
def add_path_option(self, flags=('-p', '--path')):
path = optparse.Option(nargs=0, action='callback', callback=self._set_format, callback_kwargs={'fmt': u'$path', 'store_true': True}, help=u'print paths for matched items or albums', *flags) self.add_option(path)
'Add -f/--format option to print some LibModel instances with a custom format. `target` is optional and can be one of ``library.Item``, \'item\', ``library.Album`` and \'album\'. Several behaviors are available: - if `target` is given then the format is only applied to that LibModel - if the album option is used then t...
def add_format_option(self, flags=('-f', '--format'), target=None):
kwargs = {} if target: if isinstance(target, six.string_types): target = {'item': library.Item, 'album': library.Album}[target] kwargs['target'] = target opt = optparse.Option(action='callback', callback=self._set_format, callback_kwargs=kwargs, help=u'print with custom ...
'Add album, path and format options.'
def add_all_common_options(self):
self.add_album_option() self.add_path_option() self.add_format_option()
'Creates a new subcommand. name is the primary way to invoke the subcommand; aliases are alternate names. parser is an OptionParser responsible for parsing the subcommand\'s options. help is a short description of the command. If no parser is given, it defaults to a new, empty CommonOptionsParser.'
def __init__(self, name, parser=None, help='', aliases=(), hide=False):
self.name = name self.parser = (parser or CommonOptionsParser()) self.aliases = aliases self.help = help self.hide = hide self._root_parser = None
'Create a new subcommand-aware option parser. All of the options to OptionParser.__init__ are supported in addition to subcommands, a sequence of Subcommand objects.'
def __init__(self, *args, **kwargs):
if ('usage' not in kwargs): kwargs['usage'] = u'\n %prog COMMAND [ARGS...]\n %prog help COMMAND' kwargs['add_help_option'] = False super(SubcommandsOptionParser, self).__init__(*args, **kwargs) self.disable_interspersed_args() self.subcommands = []
'Adds a Subcommand object to the parser\'s list of commands.'
def add_subcommand(self, *cmds):
for cmd in cmds: cmd.root_parser = self self.subcommands.append(cmd)
'Return the subcommand in self.subcommands matching the given name. The name may either be the name of a subcommand or an alias. If no subcommand matches, returns None.'
def _subcommand_for_name(self, name):
for subcommand in self.subcommands: if ((name == subcommand.name) or (name in subcommand.aliases)): return subcommand return None
'Parse options up to the subcommand argument. Returns a tuple of the options object and the remaining arguments.'
def parse_global_options(self, args):
(options, subargs) = self.parse_args(args) if options.help: subargs = ['help'] elif options.version: subargs = ['version'] return (options, subargs)
'Given the `args` left unused by a `parse_global_options`, return the invoked subcommand, the subcommand options, and the subcommand arguments.'
def parse_subcommand(self, args):
if (not args): args = ['help'] cmdname = args.pop(0) subcommand = self._subcommand_for_name(cmdname) if (not subcommand): raise UserError(u"unknown command '{0}'".format(cmdname)) (suboptions, subargs) = subcommand.parse_args(args) return (subcommand, suboptions, subargs)
'Given an initial autotagging of items, go through an interactive dance with the user to ask for a choice of metadata. Returns an AlbumMatch object, ASIS, or SKIP.'
def choose_match(self, task):
print_() print_((displayable_path(task.paths, u'\n') + u' ({0} items)'.format(len(task.items)))) action = _summary_judgment(task.rec) if (action == importer.action.APPLY): match = task.candidates[0] show_change(task.cur_artist, task.cur_album, match) return match elif (...
'Ask the user for a choice about tagging a single item. Returns either an action constant or a TrackMatch object.'
def choose_item(self, task):
print_() print_(displayable_path(task.item.path)) (candidates, rec) = (task.candidates, task.rec) action = _summary_judgment(task.rec) if (action == importer.action.APPLY): match = candidates[0] show_item_change(task.item, match) return match elif (action is not None): ...