desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create an object with values drawn from the database. This is a performance optimization: the checks involved with ordinary construction are bypassed.'
@classmethod def _awaken(cls, db=None, fixed_values={}, flex_values={}):
obj = cls(db) for (key, value) in fixed_values.items(): obj._values_fixed[key] = cls._type(key).from_sql(value) for (key, value) in flex_values.items(): obj._values_flex[key] = cls._type(key).from_sql(value) return obj
'Mark all fields as *clean* (i.e., not needing to be stored to the database).'
def clear_dirty(self):
self._dirty = set()
'Ensure that this object is associated with a database row: it has a reference to a database (`_db`) and an id. A ValueError exception is raised otherwise.'
def _check_db(self, need_id=True):
if (not self._db): raise ValueError(u'{0} has no database'.format(type(self).__name__)) if (need_id and (not self.id)): raise ValueError(u'{0} has no id'.format(type(self).__name__))
'Get the type of a field, a `Type` instance. If the field has no explicit type, it is given the base `Type`, which does no conversion.'
@classmethod def _type(cls, key):
return (cls._fields.get(key) or cls._types.get(key) or types.DEFAULT)
'Get the value for a field. Raise a KeyError if the field is not available.'
def __getitem__(self, key):
getters = self._getters() if (key in getters): return getters[key](self) elif (key in self._fields): return self._values_fixed.get(key) elif (key in self._values_flex): return self._values_flex[key] else: raise KeyError(key)
'Assign the value for a field.'
def __setitem__(self, key, value):
if (key in self._fields): source = self._values_fixed else: source = self._values_flex value = self._type(key).normalize(value) old_value = source.get(key) source[key] = value if (self._always_dirty or (old_value != value)): self._dirty.add(key)
'Remove a flexible attribute from the model.'
def __delitem__(self, key):
if (key in self._values_flex): del self._values_flex[key] self._dirty.add(key) elif (key in self._getters()): raise KeyError(u'computed field {0} cannot be deleted'.format(key)) elif (key in self._fields): raise KeyError(u'fixed field {0} cannot be ...
'Get a list of available field names for this object. The `computed` parameter controls whether computed (plugin-provided) fields are included in the key list.'
def keys(self, computed=False):
base_keys = (list(self._fields) + list(self._values_flex.keys())) if computed: return (base_keys + list(self._getters().keys())) else: return base_keys
'Get a list of available keys for objects of this type. Includes fixed and computed fields.'
@classmethod def all_keys(cls):
return (list(cls._fields) + list(cls._getters().keys()))
'Assign all values in the given dict.'
def update(self, values):
for (key, value) in values.items(): self[key] = value
'Iterate over (key, value) pairs that this object contains. Computed fields are not included.'
def items(self):
for key in self: (yield (key, self[key]))
'Get the value for a given key or `default` if it does not exist.'
def get(self, key, default=None):
if (key in self): return self[key] else: return default
'Determine whether `key` is an attribute on this object.'
def __contains__(self, key):
return (key in self.keys(True))
'Iterate over the available field names (excluding computed fields).'
def __iter__(self):
return iter(self.keys())
'Save the object\'s metadata into the library database. :param fields: the fields to be stored. If not specified, all fields will be.'
def store(self, fields=None):
if (fields is None): fields = self._fields self._check_db() assignments = [] subvars = [] for key in fields: if ((key != 'id') and (key in self._dirty)): self._dirty.remove(key) assignments.append((key + '=?')) value = self._type(key).to_sql(self[k...
'Refresh the object\'s metadata from the library database.'
def load(self):
self._check_db() stored_obj = self._db._get(type(self), self.id) assert (stored_obj is not None), u'object {0} not in DB'.format(self.id) self._values_fixed = {} self._values_flex = {} self.update(dict(stored_obj)) self.clear_dirty()
'Remove the object\'s associated rows from the database.'
def remove(self):
self._check_db() with self._db.transaction() as tx: tx.mutate('DELETE FROM {0} WHERE id=?'.format(self._table), (self.id,)) tx.mutate('DELETE FROM {0} WHERE entity_id=?'.format(self._flex_table), (self.id,))
'Add the object to the library database. This object must be associated with a database; you can provide one via the `db` parameter or use the currently associated database. The object\'s `id` and `added` fields are set along with any current field values.'
def add(self, db=None):
if db: self._db = db self._check_db(False) with self._db.transaction() as tx: new_id = tx.mutate('INSERT INTO {0} DEFAULT VALUES'.format(self._table)) self.id = new_id self.added = time.time() for key in self: if (self[key] is not None): ...
'Get a mapping containing all values on this object formatted as human-readable unicode strings.'
def formatted(self, for_path=False):
return self._formatter(self, for_path)
'Evaluate a template (a string or a `Template` object) using the object\'s fields. If `for_path` is true, then no new path separators will be added to the template.'
def evaluate_template(self, template, for_path=False):
if isinstance(template, six.string_types): template = Template(template) return template.substitute(self.formatted(for_path), self._template_funcs())
'Parse a string as a value for the given key.'
@classmethod def _parse(cls, key, string):
if (not isinstance(string, six.string_types)): raise TypeError(u'_parse() argument must be a string') return cls._type(key).parse(string)
'Set the object\'s key to a value represented by a string.'
def set_parse(self, key, string):
self[key] = self._parse(key, string)
'Create a result set that will construct objects of type `model_class`. `model_class` is a subclass of `LibModel` that will be constructed. `rows` is a query result: a list of mappings. The new objects will be associated with the database `db`. If `query` is provided, it is used as a predicate to filter the results for...
def __init__(self, model_class, rows, db, query=None, sort=None):
self.model_class = model_class self.rows = rows self.db = db self.query = query self.sort = sort self._rows = rows self._row_count = len(rows) self._objects = []
'Construct and generate Model objects for they query. The objects are returned in the order emitted from the database; no slow sort is applied. For performance, this generator caches materialized objects to avoid constructing them more than once. This way, iterating over a `Results` object a second time should be much ...
def _get_objects(self):
index = 0 while ((index < len(self._objects)) or self._rows): if (index < len(self._objects)): (yield self._objects[index]) index += 1 else: while self._rows: row = self._rows.pop(0) obj = self._make_model(row) i...
'Construct and generate Model objects for all matching objects, in sorted order.'
def __iter__(self):
if self.sort: objects = self.sort.sort(list(self._get_objects())) return iter(objects) else: return self._get_objects()
'Get the number of matching objects.'
def __len__(self):
if (not self._rows): return len(self._objects) elif self.query: count = 0 for obj in self: count += 1 return count else: return self._row_count
'Does this result contain any objects?'
def __nonzero__(self):
return self.__bool__()
'Does this result contain any objects?'
def __bool__(self):
return bool(len(self))
'Get the nth item in this result set. This is inefficient: all items up to n are materialized and thrown away.'
def __getitem__(self, n):
if ((not self._rows) and (not self.sort)): return self._objects[n] it = iter(self) try: for i in range(n): next(it) return next(it) except StopIteration: raise IndexError(u'result index {0} out of range'.format(n))
'Return the first matching object, or None if no objects match.'
def get(self):
it = iter(self) try: return next(it) except StopIteration: return None
'Begin a transaction. This transaction may be created while another is active in a different thread.'
def __enter__(self):
with self.db._tx_stack() as stack: first = (not stack) stack.append(self) if first: self.db._db_lock.acquire() return self
'Complete a transaction. This must be the most recently entered but not yet exited transaction. If it is the last active transaction, the database updates are committed.'
def __exit__(self, exc_type, exc_value, traceback):
with self.db._tx_stack() as stack: assert (stack.pop() is self) empty = (not stack) if empty: self.db._connection().commit() self.db._db_lock.release()
'Execute an SQL statement with substitution values and return a list of rows from the database.'
def query(self, statement, subvals=()):
cursor = self.db._connection().execute(statement, subvals) return cursor.fetchall()
'Execute an SQL statement with substitution values and return the row ID of the last affected row.'
def mutate(self, statement, subvals=()):
cursor = self.db._connection().execute(statement, subvals) return cursor.lastrowid
'Execute a string containing multiple SQL statements.'
def script(self, statements):
self.db._connection().executescript(statements)
'Get a SQLite connection object to the underlying database. One connection object is created per thread.'
def _connection(self):
thread_id = threading.current_thread().ident with self._shared_map_lock: if (thread_id in self._connections): return self._connections[thread_id] else: conn = self._create_connection() self._connections[thread_id] = conn return conn
'Create a SQLite connection to the underlying database. Makes a new connection every time. If you need to configure the connection settings (e.g., add custom functions), override this method.'
def _create_connection(self):
conn = sqlite3.connect(py3_path(self.path), timeout=self.timeout) conn.row_factory = sqlite3.Row return conn
'Close the all connections to the underlying SQLite database from all threads. This does not render the database object unusable; new connections can still be opened on demand.'
def _close(self):
with self._shared_map_lock: self._connections.clear()
'A context manager providing access to the current thread\'s transaction stack. The context manager synchronizes access to the stack map. Transactions should never migrate across threads.'
@contextlib.contextmanager def _tx_stack(self):
thread_id = threading.current_thread().ident with self._shared_map_lock: (yield self._tx_stacks[thread_id])
'Get a :class:`Transaction` object for interacting directly with the underlying SQLite database.'
def transaction(self):
return Transaction(self)
'Set up the schema of the database. `fields` is a mapping from field names to `Type`s. Columns are added if necessary.'
def _make_table(self, table, fields):
with self.transaction() as tx: rows = tx.query(('PRAGMA table_info(%s)' % table)) current_fields = set([row[1] for row in rows]) field_names = set(fields.keys()) if current_fields.issuperset(field_names): return if (not current_fields): columns = [] for (name, typ)...
'Create a table and associated index for flexible attributes for the given entity (if they don\'t exist).'
def _make_attribute_table(self, flex_table):
with self.transaction() as tx: tx.script('\n CREATE TABLE IF NOT EXISTS {0} (\n id INTEGER PRIMARY KEY,\n ...
'Fetch the objects of type `model_cls` matching the given query. The query may be given as a string, string sequence, a Query object, or None (to fetch everything). `sort` is an `Sort` object.'
def _fetch(self, model_cls, query=None, sort=None):
query = (query or TrueQuery()) sort = (sort or NullSort()) (where, subvals) = query.clause() order_by = sort.order_clause() sql = 'SELECT * FROM {0} WHERE {1} {2}'.format(model_cls._table, (where or '1'), ('ORDER BY {0}'.format(order_by) if order_by else '')) with self.tr...
'Get a Model object by its id or None if the id does not exist.'
def _get(self, model_cls, id):
return self._fetch(model_cls, MatchQuery('id', id)).get()
'Generate an SQLite expression implementing the query. Return (clause, subvals) where clause is a valid sqlite WHERE clause implementing the query and subvals is a list of items to be substituted for ?s in the clause.'
def clause(self):
return (None, ())
'Check whether this query matches a given Item. Can be used to perform queries on arbitrary sets of Items.'
def match(self, item):
raise NotImplementedError
'Determine whether the value matches the pattern. Both arguments are strings.'
@classmethod def value_match(cls, pattern, value):
raise NotImplementedError()
'Determine whether the value matches the pattern. The value may have any type.'
@classmethod def value_match(cls, pattern, value):
return cls.string_match(pattern, util.as_string(value))
'Determine whether the value matches the pattern. Both arguments are strings. Subclasses implement this method.'
@classmethod def string_match(cls, pattern, value):
raise NotImplementedError()
'Normalize a Unicode string\'s representation (used on both patterns and matched values).'
@staticmethod def _normalize(s):
return unicodedata.normalize('NFC', s)
'Convert a string to a numeric type (float or int). Return None if `s` is empty. Raise an InvalidQueryError if the string cannot be converted.'
def _convert(self, s):
if (not s): return None try: return int(s) except ValueError: try: return float(s) except ValueError: raise InvalidQueryArgumentTypeError(s, u'an int or a float')
'Return a clause created by joining together the clauses of all subqueries with the string joiner (padded by spaces).'
def clause_with_joiner(self, joiner):
clause_parts = [] subvals = [] for subq in self.subqueries: (subq_clause, subq_subvals) = subq.clause() if (not subq_clause): return (None, ()) clause_parts.append((('(' + subq_clause) + ')')) subvals += subq_subvals clause = ((' ' + joiner) + ' ').join(...
'Since subqueries are mutable, this object should not be hashable. However and for conveniences purposes, it can be hashed.'
def __hash__(self):
return reduce(mul, map(hash, self.subqueries), 1)
'Create a period with the given date (a `datetime` object) and precision (a string, one of "year", "month", or "day").'
def __init__(self, date, precision):
if (precision not in Period.precisions): raise ValueError(u'Invalid precision {0}'.format(precision)) self.date = date self.precision = precision
'Parse a date and return a `Period` object or `None` if the string is empty.'
@classmethod def parse(cls, string):
if (not string): return None ordinal = string.count('-') if (ordinal >= len(cls.date_formats)): return None date_format = cls.date_formats[ordinal] try: date = datetime.strptime(string, date_format) except ValueError: return None precision = cls.precisions[ord...
'Based on the precision, convert the period to a precise `datetime` for use as a right endpoint in a right-open interval.'
def open_right_endpoint(self):
precision = self.precision date = self.date if ('year' == self.precision): return date.replace(year=(date.year + 1), month=1) elif ('month' == precision): if (date.month < 12): return date.replace(month=(date.month + 1)) else: return date.replace(year=(dat...
'Create an interval with two Periods as the endpoints.'
@classmethod def from_periods(cls, start, end):
end_date = (end.open_right_endpoint() if (end is not None) else None) start_date = (start.date if (start is not None) else None) return cls(start_date, end_date)
'Convert a M:SS or numeric string to a float. Return None if `s` is empty. Raise an InvalidQueryError if the string cannot be converted.'
def _convert(self, s):
if (not s): return None try: return util.raw_seconds_short(s) except ValueError: try: return float(s) except ValueError: raise InvalidQueryArgumentTypeError(s, u'a M:SS string or a float')
'Generates a SQL fragment to be used in a ORDER BY clause, or None if no fragment is used (i.e., this is a slow sort).'
def order_clause(self):
return None
'Sort the list of objects and return a list.'
def sort(self, items):
return sorted(items)
'Indicate whether this query is *slow*, meaning that it cannot be executed in SQL and must be executed in Python.'
def is_slow(self):
return False
'Return the list of sub-sorts for which we can be (at least partially) fast. A contiguous suffix of fast (SQL-capable) sub-sorts are executable in SQL. The remaining, even if they are fast independently, must be executed slowly.'
def _sql_sorts(self):
sql_sorts = [] for sort in reversed(self.sorts): if (not (sort.order_clause() is None)): sql_sorts.append(sort) else: break sql_sorts.reverse() return sql_sorts
'The value to be exposed when the underlying value is None.'
@property def null(self):
return self.model_type()
'Given a value of this type, produce a Unicode string representing the value. This is used in template evaluation.'
def format(self, value):
if (value is None): value = self.null if (value is None): value = u'' if isinstance(value, bytes): value = value.decode('utf-8', 'ignore') return six.text_type(value)
'Parse a (possibly human-written) string and return the indicated value of this type.'
def parse(self, string):
try: return self.model_type(string) except ValueError: return self.null
'Given a value that will be assigned into a field of this type, normalize the value to have the appropriate type. This base implementation only reinterprets `None`.'
def normalize(self, value):
if (value is None): return self.null else: return value
'Receives the value stored in the SQL backend and return the value to be stored in the model. For fixed fields the type of `value` is determined by the column type affinity given in the `sql` property and the SQL to Python mapping of the database adapter. For more information see: http://www.sqlite.org/datatype3.html h...
def from_sql(self, sql_value):
if isinstance(sql_value, buffer): sql_value = bytes(sql_value).decode('utf-8', 'ignore') if isinstance(sql_value, six.text_type): return self.parse(sql_value) else: return self.normalize(sql_value)
'Convert a value as stored in the model object to a value used by the database adapter.'
def to_sql(self, model_value):
return model_value
'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...