Merge pull request #1045 from ZyX-I/style-fixes

Improve coding style
This commit is contained in:
Nikolai Aleksandrovich Pavlov 2014-09-01 00:30:05 +04:00
commit a4667c9a76
111 changed files with 551 additions and 413 deletions

View File

@ -67,6 +67,65 @@ Programming style
documentation and commit messages. documentation and commit messages.
* It is allowed to have too long lines. It is advised though to avoid lines * It is allowed to have too long lines. It is advised though to avoid lines
wider then a hundred of characters. wider then a hundred of characters.
* Imports have the following structure:
1. Shebang and modeline in a form
.. code-block:: python
#!/usr/bin/env python
# vim:fileencoding=utf-8:noet
. Modeline is required, shebang is not. If shebang is present file must end
with
.. code-block:: python
if __name__ == '__main__':
# Actual script here
2. Module docstring.
3. ``__future__`` import exactly in a form
.. code-block:: python
from __future__ import (unicode_literals, division, absolute_import, print_function)
(powerline.shell is the only exception due to problems with argparse). It
is not separated by newline with shebang and modeline, but is with
docstring.
4. Standard python library imports in a form ``import X``.
5. Standard python library imports in a form ``from X import Y``.
6. Third-party (non-python and non-powerline) library imports in a form
``import X``.
7. Third-party library imports in a form ``from X import Y``.
8. Powerline non-test imports in a form ``from powerline.X import Y``.
9. Powerline test imports in a form ``import tests.vim as vim_module``.
10. Powerline test imports in a form ``from tests.X import Y``.
Each entry is separated by newline from another entry. Any entry except for
the first and third ones is optional. Example with all entries:
.. code-block:: python
#!/usr/bin/env python
# vim:fileencoding=utf-8:noet
'''Powerline super module'''
import sys
from argparse import ArgumentParser
import psutil
from colormath.color_diff import delta_e_cie2000
from powerline.lib.unicode import u
import tests.vim as vim_module
from tests import TestCase
Submitting changes Submitting changes
================== ==================

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function) from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys

View File

@ -1,8 +1,10 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os
import sys import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd()))))
sys.path.insert(0, os.path.abspath(os.getcwd())) sys.path.insert(0, os.path.abspath(os.getcwd()))

View File

@ -17,26 +17,29 @@ Python package
. .
.. note:: .. note::
In case you want or have to use ``powerline.sh`` socat-based client you In case you want or have to use ``powerline.sh`` socat-based client you
should also install GNU env named ``genv``. This may be achieved by running should also install GNU env named ``genv``. This may be achieved by
``brew install coreutils``. running ``brew install coreutils``.
2. Install Powerline using the following command:: 2. Install Powerline using the following command::
pip install --user git+git://github.com/Lokaltog/powerline pip install --user git+git://github.com/Lokaltog/powerline
.. warning:: When using ``brew install`` to install Python one must not supply .. warning::
``--user`` flag to ``pip``. When using ``brew install`` to install Python one must not supply
``--user`` flag to ``pip``.
.. note:: You need to use the GitHub URI when installing Powerline! This .. note::
project is currently unavailable on the PyPI due to a naming conflict You need to use the GitHub URI when installing Powerline! This project is
with an unrelated project. currently unavailable on the PyPI due to a naming conflict with an
unrelated project.
.. note:: If you are powerline developer you should be aware that ``pip install .. note::
--editable`` does not currently fully work. If you install powerline this way If you are powerline developer you should be aware that ``pip install
you will be missing ``powerline`` executable and need to symlink it. It will --editable`` does not currently fully work. If you install powerline this
be located in ``scripts/powerline``. way you will be missing ``powerline`` executable and need to symlink it. It
will be located in ``scripts/powerline``.
Vim installation Vim installation
================ ================

View File

@ -1,13 +1,13 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from sphinx.ext import autodoc from __future__ import (unicode_literals, division, absolute_import, print_function)
from inspect import formatargspec from inspect import formatargspec
from sphinx.ext import autodoc
from powerline.lint.inspect import getconfigargspec from powerline.lint.inspect import getconfigargspec
from powerline.segments import Segment from powerline.segments import Segment
from powerline.lib.unicode import unicode
try:
from __builtin__ import unicode
except ImportError:
unicode = lambda s, enc: s # NOQA
def formatvalue(val): def formatvalue(val):

View File

@ -1,6 +1,6 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import
import os import os
import sys import sys
import logging import logging

View File

@ -1,11 +1,14 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
from time import sleep
from subprocess import Popen, PIPE
from powerline import Powerline from powerline import Powerline
import sys
from time import sleep
from powerline.lib.monotonic import monotonic from powerline.lib.monotonic import monotonic
from subprocess import Popen, PIPE
powerline = Powerline('wm', renderer_module='pango_markup') powerline = Powerline('wm', renderer_module='pango_markup')
powerline.update_renderer() powerline.update_renderer()

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals, print_function
import os import os
import re import re

View File

@ -1,15 +1,17 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import print_function from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline import Powerline
from powerline.lib.monotonic import monotonic
import sys import sys
import time import time
import i3
from threading import Lock from threading import Lock
import i3
from powerline import Powerline
from powerline.lib.monotonic import monotonic
if __name__ == '__main__': if __name__ == '__main__':
name = 'wm' name = 'wm'

View File

@ -1,12 +1,13 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from weakref import ref from weakref import ref
from powerline.ipython import IPythonPowerline, RewriteResult
from IPython.core.prompts import PromptManager from IPython.core.prompts import PromptManager
from IPython.core.magic import Magics, magics_class, line_magic from IPython.core.magic import Magics, magics_class, line_magic
from powerline.ipython import IPythonPowerline, RewriteResult
@magics_class @magics_class
class PowerlineMagics(Magics): class PowerlineMagics(Magics):

View File

@ -1,16 +1,17 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import re import re
from weakref import ref from weakref import ref
from powerline.ipython import IPythonPowerline, RewriteResult
from powerline.lib.unicode import string
from IPython.Prompts import BasePrompt from IPython.Prompts import BasePrompt
from IPython.ipapi import get as get_ipython from IPython.ipapi import get as get_ipython
from IPython.ipapi import TryNext from IPython.ipapi import TryNext
from powerline.ipython import IPythonPowerline, RewriteResult
from powerline.lib.unicode import string
class IPythonInfo(object): class IPythonInfo(object):
def __init__(self, cache): def __init__(self, cache):

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from libqtile import bar from libqtile import bar
from libqtile.widget import base from libqtile.widget import base

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals, division, print_function
import re import re
import os import os

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys
import codecs import codecs
@ -8,6 +9,10 @@ try:
except ImportError: except ImportError:
vim = {} vim = {}
if not hasattr(vim, 'bindeval'):
import json
if hasattr(vim, 'bindeval'): if hasattr(vim, 'bindeval'):
def vim_get_func(f, rettype=None): def vim_get_func(f, rettype=None):
'''Return a vim function binding.''' '''Return a vim function binding.'''
@ -19,8 +24,6 @@ if hasattr(vim, 'bindeval'):
except vim.error: except vim.error:
return None return None
else: else:
import json
class VimFunc(object): class VimFunc(object):
'''Evaluate a vim function using vim.eval(). '''Evaluate a vim function using vim.eval().
@ -73,14 +76,14 @@ else:
_vim_exists = vim_get_func('exists', rettype=int) _vim_exists = vim_get_func('exists', rettype=int)
def vim_getvar(varname): # NOQA def vim_getvar(varname):
varname = 'g:' + varname varname = 'g:' + varname
if _vim_exists(varname): if _vim_exists(varname):
return vim.eval(varname) return vim.eval(varname)
else: else:
raise KeyError(varname) raise KeyError(varname)
def bufvar_exists(buffer, varname): # NOQA def bufvar_exists(buffer, varname):
if not buffer or buffer.number == vim.current.buffer.number: if not buffer or buffer.number == vim.current.buffer.number:
return int(vim.eval('exists("b:{0}")'.format(varname))) return int(vim.eval('exists("b:{0}")'.format(varname)))
else: else:
@ -88,7 +91,7 @@ else:
'has_key(getbufvar({0}, ""), {1})'.format(buffer.number, varname) 'has_key(getbufvar({0}, ""), {1})'.format(buffer.number, varname)
)) ))
def vim_getwinvar(segment_info, varname): # NOQA def vim_getwinvar(segment_info, varname):
result = vim.eval('getwinvar({0}, "{1}")'.format(segment_info['winnr'], varname)) result = vim.eval('getwinvar({0}, "{1}")'.format(segment_info['winnr'], varname))
if result == '': if result == '':
if not int(vim.eval('has_key(getwinvar({0}, ""), "{1}")'.format(segment_info['winnr'], varname))): if not int(vim.eval('has_key(getwinvar({0}, ""), "{1}")'.format(segment_info['winnr'], varname))):
@ -122,13 +125,13 @@ if hasattr(vim, 'options'):
def vim_setoption(option, value): def vim_setoption(option, value):
vim.options[str(option)] = value vim.options[str(option)] = value
else: else:
def vim_getbufoption(info, option): # NOQA def vim_getbufoption(info, option):
return getbufvar(info['bufnr'], '&' + option) return getbufvar(info['bufnr'], '&' + option)
def vim_getoption(option): # NOQA def vim_getoption(option):
return vim.eval('&g:' + option) return vim.eval('&g:' + option)
def vim_setoption(option, value): # NOQA def vim_setoption(option, value):
vim.command('let &g:{option} = {value}'.format( vim.command('let &g:{option} = {value}'.format(
option=option, value=json.encode(value))) option=option, value=json.encode(value)))
@ -205,10 +208,10 @@ else:
def _last_tab_nr(): def _last_tab_nr():
return int(vim.eval('tabpagenr("$")')) return int(vim.eval('tabpagenr("$")'))
def current_tabpage(): # NOQA def current_tabpage():
return Tabpage(int(vim.eval('tabpagenr()'))) return Tabpage(int(vim.eval('tabpagenr()')))
def list_tabpages(): # NOQA def list_tabpages():
return [Tabpage(nr) for nr in range(1, _last_tab_nr() + 1)] return [Tabpage(nr) for nr in range(1, _last_tab_nr() + 1)]
class TabBufSegmentInfo(dict): class TabBufSegmentInfo(dict):
@ -258,7 +261,7 @@ if sys.version_info < (3,):
else: else:
vim_bufname = vim_get_func('bufname') vim_bufname = vim_get_func('bufname')
def buffer_name(buf): # NOQA def buffer_name(buf):
try: try:
name = buf.name name = buf.name
except UnicodeDecodeError: except UnicodeDecodeError:

