Merge pull request #695 from ZyX-I/powerline-lint-fix

Fix powerline-lint tests
This commit is contained in:
ZyX-I 2014-01-10 09:17:17 -08:00
commit 84d2b46e6a
17 changed files with 128 additions and 63 deletions

View File

@ -1,2 +1,3 @@
setlocal noexpandtab setlocal noexpandtab
let g:syntastic_python_flake8_args = '--ignore=W191,E501,E121,E122,E123,E128,E225,W291' let g:syntastic_python_flake8_args = '--ignore=W191,E501,E121,E122,E123,E128,E225,W291,E126'
let b:syntastic_checkers = ['flake8']

View File

@ -39,10 +39,10 @@
"help": "help", "help": "help",
"quickfix": "quickfix", "quickfix": "quickfix",
"powerline.matchers.plugin.nerdtree.nerdtree": "plugin/nerdtree", "powerline.matchers.plugin.nerdtree.nerdtree": "plugin_nerdtree",
"powerline.matchers.plugin.ctrlp.ctrlp": "plugin/ctrlp", "powerline.matchers.plugin.ctrlp.ctrlp": "plugin_ctrlp",
"powerline.matchers.plugin.gundo.gundo": "plugin/gundo", "powerline.matchers.plugin.gundo.gundo": "plugin_gundo",
"powerline.matchers.plugin.gundo.gundo_preview": "plugin/gundo-preview" "powerline.matchers.plugin.gundo.gundo_preview": "plugin_gundo-preview"
} }
}, },
"wm": { "wm": {

View File

@ -4,18 +4,8 @@
"uptime": { "uptime": {
"before": "⇑ " "before": "⇑ "
}, },
"external_ip": {
"before": "ⓦ "
},
"date": { "date": {
"before": "⌚ " "before": "⌚ "
},
"email_imap_alert": {
"before": "✉ ",
"args": {
"username": "",
"password": ""
}
} }
}, },
"segments": { "segments": {

View File

@ -1,5 +1,4 @@
{ {
"default_module": "powerline.segments.plugin.gundo",
"segments": { "segments": {
"left": [ "left": [
{ {

View File

@ -1,5 +1,4 @@
{ {
"default_module": "powerline.segments.plugin.gundo",
"segments": { "segments": {
"left": [ "left": [
{ {

View File

@ -6,7 +6,6 @@ from powerline.lib.config import load_json_config
from powerline.lint.markedjson.error import echoerr, MarkedError from powerline.lint.markedjson.error import echoerr, MarkedError
from powerline.segments.vim import vim_modes from powerline.segments.vim import vim_modes
from powerline.lint.inspect import getconfigargspec from powerline.lint.inspect import getconfigargspec
from powerline.lint.markedjson.markedvalue import gen_marked_value
from powerline.lib.threaded import ThreadedSegment from powerline.lib.threaded import ThreadedSegment
import itertools import itertools
import sys import sys
@ -43,9 +42,22 @@ def context_key(context):
return key_sep.join((c[0] for c in context)) return key_sep.join((c[0] for c in context))
class DelayedEchoErr(object): class EchoErr(object):
def __init__(self, echoerr): __slots__ = ('echoerr', 'logger',)
def __init__(self, echoerr, logger):
self.echoerr = echoerr self.echoerr = echoerr
self.logger = logger
def __call__(self, *args, **kwargs):
self.echoerr(*args, **kwargs)
class DelayedEchoErr(EchoErr):
__slots__ = ('echoerr', 'logger', 'errs')
def __init__(self, echoerr):
super(DelayedEchoErr, self).__init__(echoerr, echoerr.logger)
self.errs = [] self.errs = []
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
@ -331,7 +343,9 @@ class Spec(object):
if khadproblem: if khadproblem:
hadproblem = True hadproblem = True
if proceed: if proceed:
valspec.match(value[key], value.mark, data, context + ((key, value[key]),), echoerr) proceed, vhadproblem = valspec.match(value[key], value.mark, data, context + ((key, value[key]),), echoerr)
if vhadproblem:
hadproblem = True
break break
else: else:
hadproblem = True hadproblem = True
@ -603,7 +617,9 @@ def check_segment_module(module, data, context, echoerr):
with WithPath(data['import_paths']): with WithPath(data['import_paths']):
try: try:
__import__(unicode(module)) __import__(unicode(module))
except ImportError: except ImportError as e:
if echoerr.logger.level >= logging.DEBUG:
echoerr.logger.exception(e)
echoerr(context='Error while checking segments (key {key})'.format(key=context_key(context)), echoerr(context='Error while checking segments (key {key})'.format(key=context_key(context)),
problem='failed to import module {0}'.format(module), problem='failed to import module {0}'.format(module),
problem_mark=module.mark) problem_mark=module.mark)
@ -984,13 +1000,19 @@ theme_spec = (Spec(
).context_message('Error while loading theme')) ).context_message('Error while loading theme'))
def check(path=None): def check(path=None, debug=False):
search_paths = [path] if path else Powerline.get_config_paths() search_paths = [path] if path else Powerline.get_config_paths()
logger = logging.getLogger('powerline-lint')
logger.setLevel(logging.DEBUG if debug else logging.ERROR)
logger.addHandler(logging.StreamHandler())
ee = EchoErr(echoerr, logger)
dirs = { dirs = {
'themes': defaultdict(lambda: []), 'themes': defaultdict(lambda: []),
'colorschemes': defaultdict(lambda: []) 'colorschemes': defaultdict(lambda: [])
} }
for path in reversed(search_paths): for path in reversed(search_paths):
for subdir in ('themes', 'colorschemes'): for subdir in ('themes', 'colorschemes'):
d = os.path.join(path, subdir) d = os.path.join(path, subdir)
@ -1004,14 +1026,16 @@ def check(path=None):
sys.stderr.write('Path {0} is supposed to be a directory, but it is not\n'.format(d)) sys.stderr.write('Path {0} is supposed to be a directory, but it is not\n'.format(d))
configs = { configs = {
'themes': defaultdict(lambda: {}), 'themes': defaultdict(lambda: {}),
'colorschemes': defaultdict(lambda: {}) 'colorschemes': defaultdict(lambda: {})
} }
for subdir in ('themes', 'colorschemes'): for subdir in ('themes', 'colorschemes'):
for ext in dirs[subdir]: for ext in dirs[subdir]:
for d in dirs[subdir][ext]: for d in dirs[subdir][ext]:
for config in os.listdir(d): for config in os.listdir(d):
if config.endswith('.json'): if os.path.isdir(os.path.join(d, config)):
dirs[subdir][ext].append(os.path.join(d, config))
elif config.endswith('.json'):
configs[subdir][ext][config[:-5]] = os.path.join(d, config) configs[subdir][ext][config[:-5]] = os.path.join(d, config)
diff = set(configs['themes']) ^ set(configs['colorschemes']) diff = set(configs['themes']) ^ set(configs['colorschemes'])
@ -1022,7 +1046,7 @@ def check(path=None):
ext, ext,
'configuration' if (ext in dirs['themes'] and ext in dirs['colorschemes']) else 'directory', 'configuration' if (ext in dirs['themes'] and ext in dirs['colorschemes']) else 'directory',
'themes' if ext in configs['themes'] else 'colorschemes', 'themes' if ext in configs['themes'] else 'colorschemes',
)) ))
lhadproblem = [False] lhadproblem = [False]
@ -1044,7 +1068,7 @@ def check(path=None):
sys.stderr.write(str(e) + '\n') sys.stderr.write(str(e) + '\n')
hadproblem = True hadproblem = True
else: else:
if main_spec.match(main_config, data={'configs': configs}, context=(('', main_config),))[1]: if main_spec.match(main_config, data={'configs': configs}, context=(('', main_config),), echoerr=ee)[1]:
hadproblem = True hadproblem = True
import_paths = [os.path.expanduser(path) for path in main_config.get('common', {}).get('paths', [])] import_paths = [os.path.expanduser(path) for path in main_config.get('common', {}).get('paths', [])]
@ -1060,7 +1084,7 @@ def check(path=None):
sys.stderr.write(str(e) + '\n') sys.stderr.write(str(e) + '\n')
hadproblem = True hadproblem = True
else: else:
if colors_spec.match(colors_config, context=(('', colors_config),))[1]: if colors_spec.match(colors_config, context=(('', colors_config),), echoerr=ee)[1]:
hadproblem = True hadproblem = True
if lhadproblem[0]: if lhadproblem[0]:
@ -1084,7 +1108,7 @@ def check(path=None):
spec = vim_colorscheme_spec spec = vim_colorscheme_spec
else: else:
spec = colorscheme_spec spec = colorscheme_spec
if spec.match(config, context=(('', config),), data=data)[1]: if spec.match(config, context=(('', config),), data=data, echoerr=ee)[1]:
hadproblem = True hadproblem = True
theme_configs = defaultdict(lambda: {}) theme_configs = defaultdict(lambda: {})
@ -1105,6 +1129,6 @@ def check(path=None):
'main_config': main_config, 'ext_theme_configs': configs, 'colors_config': colors_config} 'main_config': main_config, 'ext_theme_configs': configs, 'colors_config': colors_config}
for theme, config in configs.items(): for theme, config in configs.items():
data['theme'] = theme data['theme'] = theme
if theme_spec.match(config, context=(('', config),), data=data)[1]: if theme_spec.match(config, context=(('', config),), data=data, echoerr=ee)[1]:
hadproblem = True hadproblem = True
return hadproblem return hadproblem

View File

@ -4,6 +4,7 @@ from inspect import ArgSpec, getargspec
from powerline.lib.threaded import ThreadedSegment, KwThreadedSegment from powerline.lib.threaded import ThreadedSegment, KwThreadedSegment
from itertools import count from itertools import count
def getconfigargspec(obj): def getconfigargspec(obj):
if isinstance(obj, ThreadedSegment): if isinstance(obj, ThreadedSegment):
args = ['interval'] args = ['interval']

View File

@ -53,13 +53,13 @@ class Mark:
break break
snippet = [self.buffer[start:self.pointer], self.buffer[self.pointer], self.buffer[self.pointer + 1:end]] snippet = [self.buffer[start:self.pointer], self.buffer[self.pointer], self.buffer[self.pointer + 1:end]]
snippet = [strtrans(s) for s in snippet] snippet = [strtrans(s) for s in snippet]
return ' ' * indent + head + ''.join(snippet) + tail + '\n' \ return (' ' * indent + head + ''.join(snippet) + tail + '\n'
+ ' ' * (indent + len(head) + len(snippet[0])) + '^' + ' ' * (indent + len(head) + len(snippet[0])) + '^')
def __str__(self): def __str__(self):
snippet = self.get_snippet() snippet = self.get_snippet()
where = " in \"%s\", line %d, column %d" \ where = (" in \"%s\", line %d, column %d"
% (self.name, self.line + 1, self.column + 1) % (self.name, self.line + 1, self.column + 1))
if snippet is not None: if snippet is not None:
where += ":\n" + snippet where += ":\n" + snippet
if type(where) is str: if type(where) is str:

View File

@ -71,8 +71,8 @@ class BaseResolver:
return return
if index_check is True and current_index is not None: if index_check is True and current_index is not None:
return return
if (index_check is False or index_check is None) \ if ((index_check is False or index_check is None)
and current_index is None: and current_index is None):
return return
if isinstance(index_check, str): if isinstance(index_check, str):
if not (isinstance(current_index, ScalarNode) if not (isinstance(current_index, ScalarNode)

View File

@ -1,19 +1,22 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
import os import os
import vim try:
import vim
vim.command('''function! Powerline_plugin_ctrlp_main(...) vim.command('''function! Powerline_plugin_ctrlp_main(...)
let b:powerline_ctrlp_type = 'main' let b:powerline_ctrlp_type = 'main'
let b:powerline_ctrlp_args = a:000 let b:powerline_ctrlp_args = a:000
endfunction''') endfunction''')
vim.command('''function! Powerline_plugin_ctrlp_prog(...) vim.command('''function! Powerline_plugin_ctrlp_prog(...)
let b:powerline_ctrlp_type = 'prog' let b:powerline_ctrlp_type = 'prog'
let b:powerline_ctrlp_args = a:000 let b:powerline_ctrlp_args = a:000
endfunction''') endfunction''')
vim.command('''let g:ctrlp_status_func = { 'main': 'Powerline_plugin_ctrlp_main', 'prog': 'Powerline_plugin_ctrlp_prog' }''') vim.command('''let g:ctrlp_status_func = { 'main': 'Powerline_plugin_ctrlp_main', 'prog': 'Powerline_plugin_ctrlp_prog' }''')
except ImportError:
vim = object() # NOQA
def ctrlp(matcher_info): def ctrlp(matcher_info):

View File

@ -1,10 +1,18 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
import vim try:
import vim
except ImportError:
vim = object() # NOQA
from powerline.bindings.vim import getbufvar from powerline.bindings.vim import getbufvar
def ctrlp(pl, side): def ctrlp(pl, side):
'''
Highlight groups used: ``ctrlp.regex`` or ``background``, ``ctrlp.prev`` or ``background``, ``ctrlp.item`` or ``file_name``, ``ctrlp.next`` or ``background``, ``ctrlp.marked`` or ``background``, ``ctrlp.focus`` or ``background``, ``ctrlp.byfname`` or ``background``, ``ctrlp.progress`` or ``file_name``, ``ctrlp.progress`` or ``file_name``.
'''
ctrlp_type = getbufvar('%', 'powerline_ctrlp_type') ctrlp_type = getbufvar('%', 'powerline_ctrlp_type')
ctrlp_args = getbufvar('%', 'powerline_ctrlp_args') ctrlp_args = getbufvar('%', 'powerline_ctrlp_args')
@ -12,6 +20,10 @@ def ctrlp(pl, side):
def ctrlp_stl_left_main(pl, focus, byfname, regex, prev, item, next, marked): def ctrlp_stl_left_main(pl, focus, byfname, regex, prev, item, next, marked):
'''
Highlight groups used: ``ctrlp.regex`` or ``background``, ``ctrlp.prev`` or ``background``, ``ctrlp.item`` or ``file_name``, ``ctrlp.next`` or ``background``, ``ctrlp.marked`` or ``background``.
'''
marked = marked[2:-1] marked = marked[2:-1]
segments = [] segments = []
@ -54,6 +66,10 @@ def ctrlp_stl_left_main(pl, focus, byfname, regex, prev, item, next, marked):
def ctrlp_stl_right_main(pl, focus, byfname, regex, prev, item, next, marked): def ctrlp_stl_right_main(pl, focus, byfname, regex, prev, item, next, marked):
'''
Highlight groups used: ``ctrlp.focus`` or ``background``, ``ctrlp.byfname`` or ``background``.
'''
segments = [ segments = [
{ {
'contents': focus, 'contents': focus,
@ -72,6 +88,10 @@ def ctrlp_stl_right_main(pl, focus, byfname, regex, prev, item, next, marked):
def ctrlp_stl_left_prog(pl, progress): def ctrlp_stl_left_prog(pl, progress):
'''
Highlight groups used: ``ctrlp.progress`` or ``file_name``.
'''
return [ return [
{ {
'contents': 'Loading...', 'contents': 'Loading...',
@ -81,6 +101,10 @@ def ctrlp_stl_left_prog(pl, progress):
def ctrlp_stl_right_prog(pl, progress): def ctrlp_stl_right_prog(pl, progress):
'''
Highlight groups used: ``ctrlp.progress`` or ``file_name``.
'''
return [ return [
{ {
'contents': progress, 'contents': progress,

View File

@ -1,6 +1,9 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
import vim try:
import vim
except ImportError:
vim = object() # NOQA
from powerline.bindings.vim import getbufvar from powerline.bindings.vim import getbufvar
from powerline.segments.vim import window_cached from powerline.segments.vim import window_cached
@ -8,6 +11,10 @@ from powerline.segments.vim import window_cached
@window_cached @window_cached
def nerdtree(pl): def nerdtree(pl):
'''Return directory that is shown by the current buffer.
Highlight groups used: ``nerdtree.path`` or ``file_name``.
'''
ntr = getbufvar('%', 'NERDTreeRoot') ntr = getbufvar('%', 'NERDTreeRoot')
if not ntr: if not ntr:
return return

View File

@ -1,12 +1,25 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
import vim try:
import vim
except ImportError:
vim = object() # NOQA
from powerline.segments.vim import window_cached from powerline.segments.vim import window_cached
@window_cached @window_cached
def syntastic(pl): def syntastic(pl, err_format='ERR:  {first_line} ({num}) ', warn_format='WARN:  {first_line} ({num}) '):
'''Show whether syntastic has found any errors or warnings
:param str err_format:
Format string for errors.
:param str warn_format:
Format string for warnings.
Highlight groups used: ``syntastic.warning`` or ``warning``, ``syntastic.error`` or ``error``.
'''
if not int(vim.eval('exists("g:SyntasticLoclist")')): if not int(vim.eval('exists("g:SyntasticLoclist")')):
return return
has_errors = int(vim.eval('g:SyntasticLoclist.current().hasErrorsOrWarningsToDisplay()')) has_errors = int(vim.eval('g:SyntasticLoclist.current().hasErrorsOrWarningsToDisplay()'))
@ -17,12 +30,12 @@ def syntastic(pl):
segments = [] segments = []
if errors: if errors:
segments.append({ segments.append({
'contents': 'ERR:  {line} ({num}) '.format(line=errors[0]['lnum'], num=len(errors)), 'contents': err_format.format(first_line=errors[0]['lnum'], num=len(errors)),
'highlight_group': ['syntastic.error', 'error', 'background'], 'highlight_group': ['syntastic.error', 'error'],
}) })
if warnings: if warnings:
segments.append({ segments.append({
'contents': 'WARN:  {line} ({num}) '.format(line=warnings[0]['lnum'], num=len(warnings)), 'contents': warn_format.format(first_line=warnings[0]['lnum'], num=len(warnings)),
'highlight_group': ['syntastic.warning', 'warning', 'background'], 'highlight_group': ['syntastic.warning', 'warning'],
}) })
return segments return segments

View File

@ -1,6 +1,9 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
import vim try:
import vim
except ImportError:
vim = object() # NOQA
from powerline.segments.vim import window_cached from powerline.segments.vim import window_cached

View File

@ -8,7 +8,8 @@ import sys
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-p', '--config_path', metavar='PATH') parser.add_argument('-p', '--config_path', metavar='PATH')
parser.add_argument('-d', '--debug', action='store_const', const=True)
if __name__ == '__main__': if __name__ == '__main__':
args = parser.parse_args() args = parser.parse_args()
sys.exit(check(args.config_path)) sys.exit(check(args.config_path, args.debug))