Пример #1
0
    def run_convert_path(self, path, *args):
        """Run the `convert` command on a given path."""
        # The path is currently a filesystem bytestring. Convert it to
        # an argument bytestring.
        path = path.decode(util._fsencoding()).encode(ui._arg_encoding())

        args = args + (b'path:' + path,)
        return self.run_command('convert', *args)
Пример #2
0
    def run_convert_path(self, path, *args):
        """Run the `convert` command on a given path."""
        # The path is currently a filesystem bytestring. Convert it to
        # an argument bytestring.
        path = path.decode(util._fsencoding()).encode(util.arg_encoding())

        args = args + (b'path:' + path, )
        return self.run_command('convert', *args)
Пример #3
0
def format_paths(path, toppath, separator="; "):
    """Attempts to decode a bytestring path to a unicode object for the
    purpose of displaying it to the user. If the `path` argument is a
    list or a tuple, the elements are joined with `separator`.
    """
    top_path = toppath.decode(_fsencoding(), 'ignore')

    if isinstance(path, (list, tuple)):
        return separator.join(format_paths(p, toppath) for p in path)
    elif isinstance(path, str):
        short_path = path.replace(top_path, '') if top_path in path else path
        return short_path

    try:
        decoded_path = path.decode(_fsencoding(), 'ignore')
        short_path = decoded_path.replace(
            top_path, '') if top_path in decoded_path else decoded_path
        return short_path
    except (UnicodeError, LookupError):
        decoded_path = path.decode('utf-8', 'ignore')
        short_path = decoded_path.replace(
            top_path, '') if top_path in decoded_path else decoded_path
        return short_path
Пример #4
0
    def create_new_album(self, album, tmplib):
        items = []
        for item in album.items():
            try:
                if not item.ipfs:
                    break
            except AttributeError:
                pass
            item_path = os.path.basename(item.path).decode(
                util._fsencoding(), 'ignore')
            # Clear current path from item
            item.path = '/ipfs/{0}/{1}'.format(album.ipfs, item_path)

            item.id = None
            items.append(item)
        if len(items) < 1:
            return False
        self._log.info("Adding '{0}' to temporary library", album)
        new_album = tmplib.add_album(items)
        new_album.ipfs = album.ipfs
        new_album.store()
Пример #5
0
    def create_new_album(self, album, tmplib):
        items = []
        for item in album.items():
            try:
                if not item.ipfs:
                    break
            except AttributeError:
                pass
            item_path = os.path.basename(item.path).decode(
                util._fsencoding(), 'ignore'
            )
            # Clear current path from item
            item.path = '/ipfs/{0}/{1}'.format(album.ipfs, item_path)

            item.id = None
            items.append(item)
        if len(items) < 1:
            return False
        self._log.info("Adding '{0}' to temporary library", album)
        new_album = tmplib.add_album(items)
        new_album.ipfs = album.ipfs
        new_album.store()
Пример #6
0
 def test_stored_hashes(self):
     test_album = self.mk_test_album()
     ipfs = IPFSPlugin()
     added_albums = ipfs.ipfs_added_albums(self.lib, self.lib.path)
     added_album = added_albums.get_album(1)
     self.assertEqual(added_album.ipfs, test_album.ipfs)
     found = False
     want_item = test_album.items()[2]
     for check_item in added_album.items():
         try:
             if check_item.ipfs:
                 ipfs_item = os.path.basename(want_item.path).decode(
                     _fsencoding(), )
                 want_path = '/ipfs/{0}/{1}'.format(test_album.ipfs,
                                                    ipfs_item)
                 want_path = bytestring_path(want_path)
                 self.assertEqual(check_item.path, want_path)
                 self.assertEqual(check_item.ipfs, want_item.ipfs)
                 self.assertEqual(check_item.title, want_item.title)
                 found = True
         except AttributeError:
             pass
     self.assertTrue(found)
Пример #7
0
 def test_stored_hashes(self):
     test_album = self.mk_test_album()
     ipfs = IPFSPlugin()
     added_albums = ipfs.ipfs_added_albums(self.lib, self.lib.path)
     added_album = added_albums.get_album(1)
     self.assertEqual(added_album.ipfs, test_album.ipfs)
     found = False
     want_item = test_album.items()[2]
     for check_item in added_album.items():
         try:
             if check_item.ipfs:
                 ipfs_item = os.path.basename(want_item.path).decode(
                     _fsencoding(),
                 )
                 want_path = '/ipfs/{0}/{1}'.format(test_album.ipfs,
                                                    ipfs_item)
                 want_path = bytestring_path(want_path)
                 self.assertEqual(check_item.path, want_path)
                 self.assertEqual(check_item.ipfs, want_item.ipfs)
                 self.assertEqual(check_item.title, want_item.title)
                 found = True
         except AttributeError:
             pass
     self.assertTrue(found)
