Fix zsh/zpython issue

This commit is contained in:
Foo 2013-02-25 00:45:40 +04:00 committed by Kim Silkebækken
parent dfaf381040
commit 43d9639534
7 changed files with 89 additions and 37 deletions

View File

@ -420,6 +420,33 @@ Powerline script has a number of options controlling powerline behavior. Here
performed by powerline script itself, but ``-p ~/.powerline`` will likely be performed by powerline script itself, but ``-p ~/.powerline`` will likely be
expanded by the shell to something like ``-p /home/user/.powerline``. expanded by the shell to something like ``-p /home/user/.powerline``.
Zsh/zpython overrides
---------------------
Here overrides are controlled by similarly to the powerline script, but values
are taken from zsh variables.
``POWERLINE_CONFIG``
Overrides options from :file:`powerline/config.json`. Should be a zsh
associative array with keys equal to ``KEY.NESTED_KEY`` and values being
JSON strings. Pair ``KEY.KEY1 VALUE`` is equivalent to ``{"KEY": {"KEY1":
VALUE}}``. All pairs are then recursively merged into one dictionary and
this dictionary is recursively merged with the contents of the file.
``POWERLINE_THEME_CONFIG``
Overrides options from :file:`powerline/themes/shell/*.json`. Should be
a zsh associative array with keys equal to ``THEME_NAME.KEY.NESTED_KEY`` and
values being JSON strings. Is processed like the above ``POWERLINE_CONFIG``,
but only subdictionaries for ``THEME_NAME`` key are merged with theme
configuration when theme with given name is requested.
``POWERLINE_CONFIG_PATH``
Sets directory where configuration should be read from. If present, no
default locations are searched for configuration. No expansions are
performed by powerline script itself, but zsh usually performs them on its
own if you set variable without quotes: ``POWERLINE_CONFIG_PATH=~/example``.
Expansion depends on zsh configuration.
Ipython overrides Ipython overrides
----------------- -----------------

View File

@ -1,11 +1,11 @@
import zsh import zsh
import json
from powerline.shell import ShellPowerline from powerline.shell import ShellPowerline
from powerline.lib import parsedotval
def get_var_config(var): def get_var_config(var):
try: try:
return dict(((k, json.loads(v)) for k, v in zsh.getvalue(var).items())) return [parsedotval(i) for i in zsh.getvalue(var).items()]
except: except:
return None return None
@ -24,11 +24,24 @@ class Args(object):
@property @property
def config(self): def config(self):
return get_var_config('POWERLINE_CONFIG') try:
return get_var_config('POWERLINE_CONFIG')
except IndexError:
return None
@property @property
def theme_option(self): def theme_option(self):
return get_var_config('POWERLINE_THEME_CONFIG') try:
return get_var_config('POWERLINE_THEME_CONFIG')
except IndexError:
return None
@property
def config_path(self):
try:
return zsh.getvalue('POWERLINE_CONFIG_PATH')
except IndexError:
return None
class Prompt(object): class Prompt(object):

View File

@ -29,6 +29,14 @@ def pick_gradient_value(grad_list, gradient_level):
return grad_list[int(round(gradient_level * (len(grad_list) - 1) / 100))] return grad_list[int(round(gradient_level * (len(grad_list) - 1) / 100))]
def hl_iter(value):
if type(value) is list:
for v in value:
yield v
else:
yield value
class Colorscheme(object): class Colorscheme(object):
def __init__(self, colorscheme_config, colors_config): def __init__(self, colorscheme_config, colors_config):
'''Initialize a colorscheme.''' '''Initialize a colorscheme.'''
@ -64,7 +72,7 @@ class Colorscheme(object):
def get_highlighting(self, groups, mode, gradient_level=None): def get_highlighting(self, groups, mode, gradient_level=None):
trans = self.translations.get(mode, {}) trans = self.translations.get(mode, {})
for group in groups: for group in hl_iter(groups):
if 'groups' in trans and group in trans['groups']: if 'groups' in trans and group in trans['groups']:
try: try:
group_props = trans['groups'][group] group_props = trans['groups'][group]

View File

@ -1,4 +1,5 @@
from functools import wraps from functools import wraps
import json
from powerline.lib.memoize import memoize # NOQA from powerline.lib.memoize import memoize # NOQA
from powerline.lib.humanize_bytes import humanize_bytes # NOQA from powerline.lib.humanize_bytes import humanize_bytes # NOQA
@ -34,3 +35,33 @@ def add_divider_highlight_group(highlight_group):
return None return None
return f return f
return dec return dec
def keyvaluesplit(s):
if '=' not in s:
raise TypeError('Option must look like option=json_value')
if s[0] == '_':
raise ValueError('Option names must not start with `_\'')
idx = s.index('=')
o = s[:idx]
val = json.loads(s[idx+1:])
return (o, val)
def parsedotval(s):
if type(s) is tuple:
o, val = s
else:
o, val = keyvaluesplit(s)
keys = o.split('.')
if len(keys) > 1:
r = (keys[0], {})
rcur = r[1]
for key in keys[1:-1]:
rcur[key] = {}
rcur = rcur[key]
rcur[keys[-1]] = val
return r
else:
return (o, val)

