Exemplo n.º 1
0
def _process_item(item,
                  lib,
                  copy=False,
                  move=False,
                  delete=False,
                  tag=False,
                  format=None):
    """Process Item `item` in `lib`.
    """
    if copy:
        item.move_file(dest=copy, copy=True)
        item.store()
    if move:
        item.move_file(dest=move, copy=False)
        item.store()
    if delete:
        item.remove(delete=True)
    if tag:
        try:
            k, v = tag.split('=')
        except:
            raise UserError('%s: can\'t parse k=v tag: %s' % (PLUGIN, tag))
        setattr(k, v)
        item.store()
    print_obj(item, lib, fmt=format)
Exemplo n.º 2
0
 def _process_item(self,
                   item,
                   copy=False,
                   move=False,
                   delete=False,
                   tag=False,
                   fmt=u''):
     """Process Item `item`.
     """
     print_(format(item, fmt))
     if copy:
         item.move(basedir=copy, copy=True)
         item.store()
     if move:
         item.move(basedir=move, copy=False)
         item.store()
     if delete:
         item.remove(delete=True)
     if tag:
         try:
             k, v = tag.split('=')
         except Exception:
             raise UserError(u"{}: can't parse k=v tag: {}".format(
                 PLUGIN, tag))
         setattr(item, k, v)
         item.store()
Exemplo n.º 3
0
 def _process_item(self,
                   item,
                   copy=False,
                   move=False,
                   delete=False,
                   tag=False,
                   fmt=''):
     """Process Item `item`.
     """
     print_(format(item, fmt))
     if copy:
         item.move(basedir=copy, operation=MoveOperation.COPY)
         item.store()
     if move:
         item.move(basedir=move)
         item.store()
     if delete:
         item.remove(delete=True)
     if tag:
         try:
             k, v = tag.split('=')
         except Exception:
             raise UserError(f"{PLUGIN}: can't parse k=v tag: {tag}")
         setattr(item, k, v)
         item.store()
Exemplo n.º 4
0
 def update(self, lib, options):
     try:
         alt = self.alternative(options.name, lib)
     except KeyError as e:
         raise UserError(u"Alternative collection '{0}' not found.".format(
             e.args[0]))
     alt.update(create=options.create)
Exemplo n.º 5
0
    def loaded(self):
        found_plugins = set()
        for plugin in find_plugins():
            if plugin.name in self.needed_plugins:
                found_plugins.add(plugin.name)

            if plugin.name == "savedqueries":
                self.queryfunc = plugin.item_queries["query"]

        for plugin_name in self.needed_plugins:
            if plugin_name not in found_plugins:
                raise UserError(
                    f"`{plugin_name}` plugin is required to use the `{self.name}` plugin"
                )

        self.savedqueries = FactoryDict(lambda name: self.queryfunc(name))
        self.template_fields = {
            "navigation_path": self.navigation_path,
        }

        self.funcs = beets.plugins.template_funcs()
        self.the = self.funcs["the"]
        self.replacefunc = self.funcs["replace"]
        self.bucket = self.funcs["bucket"]
        self.asciify = DefaultTemplateFunctions.tmpl_asciify
Exemplo n.º 6
0
 def _process_item(self,
                   item,
                   lib,
                   copy=False,
                   move=False,
                   delete=False,
                   tag=False,
                   fmt=''):
     """Process Item `item` in `lib`.
     """
     if copy:
         item.move(basedir=copy, copy=True)
         item.store()
     if move:
         item.move(basedir=move, copy=False)
         item.store()
     if delete:
         item.remove(delete=True)
     if tag:
         try:
             k, v = tag.split('=')
         except:
             raise UserError('%s: can\'t parse k=v tag: %s' % (PLUGIN, tag))
         setattr(k, v)
         item.store()
     print_(format(item, fmt))
Exemplo n.º 7
0
def get_replacements(config):
    replacements = []
    for pattern, repl in config.get(dict).items():
        try:
            replacements.append((re.compile(pattern), repl or ""))
        except re.error as exc:
            raise UserError(f"error compiling regex `{pattern}`: {exc}")
    return replacements
Exemplo n.º 8
0
    def check(self, external):
        if external and not IntegrityChecker.allAvailable():
            no_checkers_warning = u"No integrity checkers found. " \
                                  "Run 'beet check --list-tools'"
            raise UserError(no_checkers_warning)

        if external:
            progs = list(map(lambda c: c.name,
                             IntegrityChecker.allAvailable()))
            plural = 's' if len(progs) > 1 else ''
            self.log(u'Using integrity checker{} {}'.format(
                plural, ', '.join(progs)))

        items = list(self.lib.items(self.query))
        failures = [0]

        def check(item):
            try:
                if external:
                    verify_integrity(item)
                elif item.get('checksum', None):
                    verify_checksum(item)
                log.debug(u'{}: {}'.format(colorize('green', u'OK'),
                                           displayable_path(item.path)))
            except ChecksumError:
                log.error(u'{}: {}'.format(colorize('red', u'FAILED'),
                                           displayable_path(item.path)))
                failures[0] += 1
            except IntegrityError as ex:
                log.warning(u'{} {}: {}'.format(colorize('yellow', u'WARNING'),
                                                ex.reason,
                                                displayable_path(item.path)))
                failures[0] += 1
            except IOError as exc:
                log.error(u'{} {}'.format(colorize('red', u'ERROR'), exc))
                failures[0] += 1

        if external:
            msg = u'Running external tests'
        else:
            msg = u'Verifying checksums'
        self.execute_with_progress(check, items, msg)

        failures = failures[0]
        if external:
            if failures:
                self.log(u'Found {} integrity error(s)'.format(failures))
                sys.exit(15)
            else:
                self.log(u'Integrity successfully verified')
        else:
            if failures:
                self.log(u'Failed to verify checksum of {} file(s)'.format(
                    failures))
                sys.exit(15)
            else:
                self.log(u'All checksums successfully verified')
