Completed
Pull Request — master (#178)
by Björn
21:44 queued 20:38
created

neovim.setup_logging()   A

Complexity

Conditions 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 11.2817
Metric Value
cc 4
dl 0
loc 19
ccs 3
cts 13
cp 0.2308
crap 11.2817
rs 9.2
1
"""Python client for Nvim.
2
3
Client library for talking with Nvim processes via it's msgpack-rpc API.
4
"""
5 6
import logging
6 6
import os
7 6
import sys
8
9 6
from .api import DecodeHook, Nvim, SessionHook
10 6
from .msgpack_rpc import (ErrorResponse, child_session, socket_session, stdio_session,
11
                          tcp_session)
12 6
from .plugin import (Host, autocmd, command, encoding, function, plugin,
13
                     rpc_export, shutdown_hook)
14
15
16 6
__all__ = ('tcp_session', 'socket_session', 'stdio_session', 'child_session',
17
           'start_host', 'autocmd', 'command', 'encoding', 'function',
18
           'plugin', 'rpc_export', 'Host', 'DecodeHook', 'Nvim',
19
           'SessionHook', 'shutdown_hook', 'attach', 'setup_logging',
20
           'ErrorResponse')
21
22
23 6
def start_host(session=None):
24
    """Promote the current process into python plugin host for Nvim.
25
26
    Start msgpack-rpc event loop for `session`, listening for Nvim requests
27
    and notifications. It registers Nvim commands for loading/unloading
28
    python plugins.
29
30
    The sys.stdout and sys.stderr streams are redirected to Nvim through
31
    `session`. That means print statements probably won't work as expected
32
    while this function doesn't return.
33
34
    This function is normally called at program startup and could have been
35
    defined as a separate executable. It is exposed as a library function for
36
    testing purposes only.
37
    """
38
    plugins = []
39
    for arg in sys.argv:
40
        _, ext = os.path.splitext(arg)
41
        if ext == '.py':
42
            plugins.append(arg)
43
        elif os.path.isdir(arg):
44
            init = os.path.join(arg, '__init__.py')
45
            if os.path.isfile(init):
46
                plugins.append(arg)
47
48
    # This is a special case to support the old workaround of
49
    # adding an empty .py file to make a package directory
50
    # visible, and it should be removed soon.
51
    for path in list(plugins):
52
        dup = path + ".py"
53
        if os.path.isdir(path) and dup in plugins:
54
            plugins.remove(dup)
55
56
    if not plugins:
57
        sys.exit('must specify at least one plugin as argument')
58
59
    setup_logging()
60
61
    if not session:
62
        session = stdio_session()
63
    host = Host(Nvim.from_session(session))
64
    host.start(plugins)
65
66
67 6
def attach(session_type, address=None, port=None, path=None, argv=None):
68
    """Provide a nicer interface to create python api sessions.
69
70
    Previous machinery to create python api sessions is still there. This only
71
    creates a facade function to make things easier for the most usual cases.
72
    Thus, instead of:
73
        from neovim import socket_session, Nvim
74
        session = tcp_session(address=<address>, port=<port>)
75
        nvim = Nvim.from_session(session)
76
    You can now do:
77
        from neovim import attach
78
        nvim = attach('tcp', address=<address>, port=<port>)
79
    And also:
80
        nvim = attach('socket', path=<path>)
81
        nvim = attach('child', argv=<argv>)
82
        nvim = attach('stdio')
83
    """
84 6
    session = (tcp_session(address, port) if session_type == 'tcp' else
85
               socket_session(path) if session_type == 'socket' else
86
               stdio_session() if session_type == 'stdio' else
87
               child_session(argv) if session_type == 'child' else
88
               None)
89
90 6
    if not session:
91
        raise Exception('Unknown session type "%s"' % session_type)
92
93 6
    return Nvim.from_session(session)
94
95
96 6
def setup_logging():
97
    """Setup logging according to environment variables."""
98 6
    logger = logging.getLogger(__name__)
99 6
    if 'NVIM_PYTHON_LOG_FILE' in os.environ:
100
        logfile = (os.environ['NVIM_PYTHON_LOG_FILE'].strip() +
101
                   '_' + str(os.getpid()))
102
        handler = logging.FileHandler(logfile, 'w')
103
        handler.formatter = logging.Formatter(
104
            '%(asctime)s [%(levelname)s @ '
105
            '%(filename)s:%(funcName)s:%(lineno)s] %(process)s - %(message)s')
106
        logging.root.addHandler(handler)
107
        level = logging.INFO
108
        if 'NVIM_PYTHON_LOG_LEVEL' in os.environ:
109
            l = getattr(logging,
110
                        os.environ['NVIM_PYTHON_LOG_LEVEL'].strip(),
111
                        level)
112
            if isinstance(l, int):
113
                level = l
114
        logger.setLevel(level)
115
116
117
# Required for python 2.6
118 6
class NullHandler(logging.Handler):
119 6
    def emit(self, record):
120 6
        pass
121
122
123 6
if not logging.root.handlers:
124
    logging.root.addHandler(NullHandler())
125