Move all parser definitions to powerline.commands.*.get_argparser()

Reasoning: they will be easier to reach there. It will also be possible to use
specific ArgumentParser class that will just collect data for sphinx.
This commit is contained in:
ZyX 2014-10-25 16:00:32 +04:00
parent c2425f6a2a
commit fadd1eec17
9 changed files with 166 additions and 142 deletions

View File

View File

@ -0,0 +1,62 @@
# vim:fileencoding=utf-8:noet
from __future__ import (division, absolute_import, print_function)
import argparse
import powerline.bindings.config as config
TMUX_ACTIONS = {
'source': config.source_tmux_files,
}
SHELL_ACTIONS = {
'command': config.shell_command,
'uses': config.uses,
}
class ConfigArgParser(argparse.ArgumentParser):
def parse_args(self, *args, **kwargs):
ret = super(ConfigArgParser, self).parse_args(*args, **kwargs)
if not hasattr(ret, 'function'):
# In Python-3* `powerline-config` (without arguments) raises
# AttributeError. I have not found any standard way to display same
# error message as in Python-2*.
self.error('too few arguments')
return ret
def get_argparser(ArgumentParser=ConfigArgParser):
parser = ArgumentParser(description='Script used to obtain powerline configuration.')
subparsers = parser.add_subparsers()
tmux_parser = subparsers.add_parser('tmux', help='Tmux-specific commands')
tmux_parser.add_argument(
'function',
choices=tuple(TMUX_ACTIONS.values()),
metavar='action',
type=(lambda v: TMUX_ACTIONS.get(v)),
help='If action is `source\' then version-specific tmux configuration files are sourced.'
)
shell_parser = subparsers.add_parser('shell', help='Shell-specific commands')
shell_parser.add_argument(
'function',
choices=tuple(SHELL_ACTIONS.values()),
type=(lambda v: SHELL_ACTIONS.get(v)),
metavar='action',
help='If action is `command\' then preferred powerline command is output, if it is `uses\' then powerline-config script will exit with 1 if specified component is disabled and 0 otherwise.',
)
shell_parser.add_argument(
'component',
nargs='?',
choices=('tmux', 'prompt'),
metavar='component',
)
shell_parser.add_argument(
'-s', '--shell',
nargs='?',
help='Shell for which query is run',
)
return parser

View File

@ -0,0 +1,15 @@
# vim:fileencoding=utf-8:noet
from __future__ import (division, absolute_import, print_function)
import argparse
def get_argparser(ArgumentParser=argparse.ArgumentParser):
parser = ArgumentParser(description='Daemon that improves powerline performance.')
parser.add_argument('--quiet', '-q', action='store_true', help='Without other options: do not complain about already running powerline-daemon instance. Will still exit with 1. With `--kill\' and `--replace\': do not show any messages. With `--foreground\': ignored. Does not silence exceptions in any case.')
parser.add_argument('--socket', '-s', help='Specify socket which will be used for connecting to daemon.')
arggr = parser.add_mutually_exclusive_group().add_argument
arggr('--kill', '-k', action='store_true', help='Kill an already running instance.')
arggr('--foreground', '-f', action='store_true', help='Run in the foreground (dont daemonize).')
arggr('--replace', '-r', action='store_true', help='Replace an already running instance.')
return parser

View File