Exemplo n.º 9
0
    def sub_path(self, path, pattern, repl=''):
        if pattern in self.patterns:
            pattern = self.patterns[pattern]
        else:
            pattern = self.patterns[pattern] = re.compile(pattern)

        try:
            return util.sanitize_path(path, [(pattern, repl)])
        except re.error as exc:
            raise UserError(u'%sub_path: error compiling regex `{0}`: {1}'.format(pattern, str(exc)))
Exemplo n.º 10
0
    def sub(self, string, pattern, repl=''):
        if pattern in self.patterns:
            pattern = self.patterns[pattern]
        else:
            pattern = self.patterns[pattern] = re.compile(pattern)

        try:
            return pattern.sub(repl, string)
        except re.error as exc:
            raise UserError(u'%sub: error compiling regex `{0}`: {1}'.format(pattern, str(exc)))
Exemplo n.º 11
0
    def replace(self, field, path):
        if field in self.replacements:
            replacements = self.replacements[field]
        else:
            try:
                replacements = self.replacements[field] = get_replacements(
                    self.config[field])
            except confuse.ConfigError as exc:
                raise UserError(
                    f"Configuration error in `{self.name}.{field}`: {exc}")

        return util.sanitize_path(path, replacements)
Exemplo n.º 12
0
        def _dup(lib, opts, args):
            self.config.set_args(opts)
            fmt = self.config['format'].get()
            album = self.config['album'].get(bool)
            full = self.config['full'].get(bool)
            strict = self.config['strict'].get(bool)
            keys = self.config['keys'].get()
            checksum = self.config['checksum'].get()
            copy = self.config['copy'].get()
            move = self.config['move'].get()
            delete = self.config['delete'].get(bool)
            tag = self.config['tag'].get()

            if album:
                keys = ['mb_albumid']
                items = lib.albums(decargs(args))
            else:
                items = lib.items(decargs(args))

            if self.config['path']:
                fmt = '$path'

            # Default format string for count mode.
            if self.config['count'] and not fmt:
                if album:
                    fmt = '$albumartist - $album'
                else:
                    fmt = '$albumartist - $album - $title'
                fmt += ': {0}'

            if checksum:
                if not isinstance(checksum, basestring):
                    raise UserError(
                        'duplicates: "checksum" option must be a command')
                for i in items:
                    k, _ = self._checksum(i, checksum)
                keys = [k]

            for obj_id, obj_count, objs in self._duplicates(items,
                                                            keys=keys,
                                                            full=full,
                                                            strict=strict):
                if obj_id:  # Skip empty IDs.
                    for o in objs:
                        self._process_item(o,
                                           lib,
                                           copy=copy,
                                           move=move,
                                           delete=delete,
                                           tag=tag,
                                           fmt=fmt.format(obj_count))
Exemplo n.º 13
0
    def start_session(self, path: str):
        self.set_is_busy(True)
        logger.info(f"Starting import session with path: {path}")
        if config['import']['log'].get() is not None:
            logpath = config['import']['log'].as_filename()
            try:
                loghandler = logging.FileHandler(logpath)
            except IOError:
                raise UserError(
                    f"Could not open log file for writing: {logpath}")
        else:
            loghandler = None

        session = TurnipImporter(self._lib, loghandler, [path], None,
                                 self.adapter)
        session.start()
        return session.track_count
Exemplo n.º 14
0
    def start_session(self, path: str):
        logger.info(f"Starting logging session with path: {path}")
        if config['import']['log'].get() is not None:
            logpath = config['import']['log'].as_filename()
            try:
                loghandler = logging.FileHandler(logpath)
            except IOError:
                raise UserError(
                    f"could not open log file for writing: {logpath}")
        else:
            loghandler = None

        self._session = TurnipImportSession(self._lib, loghandler, [path],
                                            None)
        self._session.set_callback(self.set_current_item)
        self._session.set_loading_callback(self.set_loading_status)
        self._session.set_ask_resume_callback(self.ask_resume)
        self._session.start()
Exemplo n.º 15
0
def identify_releases(release_paths):
    '''
    Given an iterator of release paths, this will attempt to identify
    each release and return a list of corresponding Release objects.

    Releases that could not be identified will not be present in the list.

    Note: This function will ask for user input.
    '''
    for path in release_paths:
        if not os.path.exists(syspath(normpath(path))):
            raise UserError(u'no such file or directory: {0}'.format(
                displayable_path(path)))

    result = []
    session = IdentifySession(release_paths, result)
    session.run()
    return result