Use aliases for :w and :q

This commit is contained in:
Florian Bruhin 2017-07-01 21:53:12 +02:00
parent ac64ea287a
commit ac78039171
5 changed files with 19 additions and 42 deletions

View File

@ -642,8 +642,7 @@ class Quitter:
else: else:
return True return True
@cmdutils.register(instance='quitter', name=['quit', 'q'], @cmdutils.register(instance='quitter', name='quit', ignore_args=True)
ignore_args=True)
def shutdown(self, status=0, session=None, last_window=False, def shutdown(self, status=0, session=None, last_window=False,
restart=False): restart=False):
"""Quit qutebrowser. """Quit qutebrowser.

View File

@ -21,7 +21,6 @@
Module attributes: Module attributes:
cmd_dict: A mapping from command-strings to command objects. cmd_dict: A mapping from command-strings to command objects.
aliases: A list of all aliases, needed for doc generation.
""" """
import inspect import inspect
@ -30,7 +29,6 @@ from qutebrowser.utils import qtutils, log
from qutebrowser.commands import command, cmdexc from qutebrowser.commands import command, cmdexc
cmd_dict = {} cmd_dict = {}
aliases = []
def check_overflow(arg, ctype): def check_overflow(arg, ctype):
@ -88,7 +86,7 @@ class register: # pylint: disable=invalid-name
self._name = name self._name = name
self._kwargs = kwargs self._kwargs = kwargs
def _get_names(self, func): def _get_name(self, func):
"""Get the name(s) which should be used for the current command. """Get the name(s) which should be used for the current command.
If the name hasn't been overridden explicitly, the function name is If the name hasn't been overridden explicitly, the function name is
@ -105,9 +103,8 @@ class register: # pylint: disable=invalid-name
""" """
if self._name is None: if self._name is None:
return [func.__name__.lower().replace('_', '-')] return [func.__name__.lower().replace('_', '-')]
elif isinstance(self._name, str):
return [self._name]
else: else:
assert isinstance(self._name, str)
return self._name return self._name
def __call__(self, func): def __call__(self, func):
@ -124,17 +121,17 @@ class register: # pylint: disable=invalid-name
Return: Return:
The original function (unmodified). The original function (unmodified).
""" """
global aliases if self._name is None:
names = self._get_names(func) name = func.__name__.lower().replace('_', '-')
log.commands.vdebug("Registering command {}".format(names[0])) else:
for name in names: assert isinstance(self._name, str), self._name
name = self._name
log.commands.vdebug("Registering command {}".format(name))
if name in cmd_dict: if name in cmd_dict:
raise ValueError("{} is already registered!".format(name)) raise ValueError("{} is already registered!".format(name))
cmd = command.Command(name=names[0], instance=self._instance, cmd = command.Command(name=name, instance=self._instance,
handler=func, **self._kwargs) handler=func, **self._kwargs)
for name in names:
cmd_dict[name] = cmd cmd_dict[name] = cmd
aliases += names[1:]
return func return func

View File

@ -1,7 +1,9 @@
## general ## general
aliases: aliases:
default: {} default:
w: session-save
q: quit
type: type:
name: Dict name: Dict
keytype: keytype:
@ -12,11 +14,6 @@ aliases:
desc: >- desc: >-
Aliases for commands. Aliases for commands.
By default, no aliases are defined. Example which adds a new command `:qtb`
to open qutebrowsers website:
`{qtb: open https://www.qutebrowser.org/}`
auto_search: auto_search:
type: type:
name: String name: String

View File

@ -458,7 +458,7 @@ class SessionManager(QObject):
for win in old_windows: for win in old_windows:
win.close() win.close()
@cmdutils.register(name=['session-save', 'w'], instance='session-manager') @cmdutils.register(instance='session-manager')
@cmdutils.argument('name', completion=usertypes.Completion.sessions) @cmdutils.argument('name', completion=usertypes.Completion.sessions)
@cmdutils.argument('win_id', win_id=True) @cmdutils.argument('win_id', win_id=True)
@cmdutils.argument('with_private', flag='p') @cmdutils.argument('with_private', flag='p')

View File

@ -35,7 +35,6 @@ from qutebrowser.utils import usertypes, typing
def clear_globals(monkeypatch): def clear_globals(monkeypatch):
"""Clear the cmdutils globals between each test.""" """Clear the cmdutils globals between each test."""
monkeypatch.setattr(cmdutils, 'cmd_dict', {}) monkeypatch.setattr(cmdutils, 'cmd_dict', {})
monkeypatch.setattr(cmdutils, 'aliases', [])
def _get_cmd(*args, **kwargs): def _get_cmd(*args, **kwargs):
@ -88,7 +87,6 @@ class TestRegister:
assert cmd.handler is fun assert cmd.handler is fun
assert cmd.name == 'fun' assert cmd.name == 'fun'
assert len(cmdutils.cmd_dict) == 1 assert len(cmdutils.cmd_dict) == 1
assert not cmdutils.aliases
def test_underlines(self): def test_underlines(self):
"""Make sure the function name is normalized correctly (_ -> -).""" """Make sure the function name is normalized correctly (_ -> -)."""
@ -120,30 +118,16 @@ class TestRegister:
assert cmdutils.cmd_dict['foobar'].name == 'foobar' assert cmdutils.cmd_dict['foobar'].name == 'foobar'
assert 'fun' not in cmdutils.cmd_dict assert 'fun' not in cmdutils.cmd_dict
assert len(cmdutils.cmd_dict) == 1 assert len(cmdutils.cmd_dict) == 1
assert not cmdutils.aliases
def test_multiple_names(self):
"""Test register with name being a list."""
@cmdutils.register(name=['foobar', 'blub'])
def fun():
"""Blah."""
pass
assert cmdutils.cmd_dict['foobar'].name == 'foobar'
assert cmdutils.cmd_dict['blub'].name == 'foobar'
assert 'fun' not in cmdutils.cmd_dict
assert len(cmdutils.cmd_dict) == 2
assert cmdutils.aliases == ['blub']
def test_multiple_registrations(self): def test_multiple_registrations(self):
"""Make sure registering the same name twice raises ValueError.""" """Make sure registering the same name twice raises ValueError."""
@cmdutils.register(name=['foobar', 'blub']) @cmdutils.register(name='foobar')
def fun(): def fun():
"""Blah.""" """Blah."""
pass pass
with pytest.raises(ValueError): with pytest.raises(ValueError):
@cmdutils.register(name=['blah', 'blub']) @cmdutils.register(name=['foobar'])
def fun2(): def fun2():
"""Blah.""" """Blah."""
pass pass