@ -0,0 +1,70 @@
# vim:fileencoding=utf-8:noet
# WARNING: using unicode_literals causes errors in argparse
from __future__ import (division, absolute_import, print_function)
import argparse
from powerline.lib import mergedicts, parsedotval
def mergeargs(argvalue):
if not argvalue:
return None
r = {}
for subval in argvalue:
mergedicts(r, dict([subval]))
return r
def finish_args(args):
if args.config:
args.config = mergeargs((parsedotval(v) for v in args.config))
if args.theme_option:
args.theme_option = mergeargs((parsedotval(v) for v in args.theme_option))
else:
args.theme_option = {}
if args.renderer_arg:
args.renderer_arg = mergeargs((parsedotval(v) for v in args.renderer_arg))
def get_argparser(ArgumentParser=argparse.ArgumentParser):
parser = ArgumentParser(description='Powerline prompt and statusline script.')
parser.add_argument('ext', nargs=1, help='Extension: application for which powerline command is launched (usually `shell\' or `tmux\').')
parser.add_argument('side', nargs='?', choices=('left', 'right', 'above', 'aboveleft'), help='Side: `left\' and `right\' represent left and right side respectively, `above\' emits lines that are supposed to be printed just above the prompt and `aboveleft\' is like concatenating `above\' with `left\' with the exception that only one Python instance is used in this case.')
parser.add_argument(
'-r', '--renderer_module', metavar='MODULE', type=str,
help='Renderer module. Usually something like `.bash\' or `.zsh\', is supposed to be set only in shell-specific bindings file.'
)
parser.add_argument('-w', '--width', type=int, help='Maximum prompt with. Triggers truncation of some segments.')
parser.add_argument('--last_exit_code', metavar='INT', type=int, help='Last exit code.')
parser.add_argument('--last_pipe_status', metavar='LIST', default='', type=lambda s: [int(status) for status in s.split()], help='Like above, but is supposed to contain space-separated array of statuses, representing exit statuses of commands in one pipe.')
parser.add_argument('--jobnum', metavar='INT', type=int, help='Number of jobs.')
parser.add_argument('-c', '--config', metavar='KEY.KEY=VALUE', action='append', help='Configuration overrides for `config.json\'. Is translated to a dictionary and merged with the dictionary obtained from actual JSON configuration: KEY.KEY=VALUE is translated to `{"KEY": {"KEY": VALUE}}\' and then merged recursively. VALUE may be any JSON value, values that are not `null\', `true\', `false\', start with digit, `{\', `[\' are treated like strings. If VALUE is omitted then corresponding key is removed.')
parser.add_argument('-t', '--theme_option', metavar='THEME.KEY.KEY=VALUE', action='append', help='Like above, but theme-specific. THEME should point to an existing and used theme to have any effect, but it is fine to use any theme here.')
parser.add_argument('-R', '--renderer_arg', metavar='KEY=VAL', action='append', help='Like above, but provides argument for renderer. Is supposed to be used only by shell bindings to provide various data like last_exit_code or last_pipe_status (they are not using --renderer_arg for historical resons: renderer_arg was added later).')
parser.add_argument('-p', '--config_path', action='append', metavar='PATH', help='Path to configuration directory. If it is present then configuration files will only be seeked in the provided path. May be provided multiple times to search in a list of directories.')
parser.add_argument('--socket', metavar='ADDRESS', type=str, help='Socket address to use in daemon clients. Is always UNIX domain socket on linux and file socket on Mac OS X. Not used here, present only for compatibility with other powerline clients. This argument must always be the first one and be in a form `--socket ADDRESS\': no `=\' or short form allowed (in other powerline clients, not here).')
return parser
def write_output(args, powerline, segment_info, write, encoding):
if args.renderer_arg:
segment_info.update(args.renderer_arg)
if args.side.startswith('above'):
for line in powerline.render_above_lines(
width=args.width,
segment_info=segment_info,
mode=segment_info['environ'].get('_POWERLINE_MODE'),
):
write(line.encode(encoding, 'replace'))
write(b'\n')
args.side = args.side[len('above'):]
if args.side:
rendered = powerline.render(
width=args.width,
side=args.side,
segment_info=segment_info,
mode=segment_info['environ'].get('_POWERLINE_MODE'),
)
write(rendered.encode(encoding, 'replace'))

View File

