desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Decide what to do when a new album or item seems similar to one that\'s already in the library.'
def resolve_duplicate(self, task, found_duplicates):
log.warning(u'This {0} is already in the library!', (u'album' if task.is_album else u'item')) if config['import']['quiet']: log.info(u'Skipping.') sel = u's' else: for duplicate in found_duplicates: print_((u'Old: ' + summarize_items((list(duplicate.i...
'Get the list of prompt choices that should be presented to the user. This consists of both built-in choices and ones provided by plugins. The `before_choose_candidate` event is sent to the plugins, with session and task as its parameters. Plugins are responsible for checking the right conditions and returning a list o...
def _get_choices(self, task):
choices = [PromptChoice(u's', u'Skip', (lambda s, t: importer.action.SKIP)), PromptChoice(u'u', u'Use as-is', (lambda s, t: importer.action.ASIS))] if task.is_album: choices += [PromptChoice(u't', u'as Tracks', (lambda s, t: importer.action.TRACKS)), PromptChoice(u'g', u'Group albums', (lambda ...
'Create a session. `lib` is a Library object. `loghandler` is a logging.Handler. Either `paths` or `query` is non-null and indicates the source of files to be imported.'
def __init__(self, lib, loghandler, paths, query):
self.lib = lib self.logger = self._setup_logging(loghandler) self.paths = paths self.query = query self._is_resuming = dict() if self.paths: self.paths = list(map(normpath, self.paths))
'Set `config` property from global import config and make implied changes.'
def set_config(self, config):
iconfig = dict(config) self.config = iconfig if iconfig['incremental']: iconfig['resume'] = False if (self.query is not None): iconfig['resume'] = False iconfig['incremental'] = False if iconfig['move']: iconfig['copy'] = False iconfig['link'] = False ...
'Log a message about a given album to the importer log. The status should reflect the reason the album couldn\'t be tagged.'
def tag_log(self, status, paths):
self.logger.info(u'{0} {1}', status, displayable_path(paths))
'Logs the task\'s current choice if it should be logged. If ``duplicate``, then this is a secondary choice after a duplicate was detected and a decision was made.'
def log_choice(self, task, duplicate=False):
paths = task.paths if duplicate: if task.should_remove_duplicates: self.tag_log(u'duplicate-replace', paths) elif (task.choice_flag in (action.ASIS, action.APPLY)): self.tag_log(u'duplicate-keep', paths) elif (task.choice_flag is action.SKIP): self.tag...
'Run the import task.'
def run(self):
self.logger.info(u'import started {0}', time.asctime()) self.set_config(config['import']) if (self.query is None): stages = [read_tasks(self)] else: stages = [query_tasks(self)] if self.config['pretend']: stages += [log_files(self)] else: if (self.config['gr...
'Returns true if the files belonging to this task have already been imported in a previous session.'
def already_imported(self, toppath, paths):
if (self.is_resuming(toppath) and all([progress_element(toppath, p) for p in paths])): return True if (self.config['incremental'] and (tuple(paths) in self.history_dirs)): return True return False
'Return `True` if user wants to resume import of this path. You have to call `ask_resume` first to determine the return value.'
def is_resuming(self, toppath):
return self._is_resuming.get(toppath, False)
'If import of `toppath` was aborted in an earlier session, ask user if she wants to resume the import. Determines the return value of `is_resuming(toppath)`.'
def ask_resume(self, toppath):
if (self.want_resume and has_progress(toppath)): if ((self.want_resume is True) or self.should_resume(toppath)): log.warning(u'Resuming interrupted import of {0}', util.displayable_path(toppath)) self._is_resuming[toppath] = True else: progress_reset(t...
'Create a task. The primary fields that define a task are: * `toppath`: The user-specified base directory that contains the music for this task. If the task has *no* user-specified base (for example, when importing based on an -L query), this can be None. This is used for tracking progress and history. * `paths`: A lis...
def __init__(self, toppath, paths, items):
self.toppath = toppath self.paths = paths self.items = items
'Given an AlbumMatch or TrackMatch object or an action constant, indicates that an action has been selected for this task.'
def set_choice(self, choice):
assert (choice != action.APPLY) if (choice in (action.SKIP, action.ASIS, action.TRACKS, action.ALBUMS, action.RETAG)): self.choice_flag = choice self.match = None else: self.choice_flag = action.APPLY self.match = choice
'Updates the progress state to indicate that this album has finished.'
def save_progress(self):
if self.toppath: progress_add(self.toppath, *self.paths)
'Save the directory in the history for incremental imports.'
def save_history(self):
if self.paths: history_add(self.paths)
'Returns identifying metadata about the current choice. For albums, this is an (artist, album) pair. For items, this is (artist, title). May only be called when the choice flag is ASIS or RETAG (in which case the data comes from the files\' current metadata) or APPLY (data comes from the choice).'
def chosen_ident(self):
if (self.choice_flag in (action.ASIS, action.RETAG)): return (self.cur_artist, self.cur_album) elif (self.choice_flag is action.APPLY): return (self.match.info.artist, self.match.info.album)
'Return a list of Items that should be added to the library. If the tasks applies an album match the method only returns the matched items.'
def imported_items(self):
if (self.choice_flag in (action.ASIS, action.RETAG)): return list(self.items) elif (self.choice_flag == action.APPLY): return list(self.match.mapping.keys()) else: assert False
'Copy metadata from match info to the items.'
def apply_metadata(self):
autotag.apply_metadata(self.match.info, self.match.mapping)
'Sets the fields given at CLI or configuration to the specified values.'
def set_fields(self):
for (field, view) in config['import']['set_fields'].items(): value = view.get() log.debug(u'Set field {1}={2} for {0}', displayable_path(self.paths), field, value) self.album[field] = value self.album.store()
'Save progress, clean up files, and emit plugin event.'
def finalize(self, session):
if session.want_resume: self.save_progress() if session.config['incremental']: self.save_history() self.cleanup(copy=session.config['copy'], delete=session.config['delete'], move=session.config['move']) if (not self.skip): self._emit_imported(session.lib)
'Remove and prune imported paths.'
def cleanup(self, copy=False, delete=False, move=False):
if self.skip: return items = self.imported_items() if (copy and delete): new_paths = [os.path.realpath(item.path) for item in items] for old_path in self.old_paths: if (old_path not in new_paths): util.remove(syspath(old_path), False) self....
'Send the `import_task_created` event for this task. Return a list of tasks that should continue through the pipeline. By default, this is a list containing only the task itself, but plugins can replace the task with new ones.'
def handle_created(self, session):
tasks = plugins.send('import_task_created', session=session, task=self) if (not tasks): tasks = [self] else: tasks = [t for inner in tasks for t in inner] return tasks
'Retrieve and store candidates for this album. User-specified candidate IDs are stored in self.search_ids: if present, the initial lookup is restricted to only those IDs.'
def lookup_candidates(self):
(artist, album, prop) = autotag.tag_album(self.items, search_ids=self.search_ids) self.cur_artist = artist self.cur_album = album self.candidates = prop.candidates self.rec = prop.recommendation
'Return a list of albums from `lib` with the same artist and album name as the task.'
def find_duplicates(self, lib):
(artist, album) = self.chosen_ident() if (artist is None): return [] duplicates = [] task_paths = set((i.path for i in self.items if i)) duplicate_query = dbcore.AndQuery((dbcore.MatchQuery('albumartist', artist), dbcore.MatchQuery('album', album))) for album in lib.albums(duplicate_quer...
'Make some album fields equal across `self.items`. For the RETAG action, we assume that the responsible for returning it (ie. a plugin) always ensures that the first item contains valid data on the relevant fields.'
def align_album_level_fields(self):
changes = {} if (self.choice_flag == action.ASIS): (plur_albumartist, freq) = util.plurality([(i.albumartist or i.artist) for i in self.items]) if ((freq == len(self.items)) or ((freq > 1) and ((float(freq) / len(self.items)) >= SINGLE_ARTIST_THRESH))): changes['albumartist'] = plur_...
'Add the items as an album to the library and remove replaced items.'
def add(self, lib):
self.align_album_level_fields() with lib.transaction(): self.record_replaced(lib) self.remove_replaced(lib) self.album = lib.add_album(self.imported_items()) self.reimport_metadata(lib)
'Records the replaced items and albums in the `replaced_items` and `replaced_albums` dictionaries.'
def record_replaced(self, lib):
self.replaced_items = defaultdict(list) self.replaced_albums = defaultdict(list) replaced_album_ids = set() for item in self.imported_items(): dup_items = list(lib.items(dbcore.query.BytesQuery('path', item.path))) self.replaced_items[item] = dup_items for dup_item in dup_items: ...
'For reimports, preserves metadata for reimported items and albums.'
def reimport_metadata(self, lib):
if self.is_album: replaced_album = self.replaced_albums.get(self.album.path) if replaced_album: self.album.added = replaced_album.added self.album.update(replaced_album._values_flex) self.album.artpath = replaced_album.artpath self.album.store() ...
'Removes all the items from the library that have the same path as an item from this task.'
def remove_replaced(self, lib):
for item in self.imported_items(): for dup_item in self.replaced_items[item]: log.debug(u'Replacing item {0}: {1}', dup_item.id, displayable_path(item.path)) dup_item.remove() log.debug(u'{0} of {1} items replaced', sum((bool(l) for l in self.replaced_items.v...
'Ask the session which match should apply and apply it.'
def choose_match(self, session):
choice = session.choose_match(self) self.set_choice(choice) session.log_choice(self)
'Reload albums and items from the database.'
def reload(self):
for item in self.imported_items(): item.load() self.album.load()
'Prune any empty directories above the given file. If this task has no `toppath` or the file path provided is not within the `toppath`, then this function has no effect. Similarly, if the file still exists, no pruning is performed, so it\'s safe to call when the file in question may not have been removed.'
def prune(self, filename):
if (self.toppath and (not os.path.exists(filename))): util.prune_dirs(os.path.dirname(filename), self.toppath, clutter=config['clutter'].as_str_seq())
'Return a list of items from `lib` that have the same artist and title as the task.'
def find_duplicates(self, lib):
(artist, title) = self.chosen_ident() found_items = [] query = dbcore.AndQuery((dbcore.MatchQuery('artist', artist), dbcore.MatchQuery('title', title))) for other_item in lib.items(query): if (other_item.path != self.item.path): found_items.append(other_item) return found_items
'Ask the session which match should apply and apply it.'
def choose_match(self, session):
choice = session.choose_item(self) self.set_choice(choice) session.log_choice(self)
'Sets the fields given at CLI or configuration to the specified values.'
def set_fields(self):
for (field, view) in config['import']['set_fields'].items(): value = view.get() log.debug(u'Set field {1}={2} for {0}', displayable_path(self.paths), field, value) self.item[field] = value self.item.store()
'Returns true if the given path points to an archive that can be handled.'
@classmethod def is_archive(cls, path):
if (not os.path.isfile(path)): return False for (path_test, _) in cls.handlers(): if path_test(util.py3_path(path)): return True return False
'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()