View File

@ -1,12 +1,12 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import absolute_import, unicode_literals, division, print_function from __future__ import (unicode_literals, division, absolute_import, print_function)
import atexit import atexit
import zsh
from weakref import WeakValueDictionary, ref from weakref import WeakValueDictionary, ref
import zsh
from powerline.shell import ShellPowerline from powerline.shell import ShellPowerline
from powerline.lib import parsedotval from powerline.lib import parsedotval
from powerline.lib.unicode import unicode from powerline.lib.unicode import unicode

View File

@ -1,10 +1,9 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from copy import copy from copy import copy
try:
from __builtin__ import unicode from powerline.lib.unicode import unicode
except ImportError:
unicode = str
DEFAULT_MODE_KEY = None DEFAULT_MODE_KEY = None

View File

@ -1,8 +1,9 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals, print_function
import os import os
POWERLINE_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) POWERLINE_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BINDINGS_DIRECTORY = os.path.join(POWERLINE_ROOT, 'powerline', 'bindings') BINDINGS_DIRECTORY = os.path.join(POWERLINE_ROOT, 'powerline', 'bindings')
TMUX_CONFIG_DIRECTORY = os.path.join(BINDINGS_DIRECTORY, 'tmux') TMUX_CONFIG_DIRECTORY = os.path.join(BINDINGS_DIRECTORY, 'tmux')

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline import Powerline from powerline import Powerline
from powerline.lib import mergedicts from powerline.lib import mergedicts

View File

@ -1,7 +1,10 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from functools import wraps from __future__ import (unicode_literals, division, absolute_import, print_function)
import json import json
from functools import wraps
REMOVE_THIS_KEY = object() REMOVE_THIS_KEY = object()

View File

@ -1,15 +1,16 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.lib.threaded import MultiRunnedThread
from powerline.lib.watcher import create_file_watcher
from copy import deepcopy
from threading import Event, Lock
from collections import defaultdict
import json import json
import codecs import codecs
from copy import deepcopy
from threading import Event, Lock
from collections import defaultdict
from powerline.lib.threaded import MultiRunnedThread
from powerline.lib.watcher import create_file_watcher
def open_file(path): def open_file(path):
return codecs.open(path, encoding='utf-8') return codecs.open(path, encoding='utf-8')

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import gc import gc
import sys import sys

View File

@ -1,6 +1,9 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from math import log from math import log
unit_list = tuple(zip(['', 'k', 'M', 'G', 'T', 'P'], [0, 0, 1, 2, 2, 2])) unit_list = tuple(zip(['', 'k', 'M', 'G', 'T', 'P'], [0, 0, 1, 2, 2, 2]))

View File

@ -1,8 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import unicode_literals, absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys import sys
import os import os
@ -13,6 +10,10 @@ import struct
from ctypes.util import find_library from ctypes.util import find_library
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
class INotifyError(Exception): class INotifyError(Exception):
pass pass

View File

@ -1,6 +1,8 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from functools import wraps from functools import wraps
from powerline.lib.monotonic import monotonic from powerline.lib.monotonic import monotonic
@ -35,6 +37,6 @@ class memoize(object):
cached = self.cache[key] = { cached = self.cache[key] = {
'result': func(**kwargs), 'result': func(**kwargs),
'time': monotonic(), 'time': monotonic(),
} }
return cached['result'] return cached['result']
return decorated_function return decorated_function

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import division, absolute_import
try: try:
try: try:
@ -10,14 +9,12 @@ try:
# >={kernel}-sources-2.6.28 # >={kernel}-sources-2.6.28
from time import CLOCK_MONOTONIC_RAW as CLOCK_ID from time import CLOCK_MONOTONIC_RAW as CLOCK_ID
except ImportError: except ImportError:
from time import CLOCK_MONOTONIC as CLOCK_ID # NOQA from time import CLOCK_MONOTONIC as CLOCK_ID
monotonic = lambda: clock_gettime(CLOCK_ID) monotonic = lambda: clock_gettime(CLOCK_ID)
except ImportError: except ImportError:
# >=python-3.3 # >=python-3.3
from time import monotonic # NOQA from time import monotonic
except ImportError: except ImportError:
import ctypes import ctypes
import sys import sys
@ -28,7 +25,7 @@ except ImportError:
GetTickCount64 = ctypes.windll.kernel32.GetTickCount64 GetTickCount64 = ctypes.windll.kernel32.GetTickCount64
GetTickCount64.restype = ctypes.c_ulonglong GetTickCount64.restype = ctypes.c_ulonglong
def monotonic(): # NOQA def monotonic():
return GetTickCount64() / 1000 return GetTickCount64() / 1000
elif sys.platform == 'darwin': elif sys.platform == 'darwin':
@ -64,7 +61,7 @@ except ImportError:
timebase = mach_timebase_info() timebase = mach_timebase_info()
factor = timebase[0] / timebase[1] * 1e-9 factor = timebase[0] / timebase[1] * 1e-9
def monotonic(): # NOQA def monotonic():
return mach_absolute_time() * factor return mach_absolute_time() * factor
else: else:
# linux only (no librt on OS X) # linux only (no librt on OS X)
@ -93,7 +90,7 @@ except ImportError:
else: else:
raise OSError raise OSError
def monotonic(): # NOQA def monotonic():
if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(tspec)) != 0: if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(tspec)) != 0:
errno_ = ctypes.get_errno() errno_ = ctypes.get_errno()
raise OSError(errno_, os.strerror(errno_)) raise OSError(errno_, os.strerror(errno_))

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import unicode_literals, absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os

View File

@ -1,12 +1,12 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals, division, print_function import sys
import os
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
from locale import getlocale, getdefaultlocale, LC_MESSAGES from locale import getlocale, getdefaultlocale, LC_MESSAGES
from functools import partial from functools import partial
import sys
import os
if sys.platform.startswith('win32'): if sys.platform.startswith('win32'):
@ -68,7 +68,7 @@ try:
except ImportError: except ImportError:
# shutil.which was added in python-3.3. Here is what was added: # shutil.which was added in python-3.3. Here is what was added:
# Lib/shutil.py, commit 5abe28a9c8fe701ba19b1db5190863384e96c798 # Lib/shutil.py, commit 5abe28a9c8fe701ba19b1db5190863384e96c798
def which(cmd, mode=os.F_OK | os.X_OK, path=None): # NOQA def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which """Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such conforms to the given mode on the PATH, or None if there is no such
file. file.

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import
from threading import Thread, Lock, Event from threading import Thread, Lock, Event
from types import MethodType from types import MethodType

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from locale import getpreferredencoding from locale import getpreferredencoding
@ -7,7 +7,13 @@ from locale import getpreferredencoding
try: try:
from __builtin__ import unicode from __builtin__ import unicode
except ImportError: except ImportError:
unicode = str # NOQA unicode = str
try:
from __builtin__ import unichr
except ImportError:
unichr = chr
def u(s): def u(s):

View File

@ -1,8 +1,9 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
try: try:
from urllib.error import HTTPError from urllib.error import HTTPError # NOQA
from urllib.request import urlopen from urllib.request import urlopen # NOQA
from urllib.parse import urlencode as urllib_urlencode # NOQA from urllib.parse import urlencode as urllib_urlencode # NOQA
except ImportError: except ImportError:
from urllib2 import urlopen, HTTPError # NOQA from urllib2 import urlopen, HTTPError # NOQA

View File

@ -1,8 +1,9 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os
import errno import errno
from threading import Lock from threading import Lock
from collections import defaultdict from collections import defaultdict
@ -226,7 +227,7 @@ def guess(path, create_watcher):
continue continue
try: try:
if vcs not in globals(): if vcs not in globals():
globals()[vcs] = getattr(__import__('powerline.lib.vcs', fromlist=[vcs]), vcs) globals()[vcs] = getattr(__import__(str('powerline.lib.vcs'), fromlist=[str(vcs)]), str(vcs))
return globals()[vcs].Repository(directory, create_watcher) return globals()[vcs].Repository(directory, create_watcher)
except: except:
pass pass

View File