@ -1,18 +1,8 @@
# vim:fileencoding=utf-8:noet
# WARNING: using unicode_literals causes errors in argparse
from __future__ import (division, absolute_import, print_function)
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline import Powerline
from powerline.lib import mergedicts, parsedotval
def mergeargs(argvalue):
if not argvalue:
return None
r = {}
for subval in argvalue:
mergedicts(r, dict([subval]))
return r
from powerline.lib import mergedicts
class ShellPowerline(Powerline):
@ -47,60 +37,3 @@ class ShellPowerline(Powerline):
def do_setup(self, obj):
obj.powerline = self
def get_argparser(parser=None, *args, **kwargs):
if not parser:
import argparse
parser = argparse.ArgumentParser
p = parser(*args, **kwargs)
p.add_argument('ext', nargs=1, help='Extension: application for which powerline command is launched (usually `shell\' or `tmux\')')
p.add_argument('side', nargs='?', choices=('left', 'right', 'above', 'aboveleft'), help='Side: `left\' and `right\' represent left and right side respectively, `above\' emits lines that are supposed to be printed just above the prompt and `aboveleft\' is like concatenating `above\' with `left\' with the exception that only one Python instance is used in this case.')
p.add_argument(
'-r', '--renderer_module', metavar='MODULE', type=str,
help='Renderer module. Usually something like `.bash\' or `.zsh\', is supposed to be set only in shell-specific bindings file.'
)
p.add_argument('-w', '--width', type=int, help='Maximum prompt with. Triggers truncation of some segments')
p.add_argument('--last_exit_code', metavar='INT', type=int, help='Last exit code')
p.add_argument('--last_pipe_status', metavar='LIST', default='', type=lambda s: [int(status) for status in s.split()], help='Like above, but is supposed to contain space-separated array of statuses, representing exit statuses of commands in one pipe.')
p.add_argument('--jobnum', metavar='INT', type=int, help='Number of jobs.')
p.add_argument('-c', '--config', metavar='KEY.KEY=VALUE', action='append', help='Configuration overrides for `config.json\'. Is translated to a dictionary and merged with the dictionary obtained from actual JSON configuration: KEY.KEY=VALUE is translated to `{"KEY": {"KEY": VALUE}}\' and then merged recursively. VALUE may be any JSON value, values that are not `null\', `true\', `false\', start with digit, `{\', `[\' are treated like strings. If VALUE is omitted then corresponding key is removed.')
p.add_argument('-t', '--theme_option', metavar='THEME.KEY.KEY=VALUE', action='append', help='Like above, but theme-specific. THEME should point to an existing and used theme to have any effect, but it is fine to use any theme here.')
p.add_argument('-R', '--renderer_arg', metavar='KEY=VAL', action='append', help='Like above, but provides argument for renderer. Is supposed to be used only by shell bindings to provide various data like last_exit_code or last_pipe_status (they are not using --renderer_arg for historical resons: renderer_arg was added later).')
p.add_argument('-p', '--config_path', action='append', metavar='PATH', help='Path to configuration directory. If it is present then configuration files will only be seeked in the provided path. May be provided multiple times to search in a list of directories.')
p.add_argument('--socket', metavar='ADDRESS', type=str, help='Socket address to use in daemon clients. Is always UNIX domain socket on linux and file socket on Mac OS X. Not used here, present only for compatibility with other powerline clients. This argument must always be the first one and be in a form `--socket ADDRESS\': no `=\' or short form allowed (in other powerline clients, not here).')
return p
def finish_args(args):
if args.config:
args.config = mergeargs((parsedotval(v) for v in args.config))
if args.theme_option:
args.theme_option = mergeargs((parsedotval(v) for v in args.theme_option))
else:
args.theme_option = {}
if args.renderer_arg:
args.renderer_arg = mergeargs((parsedotval(v) for v in args.renderer_arg))
def write_output(args, powerline, segment_info, write, encoding):
if args.renderer_arg:
segment_info.update(args.renderer_arg)
if args.side.startswith('above'):
for line in powerline.render_above_lines(
width=args.width,
segment_info=segment_info,
mode=segment_info['environ'].get('_POWERLINE_MODE'),
):
write(line.encode(encoding, 'replace'))
write(b'\n')
args.side = args.side[len('above'):]
if args.side:
rendered = powerline.render(
width=args.width,
side=args.side,
segment_info=segment_info,
mode=segment_info['environ'].get('_POWERLINE_MODE'),
)
write(rendered.encode(encoding, 'replace'))

View File