View File

@ -30,7 +30,7 @@ class Renderer(object):
def get_highlighting(self, segment, mode): def get_highlighting(self, segment, mode):
segment['highlight'] = self.colorscheme.get_highlighting(segment['highlight_group'], mode, segment.get('gradient_level')) segment['highlight'] = self.colorscheme.get_highlighting(segment['highlight_group'], mode, segment.get('gradient_level'))
if segment['divider_highlight_group']: if segment['divider_highlight_group']:
segment['divider_highlight'] = self.colorscheme.get_highlighting([segment['divider_highlight_group']], mode) segment['divider_highlight'] = self.colorscheme.get_highlighting(segment['divider_highlight_group'], mode)
else: else:
segment['divider_highlight'] = None segment['divider_highlight'] = None
return segment return segment

View File

@ -45,10 +45,6 @@ segment_getters = {
} }
def scalar_to_list(value):
return value if type(value) is list else [value]
def gen_segment_getter(ext, path, theme_configs, default_module=None): def gen_segment_getter(ext, path, theme_configs, default_module=None):
data = { data = {
'default_module': default_module or 'powerline.segments.' + ext, 'default_module': default_module or 'powerline.segments.' + ext,
@ -69,7 +65,7 @@ def gen_segment_getter(ext, path, theme_configs, default_module=None):
highlight_group = segment_type != 'function' and segment.get('highlight_group') or segment.get('name') highlight_group = segment_type != 'function' and segment.get('highlight_group') or segment.get('name')
return { return {
'type': segment_type, 'type': segment_type,
'highlight_group': scalar_to_list(highlight_group), 'highlight_group': highlight_group,
'divider_highlight_group': None, 'divider_highlight_group': None,
'before': get_key(segment, module, 'before', ''), 'before': get_key(segment, module, 'before', ''),
'after': get_key(segment, module, 'after', ''), 'after': get_key(segment, module, 'after', ''),

View File

@ -4,6 +4,7 @@
import argparse import argparse
import sys import sys
import json import json
from powerline.lib import parsedotval
try: try:
from powerline.shell import ShellPowerline from powerline.shell import ShellPowerline
@ -12,30 +13,6 @@ except ImportError:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from powerline.shell import ShellPowerline # NOQA from powerline.shell import ShellPowerline # NOQA
def oval(s):
if '=' not in s:
raise TypeError('Option must look like option=json_value')
if s[0] == '_':
raise ValueError('Option names must not start with `_\'')
idx = s.index('=')
o = s[:idx]
val = json.loads(s[idx+1:])
return (o, val)
def odotval(s):
o, val = oval(s)
keys = o.split('.')
if len(keys) > 1:
r = (keys[0], {})
rcur = r[1]
for key in keys[1:-1]:
rcur[key] = {}
rcur = rcur[key]
rcur[keys[-1]] = val
return r
else:
return (o, val)
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('ext', nargs=1) parser.add_argument('ext', nargs=1)
parser.add_argument('side', nargs='?', choices=('left', 'right')) parser.add_argument('side', nargs='?', choices=('left', 'right'))
@ -43,8 +20,8 @@ parser.add_argument('-r', '--renderer_module', metavar='MODULE', type=str)
parser.add_argument('-w', '--width', type=int) parser.add_argument('-w', '--width', type=int)
parser.add_argument('--last_exit_code', metavar='INT', type=int) parser.add_argument('--last_exit_code', metavar='INT', type=int)
parser.add_argument('--last_pipe_status', metavar='LIST', default='', type=lambda s: [int(status) for status in s.split()]) parser.add_argument('--last_pipe_status', metavar='LIST', default='', type=lambda s: [int(status) for status in s.split()])
parser.add_argument('-c', '--config', metavar='KEY.KEY=VALUE', type=odotval, action='append') parser.add_argument('-c', '--config', metavar='KEY.KEY=VALUE', type=parsedotval, action='append')
parser.add_argument('-t', '--theme_option', metavar='THEME.KEY.KEY=VALUE', type=odotval, action='append') parser.add_argument('-t', '--theme_option', metavar='THEME.KEY.KEY=VALUE', type=parsedotval, action='append')
parser.add_argument('-p', '--config_path', metavar='PATH') parser.add_argument('-p', '--config_path', metavar='PATH')
if __name__ == '__main__': if __name__ == '__main__':