Cleanup Python files to comply better with PEP 8

Removed excessive newlines and comments, and fixed whitespace issues.
This commit is contained in:
Kim Silkebækken 2013-01-15 08:49:40 +01:00
parent 7eb3bfde9c
commit 6d3dea1f0b
20 changed files with 43 additions and 149 deletions

View File

@ -5,12 +5,9 @@ class Colorscheme(object):
DEFAULT_MODE_KEY = '__default__'
def __init__(self, colorscheme):
'''Initialize a colorscheme.
'''
'''Initialize a colorscheme.'''
self.colors = {}
self.modes_groups = {
self.DEFAULT_MODE_KEY: {}
}
self.modes_groups = {self.DEFAULT_MODE_KEY: {}}
# Create a dict of color tuples with both a cterm and hex value
for color_name, color in colorscheme['colors'].items():
@ -22,36 +19,33 @@ class Colorscheme(object):
# Create highlighting groups for all modes
for group_name, group_props in colorscheme['groups'].items():
group_attr_flag = self._get_attr_flag(group_props.get('attr', []))
self.modes_groups[self.DEFAULT_MODE_KEY][group_name] = {
'fg': self.colors[group_props['fg']],
'bg': self.colors[group_props['bg']],
'attr': group_attr_flag,
}
}
# Create mode-specific highlighting for this group
for mode, translations in colorscheme['mode_translations'].items():
if not mode in self.modes_groups:
self.modes_groups[mode] = {}
if group_name in translations.get('groups', {}):
# Override entire group if present in the translations group dict
self.modes_groups[mode][group_name] = {
'fg': self.colors[translations['groups'][group_name]['fg']],
'bg': self.colors[translations['groups'][group_name]['bg']],
'attr': self._get_attr_flag(translations['groups'][group_name].get('attr', [])),
}
}
else:
# Fallback to color translations from the translations colors dict
self.modes_groups[mode][group_name] = {
'fg': self.colors[translations.get('colors', {}).get(group_props['fg'], group_props['fg'])],
'bg': self.colors[translations.get('colors', {}).get(group_props['bg'], group_props['bg'])],
'attr': group_attr_flag,
}
}
def get_group_highlighting(self, group):
'''Return highlighting information for all modes of a highlighting group.
'''
'''Return highlighting information for all modes of a highlighting group.'''
group_highlighting = {}
for mode, mode_group in self.modes_groups.items():
try:
@ -74,7 +68,6 @@ class Colorscheme(object):
'''
if not mode or mode not in self.modes_groups:
mode = self.DEFAULT_MODE_KEY
try:
return self.modes_groups[mode][group]
except TypeError:
@ -82,14 +75,11 @@ class Colorscheme(object):
if try_group in self.modes_groups[mode]:
return self.modes_groups[mode][try_group]
raise KeyError('Highlighting groups not found in colorscheme: {0}'.format(group))
return self.modes_groups[mode][group]
def _get_attr_flag(self, attributes):
'''Convert an attribute array to a renderer flag.
'''
'''Convert an attribute array to a renderer flag.'''
from powerline.renderer import Renderer
attr_flag = 0
if 'bold' in attributes:
attr_flag |= Renderer.ATTR_BOLD
@ -97,7 +87,6 @@ class Colorscheme(object):
attr_flag |= Renderer.ATTR_ITALIC
if 'underline' in attributes:
attr_flag |= Renderer.ATTR_UNDERLINE
return attr_flag
cterm_to_hex = {
@ -141,4 +130,4 @@ cterm_to_hex = {
238: 0x444444, 239: 0x4e4e4e, 240: 0x585858, 241: 0x626262, 242: 0x6c6c6c, 243: 0x767676,
244: 0x808080, 245: 0x8a8a8a, 246: 0x949494, 247: 0x9e9e9e, 248: 0xa8a8a8, 249: 0xb2b2b2,
250: 0xbcbcbc, 251: 0xc6c6c6, 252: 0xd0d0d0, 253: 0xdadada, 254: 0xe4e4e4, 255: 0xeeeeee,
}
}

View File

@ -13,11 +13,9 @@ from matchers import Matchers
class Powerline(object):
def __init__(self, ext):
config_home = os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
config_path = os.path.join(config_home, 'powerline')
plugin_path = os.path.realpath(os.path.dirname(__file__))
self.search_paths = [config_path, plugin_path]
sys.path[:0] = self.search_paths
# Load main config file
@ -31,19 +29,15 @@ class Powerline(object):
# Load and initialize extension theme
theme_config = self._load_theme_config(ext, self.config_ext.get('theme', 'default'))
path = [os.path.expanduser(path) for path in self.config.get('paths', [])]
get_segment = Segments(ext, path, colorscheme).get
get_matcher = Matchers(ext, path).get
theme_kwargs = {
'ext': ext,
'colorscheme': colorscheme,
'common_config': self.config,
'get_segment': get_segment
}
'get_segment': get_segment,
}
local_themes = {}
for key, local_theme_name in self.config_ext.get('local_themes', {}).iteritems():
key = get_matcher(key)
@ -65,5 +59,4 @@ class Powerline(object):
if os.path.isfile(config_file_path):
with open(config_file_path, 'rb') as config_file_fp:
return json.load(config_file_fp)
raise IOError('Config file not found in search path: {0}'.format(config_file))

View File

@ -1,14 +1,12 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''Powerline terminal prompt example.
'''
'''Powerline terminal prompt.'''
try:
from powerline.core import Powerline
except ImportError:
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
from powerline.core import Powerline
pl = Powerline('terminal')

