From c3b4654bfb499eb51394ada64fac66af7041724e Mon Sep 17 00:00:00 2001 From: ZyX Date: Wed, 26 Feb 2014 08:49:25 +0400 Subject: [PATCH] Fix flake8 complaints --- powerline/bindings/vim/__init__.py | 1 + powerline/lib/file_watcher.py | 3 ++- powerline/lib/humanize_bytes.py | 6 ++--- powerline/lib/tree_watcher.py | 10 ++++---- powerline/lib/vcs/__init__.py | 37 ++++++++++++++++++++++-------- powerline/lib/vcs/bzr.py | 11 +++++---- powerline/lib/vcs/git.py | 8 ++++++- powerline/lib/vcs/mercurial.py | 2 ++ powerline/renderer.py | 9 ++++---- powerline/renderers/vim.py | 12 +++++----- powerline/segments/shell.py | 2 +- powerline/segments/vim.py | 5 ++-- powerline/theme.py | 2 +- tests/test_cmdline.py | 4 +++- tests/test_segments.py | 9 ++++---- tests/test_shells/postproc.py | 4 ++-- tests/vim.py | 5 ++-- tools/generate_gradients.py | 4 ++-- 18 files changed, 85 insertions(+), 49 deletions(-) diff --git a/powerline/bindings/vim/__init__.py b/powerline/bindings/vim/__init__.py index d618a089..4a17565e 100644 --- a/powerline/bindings/vim/__init__.py +++ b/powerline/bindings/vim/__init__.py @@ -129,6 +129,7 @@ if sys.version_info < (3,): return buf.name else: vim_bufname = vim_get_func('bufname') + def buffer_name(buf): # NOQA try: name = buf.name diff --git a/powerline/lib/file_watcher.py b/powerline/lib/file_watcher.py index 41e20362..21524e3b 100644 --- a/powerline/lib/file_watcher.py +++ b/powerline/lib/file_watcher.py @@ -13,11 +13,12 @@ from threading import RLock from powerline.lib.monotonic import monotonic from powerline.lib.inotify import INotify, INotifyError + def realpath(path): return os.path.abspath(os.path.realpath(path)) -class INotifyWatch(INotify): +class INotifyWatch(INotify): is_stat_based = False def __init__(self, expire_time=10): diff --git a/powerline/lib/humanize_bytes.py b/powerline/lib/humanize_bytes.py index 769c7d13..570d803e 100644 --- a/powerline/lib/humanize_bytes.py +++ b/powerline/lib/humanize_bytes.py @@ -17,6 +17,6 @@ def humanize_bytes(num, suffix='B', si_prefix=False): unit, decimals = unit_list[exponent] if unit and not si_prefix: unit = unit.upper() + 'i' - return '{{quotient:.{decimals}f}} {{unit}}{{suffix}}'\ - .format(decimals=decimals)\ - .format(quotient=quotient, unit=unit, suffix=suffix) + return ('{{quotient:.{decimals}f}} {{unit}}{{suffix}}' + .format(decimals=decimals) + .format(quotient=quotient, unit=unit, suffix=suffix)) diff --git a/powerline/lib/tree_watcher.py b/powerline/lib/tree_watcher.py index f283e10b..608e2946 100644 --- a/powerline/lib/tree_watcher.py +++ b/powerline/lib/tree_watcher.py @@ -16,19 +16,21 @@ from powerline.lib.inotify import INotify, INotifyError class NoSuchDir(ValueError): pass + class BaseDirChanged(ValueError): pass -class DirTooLarge(ValueError): +class DirTooLarge(ValueError): def __init__(self, bdir): ValueError.__init__(self, 'The directory {0} is too large to monitor. Try increasing the value in /proc/sys/fs/inotify/max_user_watches'.format(bdir)) + def realpath(path): return os.path.abspath(os.path.realpath(path)) -class INotifyTreeWatcher(INotify): +class INotifyTreeWatcher(INotify): is_dummy = False def __init__(self, basedir, ignore_event=None): @@ -141,7 +143,6 @@ class INotifyTreeWatcher(INotify): class DummyTreeWatcher(object): - is_dummy = True def __init__(self, basedir): @@ -150,8 +151,8 @@ class DummyTreeWatcher(object): def __call__(self): return False -class TreeWatcher(object): +class TreeWatcher(object): def __init__(self, expire_time=10): self.watches = {} self.last_query_times = {} @@ -203,6 +204,7 @@ class TreeWatcher(object): self.watches[path] = DummyTreeWatcher(path) return False + if __name__ == '__main__': w = INotifyTreeWatcher(sys.argv[-1]) w() diff --git a/powerline/lib/vcs/__init__.py b/powerline/lib/vcs/__init__.py index 5fa066fe..ff971c5d 100644 --- a/powerline/lib/vcs/__init__.py +++ b/powerline/lib/vcs/__init__.py @@ -1,16 +1,11 @@ # vim:fileencoding=utf-8:noet from __future__ import absolute_import -import os, errno +import os +import errno from threading import Lock from collections import defaultdict -vcs_props = ( - ('git', '.git', os.path.exists), - ('mercurial', '.hg', os.path.isdir), - ('bzr', '.bzr', os.path.isdir), -) - def generate_directories(path): if os.path.isdir(path): @@ -24,8 +19,10 @@ def generate_directories(path): break yield path + _file_watcher = None + def file_watcher(): global _file_watcher if _file_watcher is None: @@ -33,8 +30,10 @@ def file_watcher(): _file_watcher = create_file_watcher() return _file_watcher + _branch_watcher = None + def branch_watcher(): global _branch_watcher if _branch_watcher is None: @@ -42,10 +41,12 @@ def branch_watcher(): _branch_watcher = create_file_watcher() return _branch_watcher + branch_name_cache = {} branch_lock = Lock() file_status_lock = Lock() + def get_branch_name(directory, config_file, get_func): global branch_name_cache with branch_lock: @@ -79,8 +80,8 @@ def get_branch_name(directory, config_file, get_func): branch_name_cache[config_file] = get_func(directory, config_file) return branch_name_cache[config_file] -class FileStatusCache(dict): +class FileStatusCache(dict): def __init__(self): self.dirstate_map = defaultdict(set) self.ignore_map = defaultdict(set) @@ -112,8 +113,10 @@ class FileStatusCache(dict): for ignf in self.keypath_ignore_map[keypath]: yield ignf + file_status_cache = FileStatusCache() + def get_file_status(directory, dirstate_file, file_path, ignore_file_name, get_func, extra_ignore_files=()): global file_status_cache keypath = file_path if os.path.isabs(file_path) else os.path.join(directory, file_path) @@ -175,8 +178,8 @@ def get_file_status(directory, dirstate_file, file_path, ignore_file_name, get_f file_status_cache[keypath] = ans = get_func(directory, file_path) return ans -class TreeStatusCache(dict): +class TreeStatusCache(dict): def __init__(self): from powerline.lib.tree_watcher import TreeWatcher self.tw = TreeWatcher() @@ -196,14 +199,24 @@ class TreeStatusCache(dict): logger.warn('Failed to check %s for changes, with error: %s'% key, e) return self.cache_and_get(key, repo.status) + _tree_status_cache = None + def tree_status(repo, logger): global _tree_status_cache if _tree_status_cache is None: _tree_status_cache = TreeStatusCache() return _tree_status_cache(repo, logger) + +vcs_props = ( + ('git', '.git', os.path.exists), + ('mercurial', '.hg', os.path.isdir), + ('bzr', '.bzr', os.path.isdir), +) + + def guess(path): for directory in generate_directories(path): for vcs, vcs_dir, check in vcs_props: @@ -219,8 +232,12 @@ def guess(path): pass return None + def debug(): - ''' To use run python -c "from powerline.lib.vcs import debug; debug()" some_file_to_watch ''' + '''Test run guess(), repo.branch() and repo.status() + + To use run python -c "from powerline.lib.vcs import debug; debug()" + some_file_to_watch ''' import sys dest = sys.argv[-1] repo = guess(os.path.abspath(dest)) diff --git a/powerline/lib/vcs/bzr.py b/powerline/lib/vcs/bzr.py index 601546a5..9734572b 100644 --- a/powerline/lib/vcs/bzr.py +++ b/powerline/lib/vcs/bzr.py @@ -10,16 +10,17 @@ from bzrlib import (workingtree, status, library_state, trace, ui) from powerline.lib.vcs import get_branch_name, get_file_status + class CoerceIO(StringIO): def write(self, arg): if isinstance(arg, bytes): arg = arg.decode('utf-8', 'replace') return super(CoerceIO, self).write(arg) -state = None nick_pat = re.compile(br'nickname\s*=\s*(.+)') + def branch_name_from_config_file(directory, config_file): ans = None try: @@ -33,8 +34,11 @@ def branch_name_from_config_file(directory, config_file): pass return ans or os.path.basename(directory) -class Repository(object): +state = None + + +class Repository(object): def __init__(self, directory): if isinstance(directory, bytes): directory = directory.decode(sys.getfilesystemencoding() or sys.getdefaultencoding() or 'utf-8') @@ -75,7 +79,7 @@ class Repository(object): return if path: ans = raw[:2] - if ans == 'I ': # Ignored + if ans == 'I ': # Ignored ans = None return ans dirtied = untracked = ' ' @@ -90,4 +94,3 @@ class Repository(object): def branch(self): config_file = os.path.join(self.directory, '.bzr', 'branch', 'branch.conf') return get_branch_name(self.directory, config_file, branch_name_from_config_file) - diff --git a/powerline/lib/vcs/git.py b/powerline/lib/vcs/git.py index b20cafb9..08edcd7f 100644 --- a/powerline/lib/vcs/git.py +++ b/powerline/lib/vcs/git.py @@ -2,12 +2,13 @@ import os import re -import errno from powerline.lib.vcs import get_branch_name as _get_branch_name, get_file_status + _ref_pat = re.compile(br'ref:\s*refs/heads/(.+)') + def branch_name_from_config_file(directory, config_file): try: with open(config_file, 'rb') as f: @@ -19,6 +20,7 @@ def branch_name_from_config_file(directory, config_file): return m.group(1).decode('utf-8', 'replace') return raw[:7] + def git_directory(directory): path = os.path.join(directory, '.git') if os.path.isfile(path): @@ -28,10 +30,12 @@ def git_directory(directory): else: return path + def get_branch_name(base_dir): head = os.path.join(git_directory(base_dir), 'HEAD') return _get_branch_name(base_dir, head, branch_name_from_config_file) + def do_status(directory, path, func): if path: gitd = git_directory(directory) @@ -43,12 +47,14 @@ def do_status(directory, path, func): path, '.gitignore', func, extra_ignore_files=tuple(os.path.join(gitd, x) for x in ('logs/HEAD', 'info/exclude'))) return func(directory, path) + def ignore_event(path, name): # Ignore changes to the index.lock file, since they happen frequently and # dont indicate an actual change in the working tree status return False return path.endswith('.git') and name == 'index.lock' + try: import pygit2 as git diff --git a/powerline/lib/vcs/mercurial.py b/powerline/lib/vcs/mercurial.py index ade06282..2aa890cd 100644 --- a/powerline/lib/vcs/mercurial.py +++ b/powerline/lib/vcs/mercurial.py @@ -7,6 +7,7 @@ from mercurial import hg, ui, match from powerline.lib.vcs import get_branch_name, get_file_status + def branch_name_from_config_file(directory, config_file): try: with open(config_file, 'rb') as f: @@ -15,6 +16,7 @@ def branch_name_from_config_file(directory, config_file): except Exception: return 'default' + class Repository(object): __slots__ = ('directory', 'ui') diff --git a/powerline/renderer.py b/powerline/renderer.py index 256d11f0..7445ff0f 100644 --- a/powerline/renderer.py +++ b/powerline/renderer.py @@ -14,6 +14,7 @@ try: except ImportError: pass + def construct_returned_value(rendered_highlighted, segments, output_raw): if output_raw: return rendered_highlighted, ''.join((segment['_rendered_raw'] for segment in segments)) @@ -70,7 +71,7 @@ class Renderer(object): character_translations = {ord(' '): NBSP} '''Character translations for use in escape() function. - + See documentation of ``unicode.translate`` for details. ''' @@ -111,7 +112,7 @@ class Renderer(object): def strwidth(self, string): '''Function that returns string width. - + Is used to calculate the place given string occupies when handling ``width`` argument to ``.render()`` method. Must take east asian width into account. @@ -125,7 +126,7 @@ class Renderer(object): def get_theme(self, matcher_info): '''Get Theme object. - + Is to be overridden by subclasses to support local themes, this variant only returns ``.theme`` attribute. @@ -152,7 +153,7 @@ class Renderer(object): def get_segment_info(self, segment_info, mode): '''Get segment information. - + Must return a dictionary containing at least ``home``, ``environ`` and ``getcwd`` keys (see documentation for ``segment_info`` attribute). This implementation merges ``segment_info`` dictionary passed to diff --git a/powerline/renderers/vim.py b/powerline/renderers/vim.py index 6065dbbf..14496a1e 100644 --- a/powerline/renderers/vim.py +++ b/powerline/renderers/vim.py @@ -140,12 +140,12 @@ class VimRenderer(Renderer): hl_group['attr'].append('italic') if attr & 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']) + 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 vim.command('hi {group} ctermfg={ctermfg} guifg={guifg} guibg={guibg} ctermbg={ctermbg} cterm={attr} gui={attr}'.format( group=hl_group['name'], diff --git a/powerline/segments/shell.py b/powerline/segments/shell.py index 750c6f25..8afc20a1 100644 --- a/powerline/segments/shell.py +++ b/powerline/segments/shell.py @@ -46,7 +46,7 @@ def last_pipe_status(pl, segment_info): @requires_segment_info def mode(pl, segment_info, override={'vicmd': 'COMMND', 'viins': 'INSERT'}, default=None): '''Return the current mode. - + :param dict override: dict for overriding mode strings. :param str default: diff --git a/powerline/segments/vim.py b/powerline/segments/vim.py index ac9552d6..9161c729 100644 --- a/powerline/segments/vim.py +++ b/powerline/segments/vim.py @@ -161,7 +161,6 @@ def file_directory(pl, segment_info, shorten_user=True, shorten_cwd=True, shorte name = buffer_name(segment_info['buffer']) if not name: return None - import sys file_directory = vim_funcs['fnamemodify'](name, (':~' if shorten_user else '') + (':.' if shorten_cwd else '') + ':h') if not file_directory: @@ -285,7 +284,7 @@ def line_percent(pl, segment_info, gradient=False): @window_cached -def position(pl, position_strings={'top':'Top', 'bottom':'Bot', 'all':'All'}, gradient=False): +def position(pl, position_strings={'top': 'Top', 'bottom': 'Bot', 'all': 'All'}, gradient=False): '''Return the position of the current view in the file as a percentage. :param dict position_strings: @@ -368,6 +367,7 @@ def modified_buffers(pl, text='+ ', join_str=','): return text + join_str.join(buffer_mod) return None + @requires_segment_info def branch(pl, segment_info, status_colors=False): '''Return the current working branch. @@ -395,6 +395,7 @@ def branch(pl, segment_info, status_colors=False): 'divider_highlight_group': 'branch:divider', }] + @requires_segment_info def file_vcs_status(pl, segment_info): '''Return the VCS status for this buffer. diff --git a/powerline/theme.py b/powerline/theme.py index 23b0fc6f..d6b185f2 100644 --- a/powerline/theme.py +++ b/powerline/theme.py @@ -1,7 +1,7 @@ # vim:fileencoding=utf-8:noet from powerline.segment import gen_segment_getter -from powerline.lib.unicode import u, unicode +from powerline.lib.unicode import u def requires_segment_info(func): diff --git a/tests/test_cmdline.py b/tests/test_cmdline.py index cc27d396..c330da36 100644 --- a/tests/test_cmdline.py +++ b/tests/test_cmdline.py @@ -18,9 +18,11 @@ class TestParser(TestCase): parser = get_argparser() out = StrIO() err = StrIO() + def flush(): out.truncate(0) err.truncate(0) + with replace_attr(sys, 'stdout', out, 'stderr', err): for raising_args, raising_reg in [ ([], 'too few arguments|the following arguments are required: ext'), @@ -69,7 +71,7 @@ class TestParser(TestCase): '-c', 'common.spaces=4', '-t', 'default.segment_data.hostname.before=H:', '-p', '.', - '-R', 'smth={"abc":"def"}' + '-R', 'smth={"abc":"def"}', ], { 'ext': ['shell'], 'side': 'left', diff --git a/tests/test_segments.py b/tests/test_segments.py index bfea4f6a..97077658 100644 --- a/tests/test_segments.py +++ b/tests/test_segments.py @@ -476,8 +476,8 @@ class TestCommon(TestCase): def test_environment(self): pl = Pl() - variable = 'FOO'; - value = 'bar'; + variable = 'FOO' + value = 'bar' with replace_env(variable, value) as segment_info: self.assertEqual(common.environment(pl=pl, segment_info=segment_info, variable=variable), value) segment_info['environ'].pop(variable) @@ -542,6 +542,7 @@ class TestCommon(TestCase): } ]) + class TestVim(TestCase): def test_mode(self): pl = Pl() @@ -659,10 +660,10 @@ class TestVim(TestCase): vim_module._set_cursor(0, 0) self.assertEqual(vim.position(pl=pl, segment_info=segment_info), 'Top') vim_module._set_cursor(97, 0) - self.assertEqual(vim.position(pl=pl, segment_info=segment_info, position_strings={'top':'Comienzo', 'bottom':'Final', 'all':'Todo'}), 'Final') + self.assertEqual(vim.position(pl=pl, segment_info=segment_info, position_strings={'top': 'Comienzo', 'bottom': 'Final', 'all': 'Todo'}), 'Final') segment_info['buffer'][0:-1] = [str(i) for i in range(2)] vim_module._set_cursor(0, 0) - self.assertEqual(vim.position(pl=pl, segment_info=segment_info, position_strings={'top':'Comienzo', 'bottom':'Final', 'all':'Todo'}), 'Todo') + self.assertEqual(vim.position(pl=pl, segment_info=segment_info, position_strings={'top': 'Comienzo', 'bottom': 'Final', 'all': 'Todo'}), 'Todo') self.assertEqual(vim.position(pl=pl, segment_info=segment_info, gradient=True), [{'contents': 'All', 'highlight_group': ['position_gradient', 'position'], 'gradient_level': 0.0}]) finally: diff --git a/tests/test_shells/postproc.py b/tests/test_shells/postproc.py index 2da1fbc7..8d85917c 100755 --- a/tests/test_shells/postproc.py +++ b/tests/test_shells/postproc.py @@ -38,14 +38,14 @@ with codecs.open(fname, 'r', encoding='utf-8') as R: try: start = line.index('\033[0;') end = line.index('\033[0m', start) - line = line[start : end+4] + '\n' + line = line[start:end + 4] + '\n' except ValueError: line = '' elif shell == 'tcsh': try: start = line.index('\033[0;') end = line.index(' ', start) - line = line[start : end] + '\033[0m\n' + line = line[start:end] + '\033[0m\n' except ValueError: line = '' W.write(line) diff --git a/tests/vim.py b/tests/vim.py index 56efbbb1..f447f490 100644 --- a/tests/vim.py +++ b/tests/vim.py @@ -307,9 +307,9 @@ def _emul_line(expr): cursorline = windows[_window - 1].cursor[0] + 1 numlines = len(_buf_lines[_buffer()]) if expr == 'w0': - return max(cursorline-5, 1) + return max(cursorline - 5, 1) if expr == 'w$': - return min(cursorline+5, numlines) + return min(cursorline + 5, numlines) raise NotImplementedError @@ -401,7 +401,6 @@ class _Buffer(object): import os if type(name) is not bytes: name = name.encode('utf-8') - import sys self._name = os.path.abspath(name) def __getitem__(self, line): diff --git a/tools/generate_gradients.py b/tools/generate_gradients.py index 6bfe2cce..80adae15 100755 --- a/tools/generate_gradients.py +++ b/tools/generate_gradients.py @@ -138,8 +138,8 @@ palettes = { '256': (cterm_to_hex, lambda c: c), None: (cterm_to_hex[16:], lambda c: c + 16), } -r = [get_rgb(*color) for color in gradient] -r2 = [find_color(color, *palettes[args.palette])[0] for color in gradient] +r = [get_rgb(*col) for col in gradient] +r2 = [find_color(col, *palettes[args.palette])[0] for col in gradient] r3 = [i[0] for i in groupby(r2)] print(json.dumps(r)) print(json.dumps(r2))