desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns a list of archive handlers. Each handler is a `(path_test, ArchiveClass)` tuple. `path_test` is a function that returns `True` if the given path can be handled by `ArchiveClass`. `ArchiveClass` is a class that implements the same interface as `tarfile.TarFile`.'
@classmethod def handlers(cls):
if (not hasattr(cls, '_handlers')): cls._handlers = [] from zipfile import is_zipfile, ZipFile cls._handlers.append((is_zipfile, ZipFile)) from tarfile import is_tarfile, TarFile cls._handlers.append((is_tarfile, TarFile)) try: from rarfile import is_rarfi...
'Removes the temporary directory the archive was extracted to.'
def cleanup(self, **kwargs):
if self.extracted: log.debug(u'Removing extracted directory: {0}', displayable_path(self.toppath)) shutil.rmtree(self.toppath)
'Extracts the archive to a temporary directory and sets `toppath` to that directory.'
def extract(self):
for (path_test, handler_class) in self.handlers(): if path_test(util.py3_path(self.toppath)): break try: extract_to = mkdtemp() archive = handler_class(util.py3_path(self.toppath), mode='r') archive.extractall(extract_to) finally: archive.close() self....
'Create a new task factory. `toppath` is the user-specified path to search for music to import. `session` is the `ImportSession`, which controls how tasks are read from the directory.'
def __init__(self, toppath, session):
self.toppath = toppath self.session = session self.skipped = 0 self.imported = 0 self.is_archive = ArchiveImportTask.is_archive(syspath(toppath))
'Yield all import tasks for music found in the user-specified path `self.toppath`. Any necessary sentinel tasks are also produced. During generation, update `self.skipped` and `self.imported` with the number of tasks that were not produced (due to incremental mode or resumed imports) and the number of concrete tasks ac...
def tasks(self):
if self.is_archive: archive_task = self.unarchive() if (not archive_task): return for (dirs, paths) in self.paths(): if self.session.config['singletons']: for path in paths: tasks = self._create(self.singleton(path)) for task in tas...
'Handle a new task to be emitted by the factory. Emit the `import_task_created` event and increment the `imported` count if the task is not skipped. Return the same task. If `task` is None, do nothing.'
def _create(self, task):
if task: tasks = task.handle_created(self.session) self.imported += len(tasks) return tasks return []
'Walk `self.toppath` and yield `(dirs, files)` pairs where `files` are individual music files and `dirs` the set of containing directories where the music was found. This can either be a recursive search in the ordinary case, a single track when `toppath` is a file, a single directory in `flat` mode.'
def paths(self):
if (not os.path.isdir(syspath(self.toppath))): (yield ([self.toppath], [self.toppath])) elif self.session.config['flat']: paths = [] for (dirs, paths_in_dir) in albums_in_dir(self.toppath): paths += paths_in_dir (yield ([self.toppath], paths)) else: for (d...
'Return a `SingletonImportTask` for the music file.'
def singleton(self, path):
if self.session.already_imported(self.toppath, [path]): log.debug(u'Skipping previously-imported path: {0}', displayable_path(path)) self.skipped += 1 return None item = self.read_item(path) if item: return SingletonImportTask(self.toppath, item) else: re...
'Return a `ImportTask` with all media files from paths. `dirs` is a list of parent directories used to record already imported albums.'
def album(self, paths, dirs=None):
if (not paths): return None if (dirs is None): dirs = list(set((os.path.dirname(p) for p in paths))) if self.session.already_imported(self.toppath, dirs): log.debug(u'Skipping previously-imported path: {0}', displayable_path(dirs)) self.skipped += 1 return No...
'Return a `SentinelImportTask` indicating the end of a top-level directory import.'
def sentinel(self, paths=None):
return SentinelImportTask(self.toppath, paths)
'Extract the archive for this `toppath`. Extract the archive to a new directory, adjust `toppath` to point to the extracted directory, and return an `ArchiveImportTask`. If extraction fails, return None.'
def unarchive(self):
assert self.is_archive if (not (self.session.config['move'] or self.session.config['copy'])): log.warning(u"Archive importing requires either 'copy' or 'move' to be enabled.") return log.debug(u'Extracting archive: {0}', displayable_path(self.toppath)) ar...
'Return an `Item` read from the path. If an item cannot be read, return `None` instead and log an error.'
def read_item(self, path):
try: return library.Item.from_path(path) except library.ReadError as exc: if isinstance(exc.reason, mediafile.FileTypeError): pass elif isinstance(exc.reason, mediafile.UnreadableFileError): log.warning(u'unreadable file: {0}', displayable_path(path)) ...
'Generate a (likely) gerund form of the English verb.'
def _gerund(self):
if (u' ' in self.verb): return self.verb gerund = (self.verb[:(-1)] if self.verb.endswith(u'e') else self.verb) gerund += u'ing' return gerund
'Get the reason as a string.'
def _reasonstr(self):
if isinstance(self.reason, six.text_type): return self.reason elif isinstance(self.reason, bytes): return self.reason.decode('utf-8', 'ignore') elif hasattr(self.reason, 'strerror'): return self.reason.strerror else: return u'"{0}"'.format(six.text_type(self.reason))
'Create the human-readable description of the error, sans introduction.'
def get_message(self):
raise NotImplementedError
'Log to the provided `logger` a human-readable message as an error and a verbose traceback as a debug message.'
def log(self, logger):
if self.tb: logger.debug(self.tb) logger.error(u'{0}: {1}', self.error_kind, self.args[0])
'Indicate that a thread will start putting into this queue. Should not be called after the queue is already poisoned.'
def acquire(self):
with self.mutex: assert (not self.poisoned) assert (self.nthreads >= 0) self.nthreads += 1
'Indicate that a thread that was putting into this queue has exited. If this is the last thread using the queue, the queue is poisoned.'
def release(self):
with self.mutex: self.nthreads -= 1 assert (self.nthreads >= 0) if (self.nthreads == 0): self.poisoned = True _old_get = self._get def _get(): out = _old_get() if (not self.queue): _invalidate_queue(self,...
'Shut down the thread at the next chance possible.'
def abort(self):
with self.abort_lock: self.abort_flag = True if hasattr(self, 'in_queue'): _invalidate_queue(self.in_queue, POISON) if hasattr(self, 'out_queue'): _invalidate_queue(self.out_queue, POISON)
'Abort all other threads in the system for an exception.'
def abort_all(self, exc_info):
self.exc_info = exc_info for thread in self.all_threads: thread.abort()
'Makes a new pipeline from a list of coroutines. There must be at least two stages.'
def __init__(self, stages):
if (len(stages) < 2): raise ValueError(u'pipeline must have at least two stages') self.stages = [] for stage in stages: if isinstance(stage, (list, tuple)): self.stages.append(stage) else: self.stages.append((stage,))
'Run the pipeline sequentially in the current thread. The stages are run one after the other. Only the first coroutine in each stage is used.'
def run_sequential(self):
list(self.pull())
'Run the pipeline in parallel using one thread per stage. The messages between the stages are stored in queues of the given size.'
def run_parallel(self, queue_size=DEFAULT_QUEUE_SIZE):
queue_count = (len(self.stages) - 1) queues = [CountedQueue(queue_size) for i in range(queue_count)] threads = [] for coro in self.stages[0]: threads.append(FirstPipelineThread(coro, queues[0], threads)) for i in range(1, queue_count): for coro in self.stages[i]: threads....
'Yield elements from the end of the pipeline. Runs the stages sequentially until the last yields some messages. Each of the messages is then yielded by ``pulled.next()``. If the pipeline has a consumer, that is the last stage does not yield any messages, then pull will not yield any messages. Only the first coroutine i...
def pull(self):
coros = [stage[0] for stage in self.stages] for coro in coros[1:]: next(coro) for out in coros[0]: msgs = _allmsgs(out) for coro in coros[1:]: next_msgs = [] for msg in msgs: out = coro.send(msg) next_msgs.extend(_allmsgs(out)) ...
'Return "waitable" objects to pass to select(). Should return three iterables for input readiness, output readiness, and exceptional conditions (i.e., the three lists passed to select()).'
def waitables(self):
return ((), (), ())
'Called when an associated file descriptor becomes ready (i.e., is returned from a select() call).'
def fire(self):
pass
'Create a listening socket on the given hostname and port.'
def __init__(self, host, port):
self._closed = False self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((host, port)) self.sock.listen(5)
'An event that waits for a connection on the listening socket. When a connection is made, the event returns a Connection object.'
def accept(self):
if self._closed: raise SocketClosedError() return AcceptEvent(self)
'Immediately close the listening socket. (Not an event.)'
def close(self):
self._closed = True self.sock.close()
'Close the connection.'
def close(self):
self._closed = True self.sock.close()
'Read at most size bytes of data from the socket.'
def recv(self, size):
if self._closed: raise SocketClosedError() if self._buf: out = self._buf[:size] self._buf = self._buf[size:] return ValueEvent(out) else: return ReceiveEvent(self, size)
'Sends data on the socket, returning the number of bytes successfully sent.'
def send(self, data):
if self._closed: raise SocketClosedError() return SendEvent(self, data)
'Send all of data on the socket.'
def sendall(self, data):
if self._closed: raise SocketClosedError() return SendEvent(self, data, True)
'Reads a line (delimited by terminator) from the socket.'
def readline(self, terminator='\n', bufsize=1024):
if self._closed: raise SocketClosedError() while True: if (terminator in self._buf): (line, self._buf) = self._buf.split(terminator, 1) line += terminator (yield ReturnEvent(line)) break data = (yield ReceiveEvent(self, bufsize)) if...
'Given either a dictionary or a `ConfigSource` object, return a `ConfigSource` object. This lets a function accept either type of object as an argument.'
@classmethod def of(cls, value):
if isinstance(value, ConfigSource): return value elif isinstance(value, dict): return ConfigSource(value) else: raise TypeError(u'source value must be a dict')
'The core (internal) data retrieval method. Generates (value, source) pairs for each source that contains a value for this view. May raise ConfigTypeError if a type error occurs while traversing a source.'
def resolve(self):
raise NotImplementedError
'Return a (value, source) pair for the first object found for this view. This amounts to the first element returned by `resolve`. If no values are available, a NotFoundError is raised.'
def first(self):
pairs = self.resolve() try: return iter_first(pairs) except ValueError: raise NotFoundError(u'{0} not found'.format(self.name))
'Determine whether the view has a setting in any source.'
def exists(self):
try: self.first() except NotFoundError: return False return True
'Set the *default* value for this configuration view. The specified value is added as the lowest-priority configuration data source.'
def add(self, value):
raise NotImplementedError
'*Override* the value for this configuration view. The specified value is added as the highest-priority configuration data source.'
def set(self, value):
raise NotImplementedError
'The RootView object from which this view is descended.'
def root(self):
raise NotImplementedError
'Iterate over the keys of a dictionary view or the *subviews* of a list view.'
def __iter__(self):
try: keys = self.keys() for key in keys: (yield key) except ConfigTypeError: collection = self.get() if (not isinstance(collection, (list, tuple))): raise ConfigTypeError(u'{0} must be a dictionary or a list, not {1}'.format(self...
'Get a subview of this view.'
def __getitem__(self, key):
return Subview(self, key)
'Create an overlay source to assign a given key under this view.'
def __setitem__(self, key, value):
self.set({key: value})
'Overlay parsed command-line arguments, generated by a library like argparse or optparse, onto this view\'s value. ``namespace`` can be a ``dict`` or namespace object.'
def set_args(self, namespace):
args = {} if isinstance(namespace, dict): items = namespace.items() else: items = namespace.__dict__.items() for (key, value) in items: if (value is not None): args[key] = value self.set(args)
'Get the value for this view as a bytestring.'
def __str__(self):
if PY3: return self.__unicode__() else: return bytes(self.get())
'Get the value for this view as a Unicode string.'
def __unicode__(self):
return STRING(self.get())
'Gets the value for this view as a boolean. (Python 2 only.)'
def __nonzero__(self):
return self.__bool__()
'Gets the value for this view as a boolean. (Python 3 only.)'
def __bool__(self):
return bool(self.get())
'Returns a list containing all the keys available as subviews of the current views. This enumerates all the keys in *all* dictionaries matching the current view, in contrast to ``view.get(dict).keys()``, which gets all the keys for the *first* dict matching the view. If the object for this view in any source is not a d...
def keys(self):
keys = [] for (dic, _) in self.resolve(): try: cur_keys = dic.keys() except AttributeError: raise ConfigTypeError(u'{0} must be a dict, not {1}'.format(self.name, type(dic).__name__)) for key in cur_keys: if (key not in keys): ...
'Iterates over (key, subview) pairs contained in dictionaries from *all* sources at this view. If the object for this view in any source is not a dict, then a ConfigTypeError is raised.'
def items(self):
for key in self.keys(): (yield (key, self[key]))
'Iterates over all the subviews contained in dictionaries from *all* sources at this view. If the object for this view in any source is not a dict, then a ConfigTypeError is raised.'
def values(self):
for key in self.keys(): (yield self[key])
'Iterates over all subviews from collections at this view from *all* sources. If the object for this view in any source is not iterable, then a ConfigTypeError is raised. This method is intended to be used when the view indicates a list; this method will concatenate the contents of the list from all sources.'
def all_contents(self):
for (collection, _) in self.resolve(): try: it = iter(collection) except TypeError: raise ConfigTypeError(u'{0} must be an iterable, not {1}'.format(self.name, type(collection).__name__)) for value in it: (yield value)
'Create a hierarchy of OrderedDicts containing the data from this view, recursively reifying all views to get their represented values. If `redact` is set, then sensitive values are replaced with the string "REDACTED".'
def flatten(self, redact=False):
od = OrderedDict() for (key, view) in self.items(): if (redact and view.redact): od[key] = REDACTED_TOMBSTONE else: try: od[key] = view.flatten(redact=redact) except ConfigTypeError: od[key] = view.get() return od
'Retrieve the value for this view according to the template. The `template` against which the values are checked can be anything convertible to a `Template` using `as_template`. This means you can pass in a default integer or string value, for example, or a type to just check that something matches the type you expect....
def get(self, template=None):
return as_template(template).value(self, template)
'Get the value as a path. Equivalent to `get(Filename())`.'
def as_filename(self):
return self.get(Filename())
'Get the value from a list of choices. Equivalent to `get(Choice(choices))`.'
def as_choice(self, choices):
return self.get(Choice(choices))
'Get the value as any number type: int or float. Equivalent to `get(Number())`.'
def as_number(self):
return self.get(Number())
'Get the value as a sequence of strings. Equivalent to `get(StrSeq())`.'
def as_str_seq(self, split=True):
return self.get(StrSeq(split=split))
'Get the value as a (Unicode) string. Equivalent to `get(unicode)` on Python 2 and `get(str)` on Python 3.'
def as_str(self):
return self.get(String())
'Whether the view contains sensitive information and should be redacted from output.'
@property def redact(self):
return (() in self.get_redactions())
'Add or remove a redaction for a key path, which should be an iterable of keys.'
def set_redaction(self, path, flag):
raise NotImplementedError()
'Get the set of currently-redacted sub-key-paths at this view.'
def get_redactions(self):
raise NotImplementedError()
'Create a configuration hierarchy for a list of sources. At least one source must be provided. The first source in the list has the highest priority.'
def __init__(self, sources):
self.sources = list(sources) self.name = ROOT_NAME self.redactions = set()
'Remove all sources (and redactions) from this configuration.'
def clear(self):
del self.sources[:] self.redactions.clear()
'Make a subview of a parent view for a given subscript key.'
def __init__(self, parent, key):
self.parent = parent self.key = key if isinstance(self.parent, RootView): self.name = '' else: self.name = self.parent.name if (not isinstance(self.key, int)): self.name += '.' if isinstance(self.key, int): self.name += u'#{0}'.format(self.key) elif is...
'If a list has less than 4 items, represent it in inline style (i.e. comma separated, within square brackets).'
def represent_list(self, data):
node = super(Dumper, self).represent_list(data) length = len(data) if ((self.default_flow_style is None) and (length < 4)): node.flow_style = True elif (self.default_flow_style is None): node.flow_style = False return node
'Represent bool as \'yes\' or \'no\' instead of \'true\' or \'false\'.'
def represent_bool(self, data):
if data: value = u'yes' else: value = u'no' return self.represent_scalar('tag:yaml.org,2002:bool', value)
'Represent a None value with nothing instead of \'none\'.'
def represent_none(self, data):
return self.represent_scalar('tag:yaml.org,2002:null', '')
'Create a configuration object by reading the automatically-discovered config files for the application for a given name. If `modname` is specified, it should be the import name of a module whose package will be searched for a default config file. (Otherwise, no defaults are used.) Pass `False` for `read` to disable au...
def __init__(self, appname, modname=None, read=True):
super(Configuration, self).__init__([]) self.appname = appname self.modname = modname self._env_var = '{0}DIR'.format(self.appname.upper()) if read: self.read()
'Points to the location of the user configuration. The file may not exist.'
def user_config_path(self):
return os.path.join(self.config_dir(), CONFIG_FILENAME)
'Add the configuration options from the YAML file in the user\'s configuration directory (given by `config_dir`) if it exists.'
def _add_user_source(self):
filename = self.user_config_path() if os.path.isfile(filename): self.add(ConfigSource((load_yaml(filename) or {}), filename))
'Add the package\'s default configuration settings. This looks for a YAML file located inside the package for the module `modname` if it was given.'
def _add_default_source(self):
if self.modname: pkg_path = _package_path(self.modname) if pkg_path: filename = os.path.join(pkg_path, DEFAULT_FILENAME) if os.path.isfile(filename): self.add(ConfigSource(load_yaml(filename), filename, True))
'Find and read the files for this configuration and set them as the sources for this configuration. To disable either discovered user configuration files or the in-package defaults, set `user` or `defaults` to `False`.'
def read(self, user=True, defaults=True):
if user: self._add_user_source() if defaults: self._add_default_source()
'Get the path to the user configuration directory. The directory is guaranteed to exist as a postcondition (one may be created if none exist). If the application\'s ``...DIR`` environment variable is set, it is used as the configuration directory. Otherwise, platform-specific standard configuration locations are search...
def config_dir(self):
if (self._env_var in os.environ): appdir = os.environ[self._env_var] appdir = os.path.abspath(os.path.expanduser(appdir)) if os.path.isfile(appdir): raise ConfigError(u'{0} must be a directory'.format(self._env_var)) else: for confdir in config_dirs(): ...
'Parses the file as YAML and inserts it into the configuration sources with highest priority.'
def set_file(self, filename):
filename = os.path.abspath(filename) self.set(ConfigSource(load_yaml(filename), filename))
'Dump the Configuration object to a YAML file. The order of the keys is determined from the default configuration file. All keys not in the default configuration will be appended to the end of the file. :param filename: The file to dump the configuration to, or None if the YAML string should be returned instead :type ...
def dump(self, full=True, redact=False):
if full: out_dict = self.flatten(redact=redact) else: sources = [s for s in self.sources if (not s.default)] temp_root = RootView(sources) temp_root.redactions = self.redactions out_dict = temp_root.flatten(redact=redact) yaml_out = yaml.dump(out_dict, Dumper=Dumper, ...
'Remove all sources from this configuration.'
def clear(self):
super(LazyConfig, self).clear() self._lazy_suffix = [] self._lazy_prefix = []
'Create a template with a given default value. If `default` is the sentinel `REQUIRED` (as it is by default), then an error will be raised when a value is missing. Otherwise, missing values will instead return `default`.'
def __init__(self, default=REQUIRED):
self.default = default
'Invoking a template on a view gets the view\'s value according to the template.'
def __call__(self, view):
return self.value(view, self)
'Get the value for a `ConfigView`. May raise a `NotFoundError` if the value is missing (and the template requires it) or a `ConfigValueError` for invalid values.'
def value(self, view, template=None):
if view.exists(): (value, _) = view.first() return self.convert(value, view) elif (self.default is REQUIRED): raise NotFoundError(u'{0} not found'.format(view.name)) else: return self.default
'Convert the YAML-deserialized value to a value of the desired type. Subclasses should override this to provide useful conversions. May raise a `ConfigValueError` when the configuration is wrong.'
def convert(self, value, view):
return value
'Raise an exception indicating that a value cannot be accepted. `type_error` indicates whether the error is due to a type mismatch rather than a malformed value. In this case, a more specific exception is raised.'
def fail(self, message, view, type_error=False):
exc_class = (ConfigTypeError if type_error else ConfigValueError) raise exc_class(u'{0}: {1}'.format(view.name, message))
'Check that the value is an integer. Floats are rounded.'
def convert(self, value, view):
if isinstance(value, int): return value elif isinstance(value, float): return int(value) else: self.fail(u'must be a number', view, True)
'Check that the value is an int or a float.'
def convert(self, value, view):
if isinstance(value, NUMERIC_TYPES): return value else: self.fail(u'must be numeric, not {0}'.format(type(value).__name__), view, True)
'Create a template according to a dict (mapping). The mapping\'s values should themselves either be Types or convertible to Types.'
def __init__(self, mapping):
subtemplates = {} for (key, typ) in mapping.items(): subtemplates[key] = as_template(typ) self.subtemplates = subtemplates
'Get a dict with the same keys as the template and values validated according to the value types.'
def value(self, view, template=None):
out = AttrDict() for (key, typ) in self.subtemplates.items(): out[key] = typ.value(view[key], self) return out
'Create a template with the added optional `pattern` argument, a regular expression string that the value should match.'
def __init__(self, default=REQUIRED, pattern=None):
super(String, self).__init__(default) self.pattern = pattern if pattern: self.regex = re.compile(pattern)
'Check that the value is a string and matches the pattern.'
def convert(self, value, view):
if isinstance(value, BASESTRING): if (self.pattern and (not self.regex.match(value))): self.fail(u'must match the pattern {0}'.format(self.pattern), view) return value else: self.fail(u'must be a string', view, True)
'Create a template that validates any of the values from the iterable `choices`. If `choices` is a map, then the corresponding value is emitted. Otherwise, the value itself is emitted.'
def __init__(self, choices):
self.choices = choices
'Ensure that the value is among the choices (and remap if the choices are a mapping).'
def convert(self, value, view):
if (value not in self.choices): self.fail(u'must be one of {0}, not {1}'.format(repr(list(self.choices)), repr(value)), view) if isinstance(self.choices, collections.Mapping): return self.choices[value] else: return value
'Ensure that the value follows at least one template.'
def convert(self, value, view):
is_mapping = isinstance(self.template, MappingTemplate) for candidate in self.allowed: try: if is_mapping: if (isinstance(candidate, Filename) and candidate.relative_to): next_template = candidate.template_with_relatives(view, self.template) ...
'Create a new template. `split` indicates whether, when the underlying value is a single string, it should be split on whitespace. Otherwise, the resulting value is a list containing a single string.'
def __init__(self, split=True):
super(StrSeq, self).__init__() self.split = split
'`relative_to` is the name of a sibling value that is being validated at the same time. `in_app_dir` indicates whether the path should be resolved inside the application\'s config directory (even when the setting does not come from a file).'
def __init__(self, default=REQUIRED, cwd=None, relative_to=None, in_app_dir=False):
super(Filename, self).__init__(default) self.cwd = cwd self.relative_to = relative_to self.in_app_dir = in_app_dir
'Create a template that checks that the value is an instance of `typ`.'
def __init__(self, typ, default=REQUIRED):
super(TypeTemplate, self).__init__(default) self.typ = typ
'Create a resizer object with an inferred method.'
def __init__(self):
self.method = self._check_method() log.debug(u'artresizer: method is {0}', self.method) self.can_compare = self._can_compare()
'Manipulate an image file according to the method, returning a new path. For PIL or IMAGEMAGIC methods, resizes the image to a temporary file. For WEBPROXY, returns `path_in` unmodified.'
def resize(self, maxwidth, path_in, path_out=None):
if self.local: func = BACKEND_FUNCS[self.method[0]] return func(maxwidth, path_in, path_out) else: return path_in
'Modifies an image URL according the method, returning a new URL. For WEBPROXY, a URL on the proxy server is returned. Otherwise, the URL is returned unmodified.'
def proxy_url(self, maxwidth, url):
if self.local: return url else: return resize_url(url, maxwidth)
'A boolean indicating whether the resizing method is performed locally (i.e., PIL or ImageMagick).'
@property def local(self):
return (self.method[0] in BACKEND_FUNCS)
'Return the size of an image file as an int couple (width, height) in pixels. Only available locally'
def get_size(self, path_in):
if self.local: func = BACKEND_GET_SIZE[self.method[0]] return func(path_in)