View File

@ -4,8 +4,7 @@ from powerline.renderer import Renderer
class TerminalRenderer(Renderer):
'''Powerline terminal segment renderer.
'''
'''Powerline terminal segment renderer.'''
def hl(self, fg=None, bg=None, attr=None):
'''Highlight a segment.
@ -14,24 +13,20 @@ class TerminalRenderer(Renderer):
is a valid color or attribute, it's added to the ANSI escape code.
'''
ansi = []
if fg is not None:
if fg[0] is False:
ansi += [39]
else:
ansi += [38, 5, fg[0]]
if bg is not None:
if bg[0] is False:
ansi += [49]
else:
ansi += [48, 5, bg[0]]
if attr is not None:
if attr is False:
ansi += [22]
else:
if attr & Renderer.ATTR_BOLD:
ansi += [1]
return '[{0}m'.format(';'.join(str(attr) for attr in ansi))

View File

@ -16,11 +16,10 @@ def hostname():
def user():
user = os.environ.get('USER')
euid = os.geteuid()
return {
'contents': user,
'highlight': 'user' if euid != 0 else ['superuser', 'user'],
}
}
def branch():
@ -37,12 +36,9 @@ def cwd(dir_shorten_len=None, dir_limit_depth=None):
cwd = re.sub('^' + re.escape(home), '~', cwd, 1)
cwd_split = cwd.split(os.sep)
cwd_split_len = len(cwd_split)
if cwd_split_len > dir_limit_depth + 1:
del(cwd_split[0:-dir_limit_depth])
cwd_split.insert(0, u'')
cwd = [i[0:dir_shorten_len] if dir_shorten_len and i else i for i in cwd_split[:-1]] + [cwd_split[-1]]
cwd = os.path.join(*cwd)
return cwd

View File

