Example #1
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))

        # Substitute $source and $dest in the argument list.
        if not six.PY2:
            command = command.decode(ui._arg_encoding(), 'surrogateescape')
            source = source.decode(ui._arg_encoding(), 'surrogateescape')
            dest = dest.decode(ui._arg_encoding(), 'surrogateescape')

        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(ui._arg_encoding()))

        if pretend:
            self._log.info(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))
Example #2
0
def _convert_args(args):
    """Convert args to bytestrings for Python 2 and convert them to strings
       on Python 3.
    """
    for i, elem in enumerate(args):
        if six.PY2:
            if isinstance(elem, six.text_type):
                args[i] = elem.encode(_arg_encoding())
        else:
            if isinstance(elem, bytes):
                args[i] = elem.decode(_arg_encoding())

    return args
Example #3
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)
Example #4
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)
Example #5
0
File: hook.py Project: pkel/beets
        def hook_function(**kwargs):
                if command is None or len(command) == 0:
                    self._log.error('invalid command "{0}"', command)
                    return

                formatted_command = command.format(event=event, **kwargs)
                encoded_command = formatted_command.decode(_arg_encoding())
                command_pieces = shlex.split(encoded_command)

                self._log.debug('Running command "{0}" for event {1}',
                                encoded_command, event)

                try:
                    subprocess.Popen(command_pieces).wait()
                except OSError as exc:
                    self._log.error('hook for {0} failed: {1}', event, exc)
Example #6
0
def has_program(cmd, args=['--version']):
    """Returns `True` if `cmd` can be executed.
    """
    full_cmd = [cmd] + args
    for i, elem in enumerate(full_cmd):
        if isinstance(elem, unicode):
            full_cmd[i] = elem.encode(_arg_encoding())
    try:
        with open(os.devnull, 'wb') as devnull:
            subprocess.check_call(full_cmd, stderr=devnull,
                                  stdout=devnull, stdin=devnull)
    except OSError:
        return False
    except subprocess.CalledProcessError:
        return False
    else:
        return True
Example #7
0
        def hook_function(**kwargs):
                if command is None or len(command) == 0:
                    self._log.error('invalid command "{0}"', command)
                    return

                formatter = CodingFormatter(_arg_encoding())
                command_pieces = shlex_split(command)

                for i, piece in enumerate(command_pieces):
                    command_pieces[i] = formatter.format(piece, event=event,
                                                         **kwargs)

                self._log.debug(u'running command "{0}" for event {1}',
                                u' '.join(command_pieces), event)

                try:
                    subprocess.Popen(command_pieces).wait()
                except OSError as exc:
                    self._log.error(u'hook for {0} failed: {1}', event, exc)
Example #8
0
File: hook.py Project: tux-00/beets
        def hook_function(**kwargs):
            if command is None or len(command) == 0:
                self._log.error('invalid command "{0}"', command)
                return

            formatter = CodingFormatter(_arg_encoding())
            command_pieces = shlex_split(command)

            for i, piece in enumerate(command_pieces):
                command_pieces[i] = formatter.format(piece,
                                                     event=event,
                                                     **kwargs)

            self._log.debug(u'running command "{0}" for event {1}',
                            u' '.join(command_pieces), event)

            try:
                subprocess.Popen(command_pieces).wait()
            except OSError as exc:
                self._log.error(u'hook for {0} failed: {1}', event, exc)
Example #9
0
 def test_format_option_unicode(self):
     l = self.run_with_output(b'ls', b'-f',
                              u'caf\xe9'.encode(ui._arg_encoding()))
     self.assertEqual(l, u'caf\xe9\n')
Example #10
0
 def test_format_option_unicode(self):
     l = self.run_with_output(b'ls', b'-f',
                              u'caf\xe9'.encode(ui._arg_encoding()))
     self.assertEqual(l, u'caf\xe9\n')
Example #11
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))

        # Substitute $source and $dest in the argument list.
        if not six.PY2:
            command = command.decode(ui._arg_encoding(), 'surrogateescape')
            source = source.decode(ui._arg_encoding(), 'surrogateescape')
            dest = dest.decode(ui._arg_encoding(), 'surrogateescape')

        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(ui._arg_encoding()))

        if pretend:
            self._log.info(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))