@ -1,9 +1,10 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import absolute_import, unicode_literals, division, print_function from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys
import os import os
import re import re
from io import StringIO from io import StringIO
from bzrlib import (workingtree, status, library_state, trace, ui) from bzrlib import (workingtree, status, library_state, trace, ui)

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import (unicode_literals, absolute_import, print_function)
import os import os
import sys import sys

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import unicode_literals, absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys
@ -11,8 +11,7 @@ from powerline.lib.inotify import INotifyError
def create_file_watcher(pl, watcher_type='auto', expire_time=10): def create_file_watcher(pl, watcher_type='auto', expire_time=10):
''' '''Create an object that can watch for changes to specified files
Create an object that can watch for changes to specified files
Use ``.__call__()`` method of the returned object to start watching the file Use ``.__call__()`` method of the returned object to start watching the file
or check whether file has changed since last call. or check whether file has changed since last call.

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import unicode_literals, absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
import errno import errno
import os import os
@ -213,13 +213,17 @@ class INotifyTreeWatcher(INotify):
def add_watch(self, path): def add_watch(self, path):
bpath = path if isinstance(path, bytes) else path.encode(self.fenc) bpath = path if isinstance(path, bytes) else path.encode(self.fenc)
wd = self._add_watch(self._inotify_fd, ctypes.c_char_p(bpath), wd = self._add_watch(
# Ignore symlinks and watch only directories self._inotify_fd,
self.DONT_FOLLOW | self.ONLYDIR | ctypes.c_char_p(bpath),
self.MODIFY | self.CREATE | self.DELETE | # Ignore symlinks and watch only directories
self.MOVE_SELF | self.MOVED_FROM | self.MOVED_TO | self.DONT_FOLLOW | self.ONLYDIR |
self.ATTRIB | self.DELETE_SELF)
self.MODIFY | self.CREATE | self.DELETE |
self.MOVE_SELF | self.MOVED_FROM | self.MOVED_TO |
self.ATTRIB | self.DELETE_SELF
)
if wd == -1: if wd == -1:
eno = ctypes.get_errno() eno = ctypes.get_errno()
if eno == errno.ENOTDIR: if eno == errno.ENOTDIR:

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import unicode_literals, absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, absolute_import, print_function) from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys

View File