@ -4,25 +4,20 @@ from powerline.renderer import Renderer
class TmuxRenderer(Renderer):
'''Powerline tmux segment renderer.
'''
'''Powerline tmux segment renderer.'''
def hl(self, fg=None, bg=None, attr=None):
'''Highlight a segment.
'''
'''Highlight a segment.'''
tmux_attr = []
if fg is not None:
if fg[0] is False:
tmux_attr += ['fg=default']
else:
tmux_attr += ['fg=colour' + str(fg[0])]
if bg is not None:
if bg[0] is False:
tmux_attr += ['bg=default']
else:
tmux_attr += ['bg=colour' + str(bg[0])]
if attr is not None:
if attr is False:
tmux_attr += ['nobold', 'noitalics', 'nounderscore']
@ -39,5 +34,4 @@ class TmuxRenderer(Renderer):
tmux_attr += ['underscore']
else:
tmux_attr += ['nounderscore']
return '#[' + ','.join(tmux_attr) + ']'

View File

@ -8,4 +8,4 @@ def user_name():
return {
'contents': user_name,
'highlight': 'user_name' if user_name != 'root' else ['user_name_root', 'user_name'],
}
}

View File

@ -5,7 +5,5 @@ def source_plugin():
import os
import vim
from bindings import vim_get_func
fnameescape = vim_get_func('fnameescape')
vim.command('source ' + fnameescape(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'powerline.vim')))

View File

@ -6,13 +6,11 @@ try:
_vim_globals = vim.bindeval('g:')
def vim_set_global_var(var, val):
'''Set a global var in vim using bindeval().
'''
'''Set a global var in vim using bindeval().'''
_vim_globals[var] = val
def vim_get_func(f, rettype=None):
'''Return a vim function binding.
'''
'''Return a vim function binding.'''
try:
return vim.bindeval('function("' + f + '")')
except vim.error:

View File