Пример #8
0
    def encode(self, command, source, dest, pretend=False):
        """Encode `source` to `dest` using command template `command`.

        Raises `subprocess.CalledProcessError` if the command exited with a
        non-zero status code.
        """
        # The paths and arguments must be bytes.
        assert isinstance(command, bytes)
        assert isinstance(source, bytes)
        assert isinstance(dest, bytes)

        quiet = self.config['quiet'].get(bool)

        if not quiet and not pretend:
            self._log.info(u'Encoding {0}', util.displayable_path(source))

        # On Python 3, we need to construct the command to invoke as a
        # Unicode string. On Unix, this is a little unfortunate---the OS is
        # expecting bytes---so we use surrogate escaping and decode with the
        # argument encoding, which is the same encoding that will then be
        # *reversed* to recover the same bytes before invoking the OS. On
        # Windows, we want to preserve the Unicode filename "as is."
        if not six.PY2:
            command = command.decode(util.arg_encoding(), 'surrogateescape')
            if platform.system() == 'Windows':
                source = source.decode(util._fsencoding())
                dest = dest.decode(util._fsencoding())
            else:
                source = source.decode(util.arg_encoding(), 'surrogateescape')
                dest = dest.decode(util.arg_encoding(), 'surrogateescape')

        # Substitute $source and $dest in the argument list.
        args = shlex.split(command)
        encode_cmd = []
        for i, arg in enumerate(args):
            args[i] = Template(arg).safe_substitute({
                'source': source,
                'dest': dest,
            })
            if six.PY2:
                encode_cmd.append(args[i])
            else:
                encode_cmd.append(args[i].encode(util.arg_encoding()))

        if pretend:
            self._log.info(u'{0}', u' '.join(ui.decargs(args)))
            return

        try:
            util.command_output(encode_cmd)
        except subprocess.CalledProcessError as exc:
            # Something went wrong (probably Ctrl+C), remove temporary files
            self._log.info(u'Encoding {0} failed. Cleaning up...',
                           util.displayable_path(source))
            self._log.debug(u'Command {0} exited with status {1}: {2}',
                            args,
                            exc.returncode,
                            exc.output)
            util.remove(dest)
            util.prune_dirs(os.path.dirname(dest))
            raise
        except OSError as exc:
            raise ui.UserError(
                u"convert: couldn't invoke '{0}': {1}".format(
                    u' '.join(ui.decargs(args)), exc
                )
            )

        if not quiet and not pretend:
            self._log.info(u'Finished encoding {0}',
                           util.displayable_path(source))
Пример #9
0
    def encode(self, command, source, dest, pretend=False):
        """Encode `source` to `dest` using command template `command`.

        Raises `subprocess.CalledProcessError` if the command exited with a
        non-zero status code.
        """
        # The paths and arguments must be bytes.
        assert isinstance(command, bytes)
        assert isinstance(source, bytes)
        assert isinstance(dest, bytes)

        quiet = self.config['quiet'].get(bool)

        if not quiet and not pretend:
            self._log.info(u'Encoding {0}', util.displayable_path(source))

        # On Python 3, we need to construct the command to invoke as a
        # Unicode string. On Unix, this is a little unfortunate---the OS is
        # expecting bytes---so we use surrogate escaping and decode with the
        # argument encoding, which is the same encoding that will then be
        # *reversed* to recover the same bytes before invoking the OS. On
        # Windows, we want to preserve the Unicode filename "as is."
        if not six.PY2:
            command = command.decode(util.arg_encoding(), 'surrogateescape')
            if platform.system() == 'Windows':
                source = source.decode(util._fsencoding())
                dest = dest.decode(util._fsencoding())
            else:
                source = source.decode(util.arg_encoding(), 'surrogateescape')
                dest = dest.decode(util.arg_encoding(), 'surrogateescape')

        # Substitute $source and $dest in the argument list.
        args = shlex.split(command)
        encode_cmd = []
        for i, arg in enumerate(args):
            args[i] = Template(arg).safe_substitute({
                'source': source,
                'dest': dest,
            })
            if six.PY2:
                encode_cmd.append(args[i])
            else:
                encode_cmd.append(args[i].encode(util.arg_encoding()))

        if pretend:
            self._log.info(u'{0}', u' '.join(ui.decargs(args)))
            return

        try:
            util.command_output(encode_cmd)
        except subprocess.CalledProcessError as exc:
            # Something went wrong (probably Ctrl+C), remove temporary files
            self._log.info(u'Encoding {0} failed. Cleaning up...',
                           util.displayable_path(source))
            self._log.debug(u'Command {0} exited with status {1}: {2}',
                            args,
                            exc.returncode,
                            exc.output)
            util.remove(dest)
            util.prune_dirs(os.path.dirname(dest))
            raise
        except OSError as exc:
            raise ui.UserError(
                u"convert: couldn't invoke '{0}': {1}".format(
                    u' '.join(ui.decargs(args)), exc
                )
            )

        if not quiet and not pretend:
            self._log.info(u'Finished encoding {0}',
                           util.displayable_path(source))