@ -1,74 +1,22 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8:noet
'''Script used to obtain powerline configuration'''
from __future__ import (unicode_literals, division, absolute_import, print_function)
import argparse
try:
import powerline.bindings.config as config
from powerline.commands.config import get_argparser
except ImportError:
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__)))))
import powerline.bindings.config as config
from powerline.commands.config import get_argparser
TMUX_ACTIONS = {
'source': config.source_tmux_files,
}
SHELL_ACTIONS = {
'command': config.shell_command,
'uses': config.uses,
}
import powerline.bindings.config as config
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers()
tmux_parser = subparsers.add_parser('tmux', help='Tmux-specific commands')
tmux_parser.add_argument(
'function',
choices=tuple(TMUX_ACTIONS.values()),
metavar='action',
type=(lambda v: TMUX_ACTIONS.get(v)),
help='If action is `source\' then version-specific tmux configuration files are sourced.'
)
shell_parser = subparsers.add_parser('shell', help='Shell-specific commands')
shell_parser.add_argument(
'function',
choices=tuple(SHELL_ACTIONS.values()),
type=(lambda v: SHELL_ACTIONS.get(v)),
metavar='action',
help='If action is `command\' then preferred powerline command is output, if it is `uses\' then powerline-config script will exit with 1 if specified component is disabled and 0 otherwise.',
)
shell_parser.add_argument(
'component',
nargs='?',
choices=('tmux', 'prompt'),
metavar='component',
)
shell_parser.add_argument(
'-s', '--shell',
nargs='?',
help='Shell for which query is run',
)
parser = get_argparser()
args = parser.parse_args()
pl = config.create_powerline_logger(args)
try:
function = args.function
except AttributeError:
# In Python-3* `powerline-config` (without arguments) raises
# AttributeError. I have not found any standard way to display same
# error message as in Python-2*.
parser.error('too few arguments')
else:
function(pl, args)
args.function(pl, args)

View File

@ -14,10 +14,14 @@ from time import sleep
from functools import partial
from io import BytesIO
from powerline.shell import get_argparser, finish_args, ShellPowerline, write_output
from powerline.shell import ShellPowerline
from powerline.commands.main import finish_args, write_output
from powerline.lib.monotonic import monotonic
from powerline.lib.encoding import get_preferred_output_encoding
from powerline.commands.main import get_argparser as get_main_argparser
from powerline.commands.daemon import get_argparser as get_daemon_argparser
is_daemon = False
platform = sys.platform.lower()
@ -41,7 +45,7 @@ class NonInteractiveArgParser(ArgumentParser):
raise Exception(self.format_usage())
parser = get_argparser(parser=NonInteractiveArgParser, description='powerline daemon')
parser = get_main_argparser(NonInteractiveArgParser)
EOF = b'EOF\0\0'
@ -350,14 +354,7 @@ def lockpidfile():
def main():
global address
global pidfile
p = ArgumentParser(description='Daemon to improve the performance of powerline')
p.add_argument('--quiet', '-q', action='store_true', help='Without other options: do not complain about already running powerline-daemon instance. Will still exit with 1. With `--kill\' and `--replace\': do not show any messages. With `--foreground\': ignored. Does not silence exceptions in any case.')
p.add_argument('--socket', '-s', help='Specify socket which will be used for connecting to daemon.')
a = p.add_mutually_exclusive_group().add_argument
a('--kill', '-k', action='store_true', help='Kill an already running instance')
a('--foreground', '-f', action='store_true', help='Run in the foreground (dont daemonize)')
a('--replace', '-r', action='store_true', help='Replace an already running instance')
args = p.parse_args()
args = get_daemon_argparser().parse_args()
if args.socket:
address = args.socket

View File

@ -1,19 +1,18 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8:noet
'''Powerline prompt and statusline script.'''
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
import os
try:
from powerline.shell import ShellPowerline, get_argparser, finish_args, write_output
from powerline.shell import ShellPowerline
except ImportError:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__)))))
from powerline.shell import ShellPowerline, get_argparser, finish_args, write_output
from powerline.shell import ShellPowerline
from powerline.commands.main import get_argparser, finish_args, write_output
from powerline.lib.unicode import get_preferred_output_encoding
@ -24,7 +23,7 @@ else:
if __name__ == '__main__':
args = get_argparser(description=__doc__).parse_args()
args = get_argparser().parse_args()
finish_args(args)
powerline = ShellPowerline(args, run_once=True)
segment_info = {'args': args, 'environ': os.environ}

View File

@ -11,7 +11,7 @@ if sys.version_info < (3,):
else:
from io import StringIO as StrIO
from powerline.shell import get_argparser, finish_args
from powerline.commands.main import get_argparser, finish_args
from tests import TestCase
from tests.lib import replace_attr