@ -12,8 +12,7 @@ vim_setwinvar = vim_get_func('setwinvar')
class VimRenderer(Renderer):
'''Powerline vim segment renderer.
'''
'''Powerline vim segment renderer.'''
PERCENT_PLACEHOLDER = u''
def __init__(self, *args, **kwargs):
@ -30,7 +29,6 @@ class VimRenderer(Renderer):
'''
window_id = vim_getwinvar(winnr, 'window_id')
winwidth = vim_winwidth(winnr)
if current:
mode = vim_mode()
theme = self.get_theme()
@ -39,10 +37,8 @@ class VimRenderer(Renderer):
else:
mode = 'nc'
theme, segments = self.window_cache.get(window_id, (None, None))
statusline = super(VimRenderer, self).render(mode, winwidth, theme, segments)
statusline = statusline.replace(self.PERCENT_PLACEHOLDER, '%%')
return statusline
def hl(self, fg=None, bg=None, attr=None):
@ -64,16 +60,13 @@ class VimRenderer(Renderer):
'guibg': 'NONE',
'attr': ['NONE'],
'name': '',
}
}
if fg is not None and fg is not False:
hl_group['ctermfg'] = fg[0]
hl_group['guifg'] = fg[1]
if bg is not None and bg is not False:
hl_group['ctermbg'] = bg[0]
hl_group['guibg'] = bg[1]
if attr:
hl_group['attr'] = []
if attr & self.ATTR_BOLD:
@ -82,17 +75,13 @@ class VimRenderer(Renderer):
hl_group['attr'].append('italic')
if attr & self.ATTR_UNDERLINE:
hl_group['attr'].append('underline')
hl_group['name'] = 'Pl_' + \
str(hl_group['ctermfg']) + '_' + \
str(hl_group['guifg']) + '_' + \
str(hl_group['ctermbg']) + '_' + \
str(hl_group['guibg']) + '_' + \
''.join(hl_group['attr'])
self.hl_groups[(fg, bg, attr)] = hl_group
# Create highlighting group in vim
vim.command('hi {group} ctermfg={ctermfg} guifg={guifg} guibg={guibg} ctermbg={ctermbg} cterm={attr} gui={attr}'.format(
group=hl_group['name'],
ctermfg=hl_group['ctermfg'],
@ -101,5 +90,4 @@ class VimRenderer(Renderer):
guibg='#{0:06x}'.format(hl_group['guibg']) if hl_group['guibg'] != 'NONE' else 'NONE',
attr=','.join(hl_group['attr']),
))
return '%#' + self.hl_groups[(fg, bg, attr)]['name'] + '#'

View File

@ -47,10 +47,8 @@ def mode(override=None):
mode = mode({ 'n': 'NORM' })
'''
mode = vim_funcs['mode']()
if not override:
return vim_modes[mode]
try:
return override[mode]
except IndexError:
@ -58,44 +56,36 @@ def mode(override=None):
def modified_indicator(text=u'+'):
'''Return a file modified indicator.
'''
'''Return a file modified indicator.'''
return text if int(vim.eval('&modified')) else None
def paste_indicator(text='PASTE'):
'''Return a paste mode indicator.
'''
'''Return a paste mode indicator.'''
return text if int(vim.eval('&paste')) else None
def readonly_indicator(text=u''):
'''Return a read-only indicator.
'''
'''Return a read-only indicator.'''
return text if int(vim.eval('&readonly')) else None
def file_directory():
'''Return file directory (head component of the file path).
'''
'''Return file directory (head component of the file path).'''
file_directory = vim_funcs['expand']('%:~:.:h')
return file_directory + os.sep if file_directory else None
def file_name(display_no_file=False, no_file_text='[No file]'):
'''Return file name (tail component of the file path).
'''
'''Return file name (tail component of the file path).'''
file_name = vim_funcs['expand']('%:~:.:t')
if not file_name and not display_no_file:
return None
if not file_name:
return {
'contents': no_file_text,
'highlight': ['file_name_no_file', 'file_name'],
}
}
return file_name
@ -124,24 +114,20 @@ def file_type():
def line_percent(gradient=False):
'''Return the cursor position in the file as a percentage.
'''
'''Return the cursor position in the file as a percentage.'''
line_current = vim_funcs['line']('.')
line_last = vim_funcs['line']('$')
percentage = int(line_current * 100 // line_last)
if not gradient:
return percentage
return {
'contents': percentage,
'highlight': ['line_percent_gradient' + str(int(5 * percentage // 100) + 1), 'line_percent'],
}
}
def line_current():
'''Return the current cursor line.
'''
'''Return the current cursor line.'''
return vim_funcs['line']('.')
@ -175,5 +161,5 @@ def file_vcs_status():
return {
'contents': status,
'highlight': ['file_vcs_status_' + status, 'file_vcs_status'],
}
}
return None

View File

@ -9,21 +9,17 @@ try:
import psMat
except ImportError:
sys.stderr.write('The required FontForge modules could not be loaded.\n\n')
if sys.version_info.major > 2:
sys.stderr.write('FontForge only supports Python 2. Please run this script with the Python 2 executable - e.g. "python2 {0}"\n'.format(sys.argv[0]))
else:
sys.stderr.write('You need FontForge with Python bindings for this script to work.\n')
sys.exit(1)
# Handle command-line arguments
parser = argparse.ArgumentParser(description='Font patcher for Powerline. Requires FontForge with Python bindings. Stores the patched font as a new, renamed font file by default.')
parser.add_argument('target_fonts', help='font files to patch', metavar='font', nargs='+', type=argparse.FileType('rb'))
parser.add_argument('--no-rename', help='don\'t add " for Powerline" to the font name', default=True, action='store_false', dest='rename_font')
parser.add_argument('--source-font', help='source symbol font', metavar='font', dest='source_font', default='{0}/fontpatcher-symbols.sfd'.format(sys.path[0]), type=argparse.FileType('rb'))
args = parser.parse_args()
@ -36,10 +32,8 @@ class FontPatcher(object):
def patch(self):
for target_font in self.target_fonts:
source_font = self.source_font
target_font_em_original = target_font.em
target_font.em = 2048
target_font.encoding = 'ISO10646'
# Rename font
@ -61,10 +55,8 @@ class FontPatcher(object):
bbox = target_font[cp].boundingBox()
except TypeError:
continue
if not target_font_width:
target_font_width = target_font[cp].width
if bbox[0] < target_bb[0]:
target_bb[0] = bbox[0]
if bbox[1] < target_bb[1]:
@ -83,7 +75,6 @@ class FontPatcher(object):
x_diff = target_bb[0] - source_bb[0]
y_diff = target_bb[1] - source_bb[1]
translate = psMat.translate(x_diff, y_diff)
transform = psMat.compose(scale, translate)
# Create new glyphs from symbol font

View File

@ -8,8 +8,7 @@ import time
class memoize(object):
'''Memoization decorator with timeout.
'''
'''Memoization decorator with timeout.'''
_cache = {}
def __init__(self, timeout, additional_key=None, persistent=False, persistent_file=None):
@ -25,22 +24,18 @@ class memoize(object):
key = (func.__name__, args, tuple(kwargs.items()), self.additional_key())
else:
key = (func.__name__, args, tuple(kwargs.items()))
if self.persistent:
try:
with open(self.persistent_file, 'rb') as fileobj:
self._cache = pickle.load(fileobj)
except (IOError, EOFError):
pass
cached = self._cache.get(key, None)
if cached is None or time.time() - cached['time'] > self.timeout:
cached = self._cache[key] = {
'result': func(*args, **kwargs),
'time': time.time(),
}
}
if self.persistent:
try:
with open(self.persistent_file, 'wb') as fileobj:
@ -51,6 +46,5 @@ class memoize(object):
except TypeError:
# Unable to pickle function result
pass
return cached['result']
return decorated_function

View File

@ -27,7 +27,7 @@ try:
if path:
try:
status = self._repo().status_file(path)
except KeyError, ValueError:
except (KeyError, ValueError):
return None
if status == git.GIT_STATUS_CURRENT:

View File

@ -32,7 +32,6 @@ class Repository(object):
"U"nknown, "I"gnored, (None)Clean.
'''
repo = self._repo()
if path:
m = match.match(None, None, [path], exact=True)
statuses = repo.status(match=m, unknown=True, ignored=True)

View File

@ -14,10 +14,8 @@ class Matchers(object):
if not separator:
match_module = 'powerline.ext.{0}.matchers'.format(self.ext)
match_function = match_name
oldpath = sys.path
sys.path = self.path + sys.path
try:
return getattr(import_module(match_module), match_function)
finally:

View File

@ -39,16 +39,13 @@ class Renderer(object):
# Handle excluded/included segments for the current mode
segments = [segment for segment in segments\
if mode not in segment['exclude_modes'] or (segment['include_modes'] and segment in segment['include_modes'])]
rendered_highlighted = self._render_segments(mode, theme, segments)
if not width:
# No width specified, so we don't need to crop or pad anything
return rendered_highlighted
# Create an ordered list of segments that can be dropped
segments_priority = [segment for segment in sorted(segments, key=lambda segment: segment['priority'], reverse=True) if segment['priority'] > 0]
while self._total_len(segments) > width and len(segments_priority):
segments.remove(segments_priority[0])
segments_priority.pop(0)
@ -65,7 +62,6 @@ class Renderer(object):
segment['contents'] = segments_fillers_contents
# Add remainder whitespace to the first filler segment
segments_fillers[0]['contents'] += ' ' * segments_fillers_remainder
return self._render_segments(mode, theme, segments)
def _render_segments(self, mode, theme, segments, render_highlighted=True):
@ -87,19 +83,16 @@ class Renderer(object):
prev_segment = segments[index - 1] if index > 0 else theme.EMPTY_SEGMENT
next_segment = segments[index + 1] if index < segments_len - 1 else theme.EMPTY_SEGMENT
compare_segment = next_segment if segment['side'] == 'left' else prev_segment
segment['rendered_raw'] = u''
outer_padding = ' ' if index == 0 or (index == segments_len - 1 and segment['side'] == 'right') else ''
divider_type = 'soft' if compare_segment['highlight'][mode]['bg'] == segment['highlight'][mode]['bg'] else 'hard'
divider = theme.get_divider(segment['side'], divider_type)
divider_hl = ''
segment_hl = ''
if render_highlighted:
if divider_type == 'hard':
divider_hl = self.hl(segment['highlight'][mode]['bg'], compare_segment['highlight'][mode]['bg'], False)
segment_hl = self.hl(**segment['highlight'][mode])
if segment['type'] == 'filler':
@ -124,7 +117,6 @@ class Renderer(object):
rendered_highlighted += segment_hl + segment['contents'] + outer_padding
else:
raise ValueError('Unknown segment type')
return rendered_highlighted
def _total_len(self, segments):

View File

@ -14,7 +14,6 @@ class Segments(object):
oldpath = sys.path
sys.path = self.path + sys.path
segment_module = str(segment.get('module', 'powerline.ext.{0}.segments'.format(self.ext)))
try:
return None, getattr(import_module(segment_module), segment['name']), '{0}.{1}'.format(segment_module, segment['name'])
finally:
@ -30,14 +29,11 @@ class Segments(object):
def get(self, segment, side):
segment_type = segment.get('type', 'function')
try:
contents, contents_func, key = getattr(self, 'get_{0}'.format(segment_type))(segment)
except AttributeError:
raise TypeError('Unknown segment type: {0}'.format(segment_type))
highlighting_group = segment.get('highlight', segment.get('name'))
return {
'key': key,
'type': segment_type,
@ -54,4 +50,4 @@ class Segments(object):
'side': side,
'exclude_modes': segment.get('exclude_modes', []),
'include_modes': segment.get('include_modes', []),
}
}

View File

@ -8,18 +8,15 @@ class Theme(object):
self.colorscheme = colorscheme
self.dividers = theme_config.get('dividers', common_config['dividers'])
self.segments = []
self.EMPTY_SEGMENT = {
'contents': None,
'highlight': {self.colorscheme.DEFAULT_MODE_KEY: {'fg': (False, False), 'bg': (False, False), 'attr': 0}}
}
}
for side in ['left', 'right']:
self.segments.extend((get_segment(segment, side) for segment in theme_config['segments'].get(side, [])))
def get_divider(self, side='left', type='soft'):
'''Return segment divider.
'''
'''Return segment divider.'''
return self.dividers[side][type]
def get_segments(self):
@ -31,10 +28,8 @@ class Theme(object):
for segment in self.segments:
if segment['type'] == 'function':
contents = segment['contents_func'](**segment['args'])
if contents is None:
continue
try:
segment['highlight'] = self.colorscheme.get_group_highlighting(contents['highlight'])
segment['contents'] = contents['contents']
@ -44,11 +39,9 @@ class Theme(object):
pass
else:
continue
segment['contents'] = unicode(segment['before'] + unicode(segment['contents']) + segment['after'])\
.ljust(segment['ljust'])\
.rjust(segment['rjust'])
# We need to yield a copy of the segment, or else mode-dependent
# segment contents can't be cached correctly e.g. when caching
# non-current window contents for vim statuslines

View File

@ -11,13 +11,6 @@ try:
except IOError:
README = ''
install_requires = []
docs_extras = [
'Sphinx',
'docutils',
]
setup(name='Powerline',
version='beta',
description='The ultimate statusline/prompt utility.',
@ -31,8 +24,11 @@ setup(name='Powerline',
include_package_data=True,
zip_safe=False,
test_suite='powerline',
install_requires=install_requires,
install_requires=[],
extras_require={
'docs': docs_extras,
},
)
'docs': [
'Sphinx',
'docutils',
],
},
)