Use *args for commands where possible.

This commit is contained in:
Florian Bruhin 2014-09-14 23:09:01 +02:00
parent f1f05516b3
commit 1fd8fb57a6
3 changed files with 15 additions and 26 deletions

View File

@ -20,7 +20,6 @@
"""A HintManager to draw hints over links.""" """A HintManager to draw hints over links."""
import math import math
import shlex
import subprocess import subprocess
import collections import collections
@ -453,7 +452,7 @@ class HintManager(QObject):
f.contentsSizeChanged.connect(self.on_contents_size_changed) f.contentsSizeChanged.connect(self.on_contents_size_changed)
self._context.connected_frames.append(f) self._context.connected_frames.append(f)
def _check_args(self, target, args): def _check_args(self, target, *args):
"""Check the arguments passed to start() and raise if they're wrong. """Check the arguments passed to start() and raise if they're wrong.
Args: Args:
@ -463,11 +462,11 @@ class HintManager(QObject):
if not isinstance(target, Target): if not isinstance(target, Target):
raise TypeError("Target {} is no Target member!".format(target)) raise TypeError("Target {} is no Target member!".format(target))
if target in (Target.userscript, Target.spawn, Target.fill): if target in (Target.userscript, Target.spawn, Target.fill):
if args is None: if not args:
raise cmdexc.CommandError( raise cmdexc.CommandError(
"'args' is required with target userscript/spawn/fill.") "'args' is required with target userscript/spawn/fill.")
else: else:
if args is not None: if args:
raise cmdexc.CommandError( raise cmdexc.CommandError(
"'args' is only allowed with target userscript/spawn.") "'args' is only allowed with target userscript/spawn.")
@ -513,7 +512,7 @@ class HintManager(QObject):
self.openurl.emit(url, newtab) self.openurl.emit(url, newtab)
def start(self, mainframe, baseurl, group=webelem.Group.all, def start(self, mainframe, baseurl, group=webelem.Group.all,
target=Target.normal, args=None): target=Target.normal, *args):
"""Start hinting. """Start hinting.
Args: Args:
@ -521,12 +520,12 @@ class HintManager(QObject):
baseurl: URL of the current page. baseurl: URL of the current page.
group: Which group of elements to hint. group: Which group of elements to hint.
target: What to do with the link. See attribute docstring. target: What to do with the link. See attribute docstring.
args: Arguments for userscript/download *args: Arguments for userscript/download
Emit: Emit:
hint_strings_updated: Emitted to update keypraser. hint_strings_updated: Emitted to update keypraser.
""" """
self._check_args(target, args) self._check_args(target, *args)
if mainframe is None: if mainframe is None:
# This should never happen since we check frame before calling # This should never happen since we check frame before calling
# start. But since we had a bug where frame is None in # start. But since we had a bug where frame is None in
@ -536,13 +535,7 @@ class HintManager(QObject):
self._context.target = target self._context.target = target
self._context.baseurl = baseurl self._context.baseurl = baseurl
self._context.frames = webelem.get_child_frames(mainframe) self._context.frames = webelem.get_child_frames(mainframe)
if args is None: self._context.args = args
self._context.args = None
else:
try:
self._context.args = shlex.split(args)
except ValueError as e:
raise cmdexc.CommandError("Could not split args: {}".format(e))
self._init_elements(mainframe, group) self._init_elements(mainframe, group)
message.instance().set_text(self.HINT_TEXTS[target]) message.instance().set_text(self.HINT_TEXTS[target])
self._connect_frame_signals() self._connect_frame_signals()

View File

@ -120,12 +120,12 @@ class KeyConfigParser(QObject):
f.write(str(self)) f.write(str(self))
@cmdutils.register(instance='keyconfig') @cmdutils.register(instance='keyconfig')
def bind(self, key, command, mode=None): def bind(self, key, *command, mode=None):
"""Bind a key to a command. """Bind a key to a command.
Args: Args:
key: The keychain or special key (inside `<...>`) to bind. key: The keychain or special key (inside `<...>`) to bind.
command: The command to execute. *command: The command to execute, with optional args.
mode: A comma-separated list of modes to bind the key in mode: A comma-separated list of modes to bind the key in
(default: `normal`). (default: `normal`).
""" """
@ -135,10 +135,10 @@ class KeyConfigParser(QObject):
for m in mode.split(','): for m in mode.split(','):
if m not in configdata.KEY_DATA: if m not in configdata.KEY_DATA:
raise cmdexc.CommandError("Invalid mode {}!".format(m)) raise cmdexc.CommandError("Invalid mode {}!".format(m))
if command.split(maxsplit=1)[0] not in cmdutils.cmd_dict: if command[0] not in cmdutils.cmd_dict:
raise cmdexc.CommandError("Invalid command {}!".format(command)) raise cmdexc.CommandError("Invalid command {}!".format(command[0]))
try: try:
self._add_binding(mode, key, command) self._add_binding(mode, key, *command)
except KeyConfigError as e: except KeyConfigError as e:
raise cmdexc.CommandError(e) raise cmdexc.CommandError(e)
for m in mode.split(','): for m in mode.split(','):

View File

@ -19,7 +19,6 @@
"""Misc. utility commands exposed to the user.""" """Misc. utility commands exposed to the user."""
import shlex
import types import types
import functools import functools
@ -42,12 +41,12 @@ def init():
@cmdutils.register() @cmdutils.register()
def later(ms: int, command): def later(ms: int, *command):
"""Execute a command after some time. """Execute a command after some time.
Args: Args:
ms: How many milliseconds to wait. ms: How many milliseconds to wait.
command: The command to run. *command: The command to run, with optional args.
""" """
timer = usertypes.Timer(name='later') timer = usertypes.Timer(name='later')
timer.setSingleShot(True) timer.setSingleShot(True)
@ -59,10 +58,7 @@ def later(ms: int, command):
raise cmdexc.CommandError("Numeric argument is too large for internal " raise cmdexc.CommandError("Numeric argument is too large for internal "
"int representation.") "int representation.")
_timers.append(timer) _timers.append(timer)
try: cmdline = ' '.join(command)
cmdline = shlex.split(command)
except ValueError as e:
raise cmdexc.CommandError("Could not split command: {}".format(e))
timer.timeout.connect(functools.partial( timer.timeout.connect(functools.partial(
_commandrunner.run_safely, cmdline)) _commandrunner.run_safely, cmdline))
timer.timeout.connect(lambda: _timers.remove(timer)) timer.timeout.connect(lambda: _timers.remove(timer))