@ -1,14 +1,14 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, absolute_import, print_function) from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.lib.path import realpath import os
from collections import defaultdict from collections import defaultdict
from threading import RLock from threading import RLock
from functools import partial from functools import partial
from threading import Thread from threading import Thread
import os from powerline.lib.path import realpath
class UvNotFound(NotImplementedError): class UvNotFound(NotImplementedError):

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import itertools import itertools
import sys import sys
@ -560,8 +561,8 @@ def check_top_theme(theme, data, context, echoerr):
return True, False, False return True, False, False
divider_spec = Spec().type(unicode).len('le', 3, divider_spec = Spec().type(unicode).len(
lambda value: 'Divider {0!r} is too large!'.format(value)).copy 'le', 3, (lambda value: 'Divider {0!r} is too large!'.format(value))).copy
ext_theme_spec = Spec().type(unicode).func(lambda *args: check_config('themes', *args)).copy ext_theme_spec = Spec().type(unicode).func(lambda *args: check_config('themes', *args)).copy
top_theme_spec = Spec().type(unicode).func(check_top_theme).copy top_theme_spec = Spec().type(unicode).func(check_top_theme).copy
ext_spec = Spec( ext_spec = Spec(

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
from inspect import ArgSpec, getargspec from inspect import ArgSpec, getargspec

View File

@ -1,7 +1,7 @@
__version__ = '3.10' # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.lint.markedjson.loader import Loader
from .loader import Loader
def load(stream, Loader=Loader): def load(stream, Loader=Loader):

View File

@ -1,8 +1,12 @@
__all__ = ['Composer', 'ComposerError'] # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from .error import MarkedError from powerline.lint.markedjson import nodes
from .events import * # NOQA from powerline.lint.markedjson import events
from .nodes import * # NOQA from powerline.lint.markedjson.error import MarkedError
__all__ = ['Composer', 'ComposerError']
class ComposerError(MarkedError): class ComposerError(MarkedError):
@ -15,15 +19,15 @@ class Composer:
def check_node(self): def check_node(self):
# Drop the STREAM-START event. # Drop the STREAM-START event.
if self.check_event(StreamStartEvent): if self.check_event(events.StreamStartEvent):
self.get_event() self.get_event()
# If there are more documents available? # If there are more documents available?
return not self.check_event(StreamEndEvent) return not self.check_event(events.StreamEndEvent)
def get_node(self): def get_node(self):
# Get the root node of the next document. # Get the root node of the next document.
if not self.check_event(StreamEndEvent): if not self.check_event(events.StreamEndEvent):
return self.compose_document() return self.compose_document()
def get_single_node(self): def get_single_node(self):
@ -32,11 +36,11 @@ class Composer:
# Compose a document if the stream is not empty. # Compose a document if the stream is not empty.
document = None document = None
if not self.check_event(StreamEndEvent): if not self.check_event(events.StreamEndEvent):
document = self.compose_document() document = self.compose_document()
# Ensure that the stream contains no more documents. # Ensure that the stream contains no more documents.
if not self.check_event(StreamEndEvent): if not self.check_event(events.StreamEndEvent):
event = self.get_event() event = self.get_event()
raise ComposerError( raise ComposerError(
"expected a single document in the stream", "expected a single document in the stream",
@ -64,11 +68,11 @@ class Composer:
def compose_node(self, parent, index): def compose_node(self, parent, index):
self.descend_resolver(parent, index) self.descend_resolver(parent, index)
if self.check_event(ScalarEvent): if self.check_event(events.ScalarEvent):
node = self.compose_scalar_node() node = self.compose_scalar_node()
elif self.check_event(SequenceStartEvent): elif self.check_event(events.SequenceStartEvent):
node = self.compose_sequence_node() node = self.compose_sequence_node()
elif self.check_event(MappingStartEvent): elif self.check_event(events.MappingStartEvent):
node = self.compose_mapping_node() node = self.compose_mapping_node()
self.ascend_resolver() self.ascend_resolver()
return node return node
@ -77,18 +81,18 @@ class Composer:
event = self.get_event() event = self.get_event()
tag = event.tag tag = event.tag
if tag is None or tag == '!': if tag is None or tag == '!':
tag = self.resolve(ScalarNode, event.value, event.implicit, event.start_mark) tag = self.resolve(nodes.ScalarNode, event.value, event.implicit, event.start_mark)
node = ScalarNode(tag, event.value, event.start_mark, event.end_mark, style=event.style) node = nodes.ScalarNode(tag, event.value, event.start_mark, event.end_mark, style=event.style)
return node return node
def compose_sequence_node(self): def compose_sequence_node(self):
start_event = self.get_event() start_event = self.get_event()
tag = start_event.tag tag = start_event.tag
if tag is None or tag == '!': if tag is None or tag == '!':
tag = self.resolve(SequenceNode, None, start_event.implicit) tag = self.resolve(nodes.SequenceNode, None, start_event.implicit)
node = SequenceNode(tag, [], start_event.start_mark, None, flow_style=start_event.flow_style) node = nodes.SequenceNode(tag, [], start_event.start_mark, None, flow_style=start_event.flow_style)
index = 0 index = 0
while not self.check_event(SequenceEndEvent): while not self.check_event(events.SequenceEndEvent):
node.value.append(self.compose_node(node, index)) node.value.append(self.compose_node(node, index))
index += 1 index += 1
end_event = self.get_event() end_event = self.get_event()
@ -99,9 +103,9 @@ class Composer:
start_event = self.get_event() start_event = self.get_event()
tag = start_event.tag tag = start_event.tag
if tag is None or tag == '!': if tag is None or tag == '!':
tag = self.resolve(MappingNode, None, start_event.implicit) tag = self.resolve(nodes.MappingNode, None, start_event.implicit)
node = MappingNode(tag, [], start_event.start_mark, None, flow_style=start_event.flow_style) node = nodes.MappingNode(tag, [], start_event.start_mark, None, flow_style=start_event.flow_style)
while not self.check_event(MappingEndEvent): while not self.check_event(events.MappingEndEvent):
# key_event = self.peek_event() # key_event = self.peek_event()
item_key = self.compose_node(node, None) item_key = self.compose_node(node, None)
# if item_key in node.value: # if item_key in node.value:

View File

@ -1,19 +1,16 @@
__all__ = ['BaseConstructor', 'Constructor', 'ConstructorError'] # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from .error import MarkedError
from .nodes import * # NOQA
from .markedvalue import gen_marked_value
import collections import collections
import types import types
from functools import wraps from functools import wraps
from powerline.lint.markedjson.error import MarkedError
try: from powerline.lint.markedjson import nodes
from __builtin__ import unicode from powerline.lint.markedjson.markedvalue import gen_marked_value
except ImportError: from powerline.lib.unicode import unicode
unicode = str # NOQA
def marked(func): def marked(func):
@ -94,7 +91,7 @@ class BaseConstructor:
@marked @marked
def construct_scalar(self, node): def construct_scalar(self, node):
if not isinstance(node, ScalarNode): if not isinstance(node, nodes.ScalarNode):
raise ConstructorError( raise ConstructorError(
None, None, None, None,
"expected a scalar node, but found %s" % node.id, "expected a scalar node, but found %s" % node.id,
@ -103,7 +100,7 @@ class BaseConstructor:
return node.value return node.value
def construct_sequence(self, node, deep=False): def construct_sequence(self, node, deep=False):
if not isinstance(node, SequenceNode): if not isinstance(node, nodes.SequenceNode):
raise ConstructorError( raise ConstructorError(
None, None, None, None,
"expected a sequence node, but found %s" % node.id, "expected a sequence node, but found %s" % node.id,
@ -116,7 +113,7 @@ class BaseConstructor:
@marked @marked
def construct_mapping(self, node, deep=False): def construct_mapping(self, node, deep=False):
if not isinstance(node, MappingNode): if not isinstance(node, nodes.MappingNode):
raise ConstructorError( raise ConstructorError(
None, None, None, None,
"expected a mapping node, but found %s" % node.id, "expected a mapping node, but found %s" % node.id,
@ -156,7 +153,7 @@ class BaseConstructor:
class Constructor(BaseConstructor): class Constructor(BaseConstructor):
def construct_scalar(self, node): def construct_scalar(self, node):
if isinstance(node, MappingNode): if isinstance(node, nodes.MappingNode):
for key_node, value_node in node.value: for key_node, value_node in node.value:
if key_node.tag == 'tag:yaml.org,2002:value': if key_node.tag == 'tag:yaml.org,2002:value':
return self.construct_scalar(value_node) return self.construct_scalar(value_node)
@ -169,13 +166,13 @@ class Constructor(BaseConstructor):
key_node, value_node = node.value[index] key_node, value_node = node.value[index]
if key_node.tag == 'tag:yaml.org,2002:merge': if key_node.tag == 'tag:yaml.org,2002:merge':
del node.value[index] del node.value[index]
if isinstance(value_node, MappingNode): if isinstance(value_node, nodes.MappingNode):
self.flatten_mapping(value_node) self.flatten_mapping(value_node)
merge.extend(value_node.value) merge.extend(value_node.value)
elif isinstance(value_node, SequenceNode): elif isinstance(value_node, nodes.SequenceNode):
submerge = [] submerge = []
for subnode in value_node.value: for subnode in value_node.value:
if not isinstance(subnode, MappingNode): if not isinstance(subnode, nodes.MappingNode):
raise ConstructorError( raise ConstructorError(
"while constructing a mapping", "while constructing a mapping",
node.start_mark, node.start_mark,
@ -203,7 +200,7 @@ class Constructor(BaseConstructor):
node.value = merge + node.value node.value = merge + node.value
def construct_mapping(self, node, deep=False): def construct_mapping(self, node, deep=False):
if isinstance(node, MappingNode): if isinstance(node, nodes.MappingNode):
self.flatten_mapping(node) self.flatten_mapping(node)
return BaseConstructor.construct_mapping(self, node, deep=deep) return BaseConstructor.construct_mapping(self, node, deep=deep)
@ -264,32 +261,25 @@ class Constructor(BaseConstructor):
Constructor.add_constructor( Constructor.add_constructor(
'tag:yaml.org,2002:null', 'tag:yaml.org,2002:null', Constructor.construct_yaml_null)
Constructor.construct_yaml_null)
Constructor.add_constructor( Constructor.add_constructor(
'tag:yaml.org,2002:bool', 'tag:yaml.org,2002:bool', Constructor.construct_yaml_bool)
Constructor.construct_yaml_bool)
Constructor.add_constructor( Constructor.add_constructor(
'tag:yaml.org,2002:int', 'tag:yaml.org,2002:int', Constructor.construct_yaml_int)
Constructor.construct_yaml_int)
Constructor.add_constructor( Constructor.add_constructor(
'tag:yaml.org,2002:float', 'tag:yaml.org,2002:float', Constructor.construct_yaml_float)
Constructor.construct_yaml_float)
Constructor.add_constructor( Constructor.add_constructor(
'tag:yaml.org,2002:str', 'tag:yaml.org,2002:str', Constructor.construct_yaml_str)
Constructor.construct_yaml_str)
Constructor.add_constructor( Constructor.add_constructor(
'tag:yaml.org,2002:seq', 'tag:yaml.org,2002:seq', Constructor.construct_yaml_seq)
Constructor.construct_yaml_seq)
Constructor.add_constructor( Constructor.add_constructor(
'tag:yaml.org,2002:map', 'tag:yaml.org,2002:map', Constructor.construct_yaml_map)
Constructor.construct_yaml_map)
Constructor.add_constructor(None, Constructor.add_constructor(
Constructor.construct_undefined) None, Constructor.construct_undefined)

View File

@ -1,13 +1,10 @@
__all__ = ['Mark', 'MarkedError', 'echoerr', 'NON_PRINTABLE'] # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys
import re import re
try: from powerline.lib.unicode import unichr
from __builtin__ import unichr
except ImportError:
unichr = chr # NOQA
NON_PRINTABLE = re.compile('[^\t\n\x20-\x7E' + unichr(0x85) + (unichr(0xA0) + '-' + unichr(0xD7FF)) + (unichr(0xE000) + '-' + unichr(0xFFFD)) + ']') NON_PRINTABLE = re.compile('[^\t\n\x20-\x7E' + unichr(0x85) + (unichr(0xA0) + '-' + unichr(0xD7FF)) + (unichr(0xE000) + '-' + unichr(0xFFFD)) + ']')

View File

@ -1,6 +1,8 @@
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
# Abstract classes. # Abstract classes.
class Event(object): class Event(object):
def __init__(self, start_mark=None, end_mark=None): def __init__(self, start_mark=None, end_mark=None):
self.start_mark = start_mark self.start_mark = start_mark
@ -38,8 +40,6 @@ class CollectionEndEvent(Event):
# Implementations. # Implementations.
class StreamStartEvent(Event): class StreamStartEvent(Event):
def __init__(self, start_mark=None, end_mark=None, encoding=None): def __init__(self, start_mark=None, end_mark=None, encoding=None):
self.start_mark = start_mark self.start_mark = start_mark

View File

@ -1,12 +1,13 @@
__all__ = ['Loader'] # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from .reader import Reader from powerline.lint.markedjson.reader import Reader
from .scanner import Scanner from powerline.lint.markedjson.scanner import Scanner
from .parser import Parser from powerline.lint.markedjson.parser import Parser
from .composer import Composer from powerline.lint.markedjson.composer import Composer
from .constructor import Constructor from powerline.lint.markedjson.constructor import Constructor
from .resolver import Resolver from powerline.lint.markedjson.resolver import Resolver
from .error import echoerr from powerline.lint.markedjson.error import echoerr
class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver): class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver):

View File

@ -1,10 +1,7 @@
__all__ = ['gen_marked_value', 'MarkedValue'] # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.lib.unicode import unicode
try:
from __builtin__ import unicode
except ImportError:
unicode = str
def gen_new(cls): def gen_new(cls):

View File

@ -1,3 +1,7 @@
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
class Node(object): class Node(object):
def __init__(self, tag, value, start_mark, end_mark): def __init__(self, tag, value, start_mark, end_mark):
self.tag = tag self.tag = tag

View File

@ -1,8 +1,9 @@
__all__ = ['Parser', 'ParserError'] # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from .error import MarkedError from powerline.lint.markedjson.error import MarkedError
from .tokens import * # NOQA from powerline.lint.markedjson import tokens
from .events import * # NOQA from powerline.lint.markedjson import events
class ParserError(MarkedError): class ParserError(MarkedError):
@ -58,7 +59,7 @@ class Parser:
def parse_stream_start(self): def parse_stream_start(self):
# Parse the stream start. # Parse the stream start.
token = self.get_token() token = self.get_token()
event = StreamStartEvent(token.start_mark, token.end_mark, encoding=token.encoding) event = events.StreamStartEvent(token.start_mark, token.end_mark, encoding=token.encoding)
# Prepare the next state. # Prepare the next state.
self.state = self.parse_implicit_document_start self.state = self.parse_implicit_document_start
@ -67,10 +68,10 @@ class Parser:
def parse_implicit_document_start(self): def parse_implicit_document_start(self):
# Parse an implicit document. # Parse an implicit document.
if not self.check_token(StreamEndToken): if not self.check_token(tokens.StreamEndToken):
token = self.peek_token() token = self.peek_token()
start_mark = end_mark = token.start_mark start_mark = end_mark = token.start_mark
event = DocumentStartEvent(start_mark, end_mark, explicit=False) event = events.DocumentStartEvent(start_mark, end_mark, explicit=False)
# Prepare the next state. # Prepare the next state.
self.states.append(self.parse_document_end) self.states.append(self.parse_document_end)
@ -83,17 +84,17 @@ class Parser:
def parse_document_start(self): def parse_document_start(self):
# Parse an explicit document. # Parse an explicit document.
if not self.check_token(StreamEndToken): if not self.check_token(tokens.StreamEndToken):
token = self.peek_token() token = self.peek_token()
self.echoerr( self.echoerr(
None, None, None, None,
("expected '<stream end>', but found %r" % token.id), token.start_mark ("expected '<stream end>', but found %r" % token.id), token.start_mark
) )
return StreamEndEvent(token.start_mark, token.end_mark) return events.StreamEndEvent(token.start_mark, token.end_mark)
else: else:
# Parse the end of the stream. # Parse the end of the stream.
token = self.get_token() token = self.get_token()
event = StreamEndEvent(token.start_mark, token.end_mark) event = events.StreamEndEvent(token.start_mark, token.end_mark)
assert not self.states assert not self.states
assert not self.marks assert not self.marks
self.state = None self.state = None
@ -104,7 +105,7 @@ class Parser:
token = self.peek_token() token = self.peek_token()
start_mark = end_mark = token.start_mark start_mark = end_mark = token.start_mark
explicit = False explicit = False
event = DocumentEndEvent(start_mark, end_mark, explicit=explicit) event = events.DocumentEndEvent(start_mark, end_mark, explicit=explicit)
# Prepare the next state. # Prepare the next state.
self.state = self.parse_document_start self.state = self.parse_document_start
@ -120,22 +121,22 @@ class Parser:
start_mark = end_mark = self.peek_token().start_mark start_mark = end_mark = self.peek_token().start_mark
event = None event = None
implicit = True implicit = True
if self.check_token(ScalarToken): if self.check_token(tokens.ScalarToken):
token = self.get_token() token = self.get_token()
end_mark = token.end_mark end_mark = token.end_mark
if token.plain: if token.plain:
implicit = (True, False) implicit = (True, False)
else: else:
implicit = (False, True) implicit = (False, True)
event = ScalarEvent(implicit, token.value, start_mark, end_mark, style=token.style) event = events.ScalarEvent(implicit, token.value, start_mark, end_mark, style=token.style)
self.state = self.states.pop() self.state = self.states.pop()
elif self.check_token(FlowSequenceStartToken): elif self.check_token(tokens.FlowSequenceStartToken):
end_mark = self.peek_token().end_mark end_mark = self.peek_token().end_mark
event = SequenceStartEvent(implicit, start_mark, end_mark, flow_style=True) event = events.SequenceStartEvent(implicit, start_mark, end_mark, flow_style=True)
self.state = self.parse_flow_sequence_first_entry self.state = self.parse_flow_sequence_first_entry
elif self.check_token(FlowMappingStartToken): elif self.check_token(tokens.FlowMappingStartToken):
end_mark = self.peek_token().end_mark end_mark = self.peek_token().end_mark
event = MappingStartEvent(implicit, start_mark, end_mark, flow_style=True) event = events.MappingStartEvent(implicit, start_mark, end_mark, flow_style=True)
self.state = self.parse_flow_mapping_first_key self.state = self.parse_flow_mapping_first_key
else: else:
token = self.peek_token() token = self.peek_token()
@ -152,11 +153,11 @@ class Parser:
return self.parse_flow_sequence_entry(first=True) return self.parse_flow_sequence_entry(first=True)
def parse_flow_sequence_entry(self, first=False): def parse_flow_sequence_entry(self, first=False):
if not self.check_token(FlowSequenceEndToken): if not self.check_token(tokens.FlowSequenceEndToken):
if not first: if not first:
if self.check_token(FlowEntryToken): if self.check_token(tokens.FlowEntryToken):
self.get_token() self.get_token()
if self.check_token(FlowSequenceEndToken): if self.check_token(tokens.FlowSequenceEndToken):
token = self.peek_token() token = self.peek_token()
self.echoerr( self.echoerr(
"While parsing a flow sequence", self.marks[-1], "While parsing a flow sequence", self.marks[-1],
@ -169,11 +170,11 @@ class Parser:
("expected ',' or ']', but got %r" % token.id), token.start_mark ("expected ',' or ']', but got %r" % token.id), token.start_mark
) )
if not self.check_token(FlowSequenceEndToken): if not self.check_token(tokens.FlowSequenceEndToken):
self.states.append(self.parse_flow_sequence_entry) self.states.append(self.parse_flow_sequence_entry)
return self.parse_node() return self.parse_node()
token = self.get_token() token = self.get_token()
event = SequenceEndEvent(token.start_mark, token.end_mark) event = events.SequenceEndEvent(token.start_mark, token.end_mark)
self.state = self.states.pop() self.state = self.states.pop()
self.marks.pop() self.marks.pop()
return event return event
@ -181,7 +182,7 @@ class Parser:
def parse_flow_sequence_entry_mapping_end(self): def parse_flow_sequence_entry_mapping_end(self):
self.state = self.parse_flow_sequence_entry self.state = self.parse_flow_sequence_entry
token = self.peek_token() token = self.peek_token()
return MappingEndEvent(token.start_mark, token.start_mark) return events.MappingEndEvent(token.start_mark, token.start_mark)
def parse_flow_mapping_first_key(self): def parse_flow_mapping_first_key(self):
token = self.get_token() token = self.get_token()
@ -189,11 +190,11 @@ class Parser:
return self.parse_flow_mapping_key(first=True) return self.parse_flow_mapping_key(first=True)
def parse_flow_mapping_key(self, first=False): def parse_flow_mapping_key(self, first=False):
if not self.check_token(FlowMappingEndToken): if not self.check_token(tokens.FlowMappingEndToken):
if not first: if not first:
if self.check_token(FlowEntryToken): if self.check_token(tokens.FlowEntryToken):
self.get_token() self.get_token()
if self.check_token(FlowMappingEndToken): if self.check_token(tokens.FlowMappingEndToken):
token = self.peek_token() token = self.peek_token()
self.echoerr( self.echoerr(
"While parsing a flow mapping", self.marks[-1], "While parsing a flow mapping", self.marks[-1],
@ -205,9 +206,9 @@ class Parser:
"while parsing a flow mapping", self.marks[-1], "while parsing a flow mapping", self.marks[-1],
("expected ',' or '}', but got %r" % token.id), token.start_mark ("expected ',' or '}', but got %r" % token.id), token.start_mark
) )
if self.check_token(KeyToken): if self.check_token(tokens.KeyToken):
token = self.get_token() token = self.get_token()
if not self.check_token(ValueToken, FlowEntryToken, FlowMappingEndToken): if not self.check_token(tokens.ValueToken, tokens.FlowEntryToken, tokens.FlowMappingEndToken):
self.states.append(self.parse_flow_mapping_value) self.states.append(self.parse_flow_mapping_value)
return self.parse_node() return self.parse_node()
else: else:
@ -216,12 +217,12 @@ class Parser:
"while parsing a flow mapping", self.marks[-1], "while parsing a flow mapping", self.marks[-1],
("expected value, but got %r" % token.id), token.start_mark ("expected value, but got %r" % token.id), token.start_mark
) )
elif not self.check_token(FlowMappingEndToken): elif not self.check_token(tokens.FlowMappingEndToken):
token = self.peek_token() token = self.peek_token()
expect_key = self.check_token(ValueToken, FlowEntryToken) expect_key = self.check_token(tokens.ValueToken, tokens.FlowEntryToken)
if not expect_key: if not expect_key:
self.get_token() self.get_token()
expect_key = self.check_token(ValueToken) expect_key = self.check_token(tokens.ValueToken)
if expect_key: if expect_key:
raise ParserError( raise ParserError(
@ -235,15 +236,15 @@ class Parser:
("expected ':', but got %r" % token.id), token.start_mark ("expected ':', but got %r" % token.id), token.start_mark
) )
token = self.get_token() token = self.get_token()
event = MappingEndEvent(token.start_mark, token.end_mark) event = events.MappingEndEvent(token.start_mark, token.end_mark)
self.state = self.states.pop() self.state = self.states.pop()
self.marks.pop() self.marks.pop()
return event return event
def parse_flow_mapping_value(self): def parse_flow_mapping_value(self):
if self.check_token(ValueToken): if self.check_token(tokens.ValueToken):
token = self.get_token() token = self.get_token()
if not self.check_token(FlowEntryToken, FlowMappingEndToken): if not self.check_token(tokens.FlowEntryToken, tokens.FlowMappingEndToken):
self.states.append(self.parse_flow_mapping_key) self.states.append(self.parse_flow_mapping_key)
return self.parse_node() return self.parse_node()

View File

@ -1,16 +1,14 @@
# This module contains abstractions for the input stream. You don't have to # vim:fileencoding=utf-8:noet
# looks further, there are no pretty code. from __future__ import (unicode_literals, division, absolute_import, print_function)
__all__ = ['Reader', 'ReaderError']
from .error import MarkedError, Mark, NON_PRINTABLE
import codecs import codecs
try: from powerline.lint.markedjson.error import MarkedError, Mark, NON_PRINTABLE
from __builtin__ import unicode from powerline.lib.unicode import unicode
except ImportError:
unicode = str # NOQA
# This module contains abstractions for the input stream. You don't have to
# looks further, there are no pretty code.
class ReaderError(MarkedError): class ReaderError(MarkedError):

View File

@ -1,10 +1,11 @@
__all__ = ['BaseResolver', 'Resolver'] # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from .error import MarkedError
from .nodes import * # NOQA
import re import re
from powerline.lint.markedjson.error import MarkedError
from powerline.lint.markedjson import nodes
class ResolverError(MarkedError): class ResolverError(MarkedError):
pass pass
@ -73,7 +74,7 @@ class BaseResolver:
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) and index_check == current_index.value): if not (isinstance(current_index, nodes.ScalarNode) and index_check == current_index.value):
return return
elif isinstance(index_check, int) and not isinstance(index_check, bool): elif isinstance(index_check, int) and not isinstance(index_check, bool):
if index_check != current_index: if index_check != current_index:
@ -81,7 +82,7 @@ class BaseResolver:
return True return True
def resolve(self, kind, value, implicit, mark=None): def resolve(self, kind, value, implicit, mark=None):
if kind is ScalarNode and implicit[0]: if kind is nodes.ScalarNode and implicit[0]:
if value == '': if value == '':
resolvers = self.yaml_implicit_resolvers.get('', []) resolvers = self.yaml_implicit_resolvers.get('', [])
else: else:
@ -97,11 +98,11 @@ class BaseResolver:
mark mark
) )
return self.DEFAULT_SCALAR_TAG return self.DEFAULT_SCALAR_TAG
if kind is ScalarNode: if kind is nodes.ScalarNode:
return self.DEFAULT_SCALAR_TAG return self.DEFAULT_SCALAR_TAG
elif kind is SequenceNode: elif kind is nodes.SequenceNode:
return self.DEFAULT_SEQUENCE_TAG return self.DEFAULT_SEQUENCE_TAG
elif kind is MappingNode: elif kind is nodes.MappingNode:
return self.DEFAULT_MAPPING_TAG return self.DEFAULT_MAPPING_TAG
@ -110,21 +111,21 @@ class Resolver(BaseResolver):
Resolver.add_implicit_resolver( Resolver.add_implicit_resolver(
'tag:yaml.org,2002:bool', 'tag:yaml.org,2002:bool',
re.compile(r'''^(?:true|false)$''', re.X), re.compile(r'''^(?:true|false)$''', re.X),
list('yYnNtTfFoO')) list('yYnNtTfFoO'))
Resolver.add_implicit_resolver( Resolver.add_implicit_resolver(
'tag:yaml.org,2002:float', 'tag:yaml.org,2002:float',
re.compile(r'^-?(?:0|[1-9]\d*)(?=[.eE])(?:\.\d+)?(?:[eE][-+]?\d+)?$', re.X), re.compile(r'^-?(?:0|[1-9]\d*)(?=[.eE])(?:\.\d+)?(?:[eE][-+]?\d+)?$', re.X),
list('-0123456789')) list('-0123456789'))
Resolver.add_implicit_resolver( Resolver.add_implicit_resolver(
'tag:yaml.org,2002:int', 'tag:yaml.org,2002:int',
re.compile(r'^(?:0|-?[1-9]\d*)$', re.X), re.compile(r'^(?:0|-?[1-9]\d*)$', re.X),
list('-0123456789')) list('-0123456789'))
Resolver.add_implicit_resolver( Resolver.add_implicit_resolver(
'tag:yaml.org,2002:null', 'tag:yaml.org,2002:null',
re.compile(r'^null$', re.X), re.compile(r'^null$', re.X),
['n']) ['n'])

View File

@ -1,3 +1,11 @@
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.lint.markedjson.error import MarkedError
from powerline.lint.markedjson import tokens
from powerline.lib.unicode import unicode
# Scanner produces tokens of the following types: # Scanner produces tokens of the following types:
# STREAM-START # STREAM-START
# STREAM-END # STREAM-END
@ -14,22 +22,11 @@
# #
# Read comments in the Scanner code for more details. # Read comments in the Scanner code for more details.
__all__ = ['Scanner', 'ScannerError']
from .error import MarkedError
from .tokens import * # NOQA
class ScannerError(MarkedError): class ScannerError(MarkedError):
pass pass
try:
from __builtin__ import unicode
except ImportError:
unicode = str # NOQA
class SimpleKey: class SimpleKey:
# See below simple keys treatment. # See below simple keys treatment.
def __init__(self, token_number, index, line, column, mark): def __init__(self, token_number, index, line, column, mark):
@ -241,8 +238,7 @@ class Scanner:
mark = self.get_mark() mark = self.get_mark()
# Add STREAM-START. # Add STREAM-START.
self.tokens.append(StreamStartToken(mark, mark, self.tokens.append(tokens.StreamStartToken(mark, mark, encoding=self.encoding))
encoding=self.encoding))
def fetch_stream_end(self): def fetch_stream_end(self):
# Reset simple keys. # Reset simple keys.
@ -254,19 +250,18 @@ class Scanner:
mark = self.get_mark() mark = self.get_mark()
# Add STREAM-END. # Add STREAM-END.
self.tokens.append(StreamEndToken(mark, mark)) self.tokens.append(tokens.StreamEndToken(mark, mark))
# The steam is finished. # The steam is finished.
self.done = True self.done = True
def fetch_flow_sequence_start(self): def fetch_flow_sequence_start(self):
self.fetch_flow_collection_start(FlowSequenceStartToken) self.fetch_flow_collection_start(tokens.FlowSequenceStartToken)
def fetch_flow_mapping_start(self): def fetch_flow_mapping_start(self):
self.fetch_flow_collection_start(FlowMappingStartToken) self.fetch_flow_collection_start(tokens.FlowMappingStartToken)
def fetch_flow_collection_start(self, TokenClass): def fetch_flow_collection_start(self, TokenClass):
# '[' and '{' may start a simple key. # '[' and '{' may start a simple key.
self.save_possible_simple_key() self.save_possible_simple_key()
@ -283,13 +278,12 @@ class Scanner:
self.tokens.append(TokenClass(start_mark, end_mark)) self.tokens.append(TokenClass(start_mark, end_mark))
def fetch_flow_sequence_end(self): def fetch_flow_sequence_end(self):
self.fetch_flow_collection_end(FlowSequenceEndToken) self.fetch_flow_collection_end(tokens.FlowSequenceEndToken)
def fetch_flow_mapping_end(self): def fetch_flow_mapping_end(self):
self.fetch_flow_collection_end(FlowMappingEndToken) self.fetch_flow_collection_end(tokens.FlowMappingEndToken)
def fetch_flow_collection_end(self, TokenClass): def fetch_flow_collection_end(self, TokenClass):
# Reset possible simple key on the current level. # Reset possible simple key on the current level.
self.remove_possible_simple_key() self.remove_possible_simple_key()
@ -312,7 +306,7 @@ class Scanner:
# Add KEY. # Add KEY.
key = self.possible_simple_keys[self.flow_level] key = self.possible_simple_keys[self.flow_level]
del self.possible_simple_keys[self.flow_level] del self.possible_simple_keys[self.flow_level]
self.tokens.insert(key.token_number - self.tokens_taken, KeyToken(key.mark, key.mark)) self.tokens.insert(key.token_number - self.tokens_taken, tokens.KeyToken(key.mark, key.mark))
# There cannot be two simple keys one after another. # There cannot be two simple keys one after another.
self.allow_simple_key = False self.allow_simple_key = False
@ -321,10 +315,9 @@ class Scanner:
start_mark = self.get_mark() start_mark = self.get_mark()
self.forward() self.forward()
end_mark = self.get_mark() end_mark = self.get_mark()
self.tokens.append(ValueToken(start_mark, end_mark)) self.tokens.append(tokens.ValueToken(start_mark, end_mark))
def fetch_flow_entry(self): def fetch_flow_entry(self):
# Simple keys are allowed after ','. # Simple keys are allowed after ','.
self.allow_simple_key = True self.allow_simple_key = True
@ -335,7 +328,7 @@ class Scanner:
start_mark = self.get_mark() start_mark = self.get_mark()
self.forward() self.forward()
end_mark = self.get_mark() end_mark = self.get_mark()
self.tokens.append(FlowEntryToken(start_mark, end_mark)) self.tokens.append(tokens.FlowEntryToken(start_mark, end_mark))
def fetch_double(self): def fetch_double(self):
# A flow scalar could be a simple key. # A flow scalar could be a simple key.
@ -385,7 +378,7 @@ class Scanner:
chunks.extend(self.scan_flow_scalar_non_spaces(start_mark)) chunks.extend(self.scan_flow_scalar_non_spaces(start_mark))
self.forward() self.forward()
end_mark = self.get_mark() end_mark = self.get_mark()
return ScalarToken(unicode().join(chunks), False, start_mark, end_mark, '"') return tokens.ScalarToken(unicode().join(chunks), False, start_mark, end_mark, '"')
ESCAPE_REPLACEMENTS = { ESCAPE_REPLACEMENTS = {
'b': '\x08', 'b': '\x08',
@ -480,4 +473,4 @@ class Scanner:
chunks.append(self.prefix(length)) chunks.append(self.prefix(length))
self.forward(length) self.forward(length)
end_mark = self.get_mark() end_mark = self.get_mark()
return ScalarToken(''.join(chunks), True, start_mark, end_mark) return tokens.ScalarToken(''.join(chunks), True, start_mark, end_mark)

View File

@ -1,3 +1,7 @@
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
class Token(object): class Token(object):
def __init__(self, start_mark, end_mark): def __init__(self, start_mark, end_mark):
self.start_mark = start_mark self.start_mark = start_mark

View File

@ -1,14 +1,13 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import unicode_literals, absolute_import, division from powerline.theme import requires_segment_info
from powerline.bindings.vim import (current_tabpage, list_tabpages, vim_getbufoption)
try: try:
import vim import vim
except ImportError: except ImportError:
vim = {} # NOQA vim = {}
from powerline.theme import requires_segment_info
from powerline.bindings.vim import (current_tabpage, list_tabpages, vim_getbufoption)
def tabpage_updated_segment_info(segment_info, tabpage, mode): def tabpage_updated_segment_info(segment_info, tabpage, mode):

View File

@ -1,2 +1,6 @@
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from pkgutil import extend_path from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) __path__ = extend_path(__path__, __name__)

View File

@ -1,8 +1,8 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import
import os import os
from powerline.bindings.vim import vim_getbufoption from powerline.bindings.vim import vim_getbufoption

View File

@ -1,2 +1,6 @@
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from pkgutil import extend_path from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) __path__ = extend_path(__path__, __name__)

View File

@ -1,22 +1,28 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os
try: try:
import vim import vim
except ImportError:
vim.command('''function! Powerline_plugin_ctrlp_main(...) vim = object()
else:
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('''
except ImportError: let g:ctrlp_status_func = {'main': 'Powerline_plugin_ctrlp_main', 'prog': 'Powerline_plugin_ctrlp_prog'}
vim = object() # NOQA ''')
def ctrlp(matcher_info): def ctrlp(matcher_info):

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os
import re import re

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os
@ -6,16 +7,10 @@ from unicodedata import east_asian_width, combining
from itertools import chain from itertools import chain
from powerline.theme import Theme from powerline.theme import Theme
from powerline.lib.unicode import unichr
try:
NBSP = unicode(' ', 'utf-8')
except NameError:
NBSP = ' '
try: NBSP = ' '
from __builtin__ import unichr as chr
except ImportError:
pass
def construct_returned_value(rendered_highlighted, segments, width, output_raw, output_width): def construct_returned_value(rendered_highlighted, segments, width, output_raw, output_width):
@ -80,7 +75,7 @@ class Renderer(object):
See documentation of ``unicode.translate`` for details. See documentation of ``unicode.translate`` for details.
''' '''
np_character_translations = dict(((i, '^' + chr(i + 0x40)) for i in range(0x20))) np_character_translations = dict(((i, '^' + unichr(i + 0x40)) for i in range(0x20)))
'''Non-printable character translations '''Non-printable character translations
These are used to transform characters in range 0x000x1F into ``^@``, These are used to transform characters in range 0x000x1F into ``^@``,

View File

@ -1,7 +1,9 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import json
from powerline.renderer import Renderer from powerline.renderer import Renderer
import json
class I3barRenderer(Renderer): class I3barRenderer(Renderer):

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.renderers.shell import ShellRenderer from powerline.renderers.shell import ShellRenderer
from powerline.theme import Theme from powerline.theme import Theme

View File

@ -1,10 +1,11 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from xml.sax.saxutils import escape as _escape
from powerline.renderer import Renderer from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from xml.sax.saxutils import escape as _escape
class PangoMarkupRenderer(Renderer): class PangoMarkupRenderer(Renderer):
'''Powerline Pango markup segment renderer.''' '''Powerline Pango markup segment renderer.'''

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals, division, print_function
from powerline.renderer import Renderer from powerline.renderer import Renderer
from powerline.theme import Theme from powerline.theme import Theme

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals
from powerline.renderers.shell import ShellRenderer from powerline.renderers.shell import ShellRenderer

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals
from powerline.renderers.shell import ShellRenderer from powerline.renderers.shell import ShellRenderer

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals
from powerline.renderers.shell.zsh import ZshPromptRenderer from powerline.renderers.shell.zsh import ZshPromptRenderer

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals
from powerline.renderers.shell import ShellRenderer from powerline.renderers.shell import ShellRenderer

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals
from powerline.renderer import Renderer from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE

View File

@ -1,20 +1,15 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import, unicode_literals import sys
import vim
from powerline.bindings.vim import vim_get_func, vim_getoption, environ, current_tabpage from powerline.bindings.vim import vim_get_func, vim_getoption, environ, current_tabpage
from powerline.renderer import Renderer from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from powerline.theme import Theme from powerline.theme import Theme
from powerline.lib.unicode import unichr
import vim
import sys
try:
from __builtin__ import unichr as chr
except ImportError:
pass
vim_mode = vim_get_func('mode', rettype=str) vim_mode = vim_get_func('mode', rettype=str)
@ -23,8 +18,8 @@ if int(vim.eval('v:version')) >= 702:
vim_mode = lambda: _vim_mode(1) vim_mode = lambda: _vim_mode(1)
mode_translations = { mode_translations = {
chr(ord('V') - 0x40): '^V', unichr(ord('V') - 0x40): '^V',
chr(ord('S') - 0x40): '^S', unichr(ord('S') - 0x40): '^S',
} }
@ -81,7 +76,7 @@ class VimRenderer(Renderer):
# renderer # renderer
return vim.strwidth(string.encode('utf-8')) return vim.strwidth(string.encode('utf-8'))
else: else:
@staticmethod # NOQA @staticmethod
def strwidth(string): def strwidth(string):
return vim.strwidth(string) return vim.strwidth(string)

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import absolute_import, unicode_literals, division, print_function from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.lib.watcher import create_file_watcher from powerline.lib.watcher import create_file_watcher

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import absolute_import from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys
@ -26,7 +26,7 @@ class Segment(object):
def argspecobjs(self): def argspecobjs(self):
yield '__call__', self.__call__ yield '__call__', self.__call__
else: else:
def argspecobjs(self): # NOQA def argspecobjs(self):
yield '__call__', self yield '__call__', self
argspecobjs.__doc__ = ( argspecobjs.__doc__ = (

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import unicode_literals, absolute_import, division
import os import os
import sys import sys
@ -9,6 +8,7 @@ import socket
from datetime import datetime from datetime import datetime
from multiprocessing import cpu_count as _cpu_count from multiprocessing import cpu_count as _cpu_count
from collections import namedtuple
from powerline.lib import add_divider_highlight_group from powerline.lib import add_divider_highlight_group
from powerline.lib.shell import asrun, run_cmd from powerline.lib.shell import asrun, run_cmd
@ -20,7 +20,6 @@ from powerline.lib.humanize_bytes import humanize_bytes
from powerline.lib.unicode import u from powerline.lib.unicode import u
from powerline.theme import requires_segment_info, requires_filesystem_watcher from powerline.theme import requires_segment_info, requires_filesystem_watcher
from powerline.segments import Segment, with_docstring from powerline.segments import Segment, with_docstring
from collections import namedtuple
cpu_count = None cpu_count = None
@ -676,23 +675,23 @@ try:
'highlight_group': ['cpu_load_percent_gradient', 'cpu_load_percent'], 'highlight_group': ['cpu_load_percent_gradient', 'cpu_load_percent'],
}] }]
except ImportError: except ImportError:
def _get_bytes(interface): # NOQA def _get_bytes(interface):
with open('/sys/class/net/{interface}/statistics/rx_bytes'.format(interface=interface), 'rb') as file_obj: with open('/sys/class/net/{interface}/statistics/rx_bytes'.format(interface=interface), 'rb') as file_obj:
rx = int(file_obj.read()) rx = int(file_obj.read())
with open('/sys/class/net/{interface}/statistics/tx_bytes'.format(interface=interface), 'rb') as file_obj: with open('/sys/class/net/{interface}/statistics/tx_bytes'.format(interface=interface), 'rb') as file_obj:
tx = int(file_obj.read()) tx = int(file_obj.read())
return (rx, tx) return (rx, tx)
def _get_interfaces(): # NOQA def _get_interfaces():
for interface in os.listdir('/sys/class/net'): for interface in os.listdir('/sys/class/net'):
x = _get_bytes(interface) x = _get_bytes(interface)
if x is not None: if x is not None:
yield interface, x[0], x[1] yield interface, x[0], x[1]
def _get_user(segment_info): # NOQA def _get_user(segment_info):
return segment_info['environ'].get('USER', None) return segment_info['environ'].get('USER', None)
class CPULoadPercentSegment(ThreadedSegment): # NOQA class CPULoadPercentSegment(ThreadedSegment):
interval = 1 interval = 1
@staticmethod @staticmethod
@ -764,12 +763,12 @@ if os.path.exists('/proc/uptime'):
elif 'psutil' in globals(): elif 'psutil' in globals():
from time import time from time import time
def _get_uptime(): # NOQA def _get_uptime():
# psutil.BOOT_TIME is not subject to clock adjustments, but time() is. # psutil.BOOT_TIME is not subject to clock adjustments, but time() is.
# Thus it is a fallback to /proc/uptime reading and not the reverse. # Thus it is a fallback to /proc/uptime reading and not the reverse.
return int(time() - psutil.BOOT_TIME) return int(time() - psutil.BOOT_TIME)
else: else:
def _get_uptime(): # NOQA def _get_uptime():
raise NotImplementedError raise NotImplementedError
@ -1199,14 +1198,14 @@ class NowPlayingSegment(Segment):
} }
try: try:
__import__('dbus') # NOQA __import__('dbus')
except ImportError: except ImportError:
if sys.platform.startswith('darwin'): if sys.platform.startswith('darwin'):
player_spotify = player_spotify_apple_script player_spotify = player_spotify_apple_script
else: else:
player_spotify = player_spotify_dbus # NOQA player_spotify = player_spotify_dbus
else: else:
player_spotify = player_spotify_dbus # NOQA player_spotify = player_spotify_dbus
def player_rhythmbox(self, pl): def player_rhythmbox(self, pl):
now_playing = run_cmd(pl, ['rhythmbox-client', '--no-start', '--no-present', '--print-playing-format', '%at\n%aa\n%tt\n%te\n%td']) now_playing = run_cmd(pl, ['rhythmbox-client', '--no-start', '--no-present', '--print-playing-format', '%at\n%aa\n%tt\n%te\n%td'])

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import i3 import i3

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.theme import requires_segment_info from powerline.theme import requires_segment_info

View File

@ -1,4 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.theme import requires_segment_info from powerline.theme import requires_segment_info
from powerline.segments import with_docstring from powerline.segments import with_docstring

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import absolute_import, unicode_literals, division, print_function from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.bindings.tmux import get_tmux_output from powerline.bindings.tmux import get_tmux_output

View File

@ -1,16 +1,15 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import unicode_literals, absolute_import, division
import os import os
import re import re
from collections import defaultdict
try: try:
import vim import vim
except ImportError: except ImportError:
vim = {} # NOQA vim = {}
from collections import defaultdict
from powerline.bindings.vim import (vim_get_func, getbufvar, vim_getbufoption, from powerline.bindings.vim import (vim_get_func, getbufvar, vim_getbufoption,
buffer_name, vim_getwinvar, buffer_name, vim_getwinvar,

View File

@ -1,2 +1,6 @@
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from pkgutil import extend_path from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) __path__ = extend_path(__path__, __name__)

View File

@ -1,9 +1,10 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
try: try:
import vim import vim
except ImportError: except ImportError:
vim = object() # NOQA vim = object()
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
@ -33,7 +34,7 @@ def ctrlp_stl_left_main(pl, focus, byfname, regex, prev, item, next, marked):
segments.append({ segments.append({
'contents': 'regex', 'contents': 'regex',
'highlight_group': ['ctrlp.regex', 'background'], 'highlight_group': ['ctrlp.regex', 'background'],
}) })
segments += [ segments += [
{ {
@ -62,7 +63,7 @@ def ctrlp_stl_left_main(pl, focus, byfname, regex, prev, item, next, marked):
'contents': marked, 'contents': marked,
'highlight_group': ['ctrlp.marked', 'background'], 'highlight_group': ['ctrlp.marked', 'background'],
'draw_inner_divider': True, 'draw_inner_divider': True,
}) })
return segments return segments

View File

@ -1,9 +1,10 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
try: try:
import vim import vim
except ImportError: except ImportError:
vim = object() # NOQA vim = object()
from powerline.bindings.vim import bufvar_exists from powerline.bindings.vim import bufvar_exists
from powerline.segments.vim import window_cached from powerline.segments.vim import window_cached

View File

@ -1,9 +1,10 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
try: try:
import vim import vim
except ImportError: except ImportError:
vim = object() # NOQA vim = object()
from powerline.segments.vim import window_cached from powerline.segments.vim import window_cached

View File

@ -1,9 +1,10 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
try: try:
import vim import vim
except ImportError: except ImportError:
vim = object() # NOQA vim = object()
from powerline.segments.vim import window_cached from powerline.segments.vim import window_cached

View File

@ -1,4 +1,6 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
# WARNING: using unicode_literals causes errors in argparse
from __future__ import (division, absolute_import, print_function)
from powerline import Powerline from powerline import Powerline
from powerline.lib import mergedicts, parsedotval from powerline.lib import mergedicts, parsedotval

View File

@ -1,9 +1,10 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import division from __future__ import (unicode_literals, division, absolute_import, print_function)
import itertools
from powerline.segment import gen_segment_getter, process_segment from powerline.segment import gen_segment_getter, process_segment
from powerline.lib.unicode import u from powerline.lib.unicode import u
import itertools
def requires_segment_info(func): def requires_segment_info(func):

View File

@ -1,6 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from __future__ import absolute_import
import sys import sys
@ -215,7 +214,7 @@ class VimPowerline(Powerline):
_vim_getwinvar = staticmethod(vim_get_func('getwinvar')) _vim_getwinvar = staticmethod(vim_get_func('getwinvar'))
_vim_setwinvar = staticmethod(vim_get_func('setwinvar')) _vim_setwinvar = staticmethod(vim_get_func('setwinvar'))
def win_idx(self, window_id): # NOQA def win_idx(self, window_id):
r = None r = None
for winnr, window in zip(count(1), vim.windows): for winnr, window in zip(count(1), vim.windows):
curwindow_id = self._vim_getwinvar(winnr, 'powerline_window_id') curwindow_id = self._vim_getwinvar(winnr, 'powerline_window_id')

View File

@ -1,7 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
'''Script used to obtain powerline configuration''' '''Script used to obtain powerline configuration'''
from __future__ import (unicode_literals, division, absolute_import, print_function)
import argparse import argparse
try: try:
@ -10,7 +13,7 @@ except ImportError:
import sys import sys
import os import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))) sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__)))))
import powerline.bindings.config as config # NOQA import powerline.bindings.config as config
TMUX_ACTIONS = { TMUX_ACTIONS = {

View File

@ -6,6 +6,7 @@ import socket
import os import os
import errno import errno
import sys import sys
from argparse import ArgumentParser from argparse import ArgumentParser
from select import select from select import select
from signal import signal, SIGTERM from signal import signal, SIGTERM
@ -246,7 +247,7 @@ def daemonize(stdin=os.devnull, stdout=os.devnull, stderr=os.devnull):
# exit first parent # exit first parent
sys.exit(0) sys.exit(0)
except OSError as e: except OSError as e:
print ("fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1) sys.exit(1)
# decouple from parent environment # decouple from parent environment
@ -261,7 +262,7 @@ def daemonize(stdin=os.devnull, stdout=os.devnull, stderr=os.devnull):
# exit from second parent # exit from second parent
sys.exit(0) sys.exit(0)
except OSError as e: except OSError as e:
print ("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1) sys.exit(1)
# Redirect standard file descriptors. # Redirect standard file descriptors.
@ -399,16 +400,18 @@ def main():
# Create a locked pid file containing the daemon's PID # Create a locked pid file containing the daemon's PID
if lockpidfile() is None: if lockpidfile() is None:
if not args.quiet: if not args.quiet:
print ('The daemon is already running. Use %s -k to kill it.' % os.path.basename(sys.argv[0]), sys.stderr.write(
file=sys.stderr) 'The daemon is already running. Use %s -k to kill it.\n' % (
os.path.basename(sys.argv[0])))
raise SystemExit(1) raise SystemExit(1)
# Bind to address or bail if we cannot bind # Bind to address or bail if we cannot bind
sock = check_existing() sock = check_existing()
if sock is None: if sock is None:
if not args.quiet: if not args.quiet:
print ('The daemon is already running. Use %s -k to kill it.' % os.path.basename(sys.argv[0]), sys.stderr.write(
file=sys.stderr) 'The daemon is already running. Use %s -k to kill it.\n' % (
os.path.basename(sys.argv[0])))
raise SystemExit(1) raise SystemExit(1)
if args.foreground: if args.foreground:

View File

@ -1,10 +1,15 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
'''Powerline configuration checker.''' '''Powerline configuration checker.'''
from __future__ import (unicode_literals, division, absolute_import, print_function)
import argparse import argparse
from powerline.lint import check
import sys import sys
from powerline.lint import check
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-p', '--config_path', action='append', metavar='PATH') parser.add_argument('-p', '--config_path', action='append', metavar='PATH')

View File

@ -1,6 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
'''Powerline prompt and statusline script.''' '''Powerline prompt and statusline script.'''
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys
import os import os
@ -10,7 +14,7 @@ try:
from powerline.shell import ShellPowerline, get_argparser, finish_args, write_output from powerline.shell import ShellPowerline, get_argparser, finish_args, write_output
except ImportError: except ImportError:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))) 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 # NOQA from powerline.shell import ShellPowerline, get_argparser, finish_args, write_output
if sys.version_info < (3,): if sys.version_info < (3,):

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import unicode_literals from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os
import sys import sys
import subprocess import subprocess
@ -8,6 +9,7 @@ import logging
from setuptools import setup, find_packages from setuptools import setup, find_packages
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
try: try:
README = open(os.path.join(CURRENT_DIR, 'README.rst'), 'rb').read().decode('utf-8') README = open(os.path.join(CURRENT_DIR, 'README.rst'), 'rb').read().decode('utf-8')

View File

@ -1,5 +1,8 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys import sys
if sys.version_info < (2, 7): if sys.version_info < (2, 7):
from unittest2 import TestCase, main # NOQA from unittest2 import TestCase, main # NOQA
from unittest2.case import SkipTest # NOQA from unittest2.case import SkipTest # NOQA

View File

@ -1,4 +1,6 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import imp import imp
import sys import sys

View File

@ -1,13 +1,18 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import os
from threading import Lock from threading import Lock
from powerline.renderer import Renderer
from powerline.lib.config import ConfigLoader
from powerline import Powerline
from tests.lib import Args, replace_attr
from copy import deepcopy from copy import deepcopy
from time import sleep from time import sleep
from functools import wraps from functools import wraps
import os
from powerline.renderer import Renderer
from powerline.lib.config import ConfigLoader
from powerline import Powerline
from tests.lib import Args, replace_attr
class TestHelpers(object): class TestHelpers(object):

View File

@ -1,5 +1,5 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import unicode_literals, absolute_import, division from __future__ import (unicode_literals, division, absolute_import, print_function)
import os import os
import json import json

View File

@ -1,5 +1,4 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function) from __future__ import (unicode_literals, division, absolute_import, print_function)

View File

@ -1,4 +1,6 @@
# vim:fileencoding=utf-8:noet # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from tests import vim from tests import vim

View File

@ -2,15 +2,19 @@
'''Tests for shell.py parser''' '''Tests for shell.py parser'''
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.shell import get_argparser, finish_args
from tests import TestCase
from tests.lib import replace_attr
import sys import sys
if sys.version_info < (3,): if sys.version_info < (3,):
from io import BytesIO as StrIO from io import BytesIO as StrIO
else: else:
from io import StringIO as StrIO # NOQA from io import StringIO as StrIO
from powerline.shell import get_argparser, finish_args
from tests import TestCase
from tests.lib import replace_attr
class TestParser(TestCase): class TestParser(TestCase):

Some files were not shown because too many files have changed in this diff Show More