Skip to content

Commit d47dc3c

Browse files
authored
Format the whole repo with Black (#419)
1 parent 43104e9 commit d47dc3c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+2854
-2389
lines changed

.github/workflows/static.yml

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,15 @@ jobs:
3535
python-version: '3.8'
3636
architecture: 'x64'
3737
- run: python -m pip install --upgrade pip setuptools jsonschema
38-
- run: pip install -e .[pylint,pycodestyle,pyflakes]
38+
# If we don't install pycodestyle, pylint will throw an unused-argument error in pylsp/plugins/pycodestyle_lint.py:72
39+
# This error cannot be resolved by adding a pylint: disable=unused-argument comment ...
40+
- run: |
41+
pip install -e .[pylint,pycodestyle,pyflakes]
42+
pip install black
3943
- name: Pylint checks
4044
run: pylint pylsp test
41-
- name: Code style checks
42-
run: pycodestyle pylsp test
45+
- name: Code style checks with black
46+
run: black --check pylsp test
4347
- name: Pyflakes checks
4448
run: pyflakes pylsp test
4549
- name: Validate JSON schema

pylsp/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ def convert_version_info(version: str) -> (int, ..., str):
2222

2323
_version.VERSION_INFO = convert_version_info(__version__)
2424

25-
PYLSP = 'pylsp'
26-
IS_WIN = os.name == 'nt'
25+
PYLSP = "pylsp"
26+
IS_WIN = os.name == "nt"
2727

2828
hookspec = pluggy.HookspecMarker(PYLSP)
2929
hookimpl = pluggy.HookimplMarker(PYLSP)

pylsp/__main__.py

Lines changed: 36 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -12,58 +12,58 @@
1212
except Exception: # pylint: disable=broad-except
1313
import json
1414

15-
from .python_lsp import (PythonLSPServer, start_io_lang_server,
16-
start_tcp_lang_server, start_ws_lang_server)
15+
from .python_lsp import (
16+
PythonLSPServer,
17+
start_io_lang_server,
18+
start_tcp_lang_server,
19+
start_ws_lang_server,
20+
)
1721
from ._version import __version__
1822

1923
LOG_FORMAT = "%(asctime)s {0} - %(levelname)s - %(name)s - %(message)s".format(
20-
time.localtime().tm_zone)
24+
time.localtime().tm_zone
25+
)
2126

2227

2328
def add_arguments(parser):
2429
parser.description = "Python Language Server"
2530

2631
parser.add_argument(
27-
"--tcp", action="store_true",
28-
help="Use TCP server instead of stdio"
32+
"--tcp", action="store_true", help="Use TCP server instead of stdio"
2933
)
3034
parser.add_argument(
31-
"--ws", action="store_true",
32-
help="Use Web Sockets server instead of stdio"
35+
"--ws", action="store_true", help="Use Web Sockets server instead of stdio"
3336
)
37+
parser.add_argument("--host", default="127.0.0.1", help="Bind to this address")
38+
parser.add_argument("--port", type=int, default=2087, help="Bind to this port")
3439
parser.add_argument(
35-
"--host", default="127.0.0.1",
36-
help="Bind to this address"
37-
)
38-
parser.add_argument(
39-
"--port", type=int, default=2087,
40-
help="Bind to this port"
41-
)
42-
parser.add_argument(
43-
'--check-parent-process', action="store_true",
40+
"--check-parent-process",
41+
action="store_true",
4442
help="Check whether parent process is still alive using os.kill(ppid, 0) "
4543
"and auto shut down language server process when parent process is not alive."
46-
"Note that this may not work on a Windows machine."
44+
"Note that this may not work on a Windows machine.",
4745
)
4846

4947
log_group = parser.add_mutually_exclusive_group()
5048
log_group.add_argument(
51-
"--log-config",
52-
help="Path to a JSON file containing Python logging config."
49+
"--log-config", help="Path to a JSON file containing Python logging config."
5350
)
5451
log_group.add_argument(
5552
"--log-file",
5653
help="Redirect logs to the given file instead of writing to stderr."
57-
"Has no effect if used with --log-config."
54+
"Has no effect if used with --log-config.",
5855
)
5956

6057
parser.add_argument(
61-
'-v', '--verbose', action='count', default=0,
62-
help="Increase verbosity of log output, overrides log config file"
58+
"-v",
59+
"--verbose",
60+
action="count",
61+
default=0,
62+
help="Increase verbosity of log output, overrides log config file",
6363
)
6464

6565
parser.add_argument(
66-
'-V', '--version', action='version', version='%(prog)s v' + __version__
66+
"-V", "--version", action="version", version="%(prog)s v" + __version__
6767
)
6868

6969

@@ -74,15 +74,14 @@ def main():
7474
_configure_logger(args.verbose, args.log_config, args.log_file)
7575

7676
if args.tcp:
77-
start_tcp_lang_server(args.host, args.port, args.check_parent_process,
78-
PythonLSPServer)
77+
start_tcp_lang_server(
78+
args.host, args.port, args.check_parent_process, PythonLSPServer
79+
)
7980
elif args.ws:
80-
start_ws_lang_server(args.port, args.check_parent_process,
81-
PythonLSPServer)
81+
start_ws_lang_server(args.port, args.check_parent_process, PythonLSPServer)
8282
else:
8383
stdin, stdout = _binary_stdio()
84-
start_io_lang_server(stdin, stdout, args.check_parent_process,
85-
PythonLSPServer)
84+
start_io_lang_server(stdin, stdout, args.check_parent_process, PythonLSPServer)
8685

8786

8887
def _binary_stdio():
@@ -99,14 +98,18 @@ def _configure_logger(verbose=0, log_config=None, log_file=None):
9998
root_logger = logging.root
10099

101100
if log_config:
102-
with open(log_config, 'r', encoding='utf-8') as f:
101+
with open(log_config, "r", encoding="utf-8") as f:
103102
logging.config.dictConfig(json.load(f))
104103
else:
105104
formatter = logging.Formatter(LOG_FORMAT)
106105
if log_file:
107106
log_handler = logging.handlers.RotatingFileHandler(
108-
log_file, mode='a', maxBytes=50*1024*1024,
109-
backupCount=10, encoding=None, delay=0
107+
log_file,
108+
mode="a",
109+
maxBytes=50 * 1024 * 1024,
110+
backupCount=10,
111+
encoding=None,
112+
delay=0,
110113
)
111114
else:
112115
log_handler = logging.StreamHandler()
@@ -123,5 +126,5 @@ def _configure_logger(verbose=0, log_config=None, log_file=None):
123126
root_logger.setLevel(level)
124127

125128

126-
if __name__ == '__main__':
129+
if __name__ == "__main__":
127130
main()

pylsp/_utils.py

Lines changed: 37 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,15 @@
1717

1818
# Eol chars accepted by the LSP protocol
1919
# the ordering affects performance
20-
EOL_CHARS = ['\r\n', '\r', '\n']
20+
EOL_CHARS = ["\r\n", "\r", "\n"]
2121
EOL_REGEX = re.compile(f'({"|".join(EOL_CHARS)})')
2222

2323
log = logging.getLogger(__name__)
2424

2525

2626
def debounce(interval_s, keyed_by=None):
2727
"""Debounce calls to this function until interval_s seconds have passed."""
28+
2829
def wrapper(func):
2930
timers = {}
3031
lock = threading.Lock()
@@ -48,7 +49,9 @@ def run():
4849
timer = threading.Timer(interval_s, run)
4950
timers[key] = timer
5051
timer.start()
52+
5153
return debounced
54+
5255
return wrapper
5356

5457

@@ -78,7 +81,9 @@ def find_parents(root, path, names):
7881
# Search each of /a/b/c, /a/b, /a
7982
while dirs:
8083
search_dir = os.path.join(*dirs)
81-
existing = list(filter(os.path.exists, [os.path.join(search_dir, n) for n in names]))
84+
existing = list(
85+
filter(os.path.exists, [os.path.join(search_dir, n) for n in names])
86+
)
8287
if existing:
8388
return existing
8489
dirs.pop()
@@ -92,11 +97,11 @@ def path_to_dot_name(path):
9297
directory = os.path.dirname(path)
9398
module_name, _ = os.path.splitext(os.path.basename(path))
9499
full_name = [module_name]
95-
while os.path.exists(os.path.join(directory, '__init__.py')):
100+
while os.path.exists(os.path.join(directory, "__init__.py")):
96101
this_directory = os.path.basename(directory)
97102
directory = os.path.dirname(directory)
98103
full_name = [this_directory] + full_name
99-
return '.'.join(full_name)
104+
return ".".join(full_name)
100105

101106

102107
def match_uri_to_workspace(uri, workspaces):
@@ -128,6 +133,7 @@ def merge_dicts(dict_a, dict_b):
128133
129134
If override_nones is True, then
130135
"""
136+
131137
def _merge_dicts_(a, b):
132138
for key in set(a.keys()).union(b.keys()):
133139
if key in a and key in b:
@@ -143,15 +149,16 @@ def _merge_dicts_(a, b):
143149
yield (key, a[key])
144150
elif b[key] is not None:
145151
yield (key, b[key])
152+
146153
return dict(_merge_dicts_(dict_a, dict_b))
147154

148155

149156
def escape_plain_text(contents: str) -> str:
150157
"""
151158
Format plain text to display nicely in environments which do not respect whitespaces.
152159
"""
153-
contents = contents.replace('\t', '\u00A0' * 4)
154-
contents = contents.replace(' ', '\u00A0' * 2)
160+
contents = contents.replace("\t", "\u00A0" * 4)
161+
contents = contents.replace(" ", "\u00A0" * 2)
155162
return contents
156163

157164

@@ -160,17 +167,17 @@ def escape_markdown(contents: str) -> str:
160167
Format plain text to display nicely in Markdown environment.
161168
"""
162169
# escape markdown syntax
163-
contents = re.sub(r'([\\*_#[\]])', r'\\\1', contents)
170+
contents = re.sub(r"([\\*_#[\]])", r"\\\1", contents)
164171
# preserve white space characters
165172
contents = escape_plain_text(contents)
166173
return contents
167174

168175

169176
def wrap_signature(signature):
170-
return '```python\n' + signature + '\n```\n'
177+
return "```python\n" + signature + "\n```\n"
171178

172179

173-
SERVER_SUPPORTED_MARKUP_KINDS = {'markdown', 'plaintext'}
180+
SERVER_SUPPORTED_MARKUP_KINDS = {"markdown", "plaintext"}
174181

175182

176183
def choose_markup_kind(client_supported_markup_kinds: List[str]):
@@ -181,10 +188,12 @@ def choose_markup_kind(client_supported_markup_kinds: List[str]):
181188
for kind in client_supported_markup_kinds:
182189
if kind in SERVER_SUPPORTED_MARKUP_KINDS:
183190
return kind
184-
return 'markdown'
191+
return "markdown"
185192

186193

187-
def format_docstring(contents: str, markup_kind: str, signatures: Optional[List[str]] = None):
194+
def format_docstring(
195+
contents: str, markup_kind: str, signatures: Optional[List[str]] = None
196+
):
188197
"""Transform the provided docstring into a MarkupContent object.
189198
190199
If `markup_kind` is 'markdown' the docstring will get converted to
@@ -195,33 +204,24 @@ def format_docstring(contents: str, markup_kind: str, signatures: Optional[List[
195204
to the provided contents of the docstring if given.
196205
"""
197206
if not isinstance(contents, str):
198-
contents = ''
207+
contents = ""
199208

200-
if markup_kind == 'markdown':
209+
if markup_kind == "markdown":
201210
try:
202211
value = docstring_to_markdown.convert(contents)
203-
return {
204-
'kind': 'markdown',
205-
'value': value
206-
}
212+
return {"kind": "markdown", "value": value}
207213
except docstring_to_markdown.UnknownFormatError:
208214
# try to escape the Markdown syntax instead:
209215
value = escape_markdown(contents)
210216

211217
if signatures:
212-
value = wrap_signature('\n'.join(signatures)) + '\n\n' + value
218+
value = wrap_signature("\n".join(signatures)) + "\n\n" + value
213219

214-
return {
215-
'kind': 'markdown',
216-
'value': value
217-
}
220+
return {"kind": "markdown", "value": value}
218221
value = contents
219222
if signatures:
220-
value = '\n'.join(signatures) + '\n\n' + value
221-
return {
222-
'kind': 'plaintext',
223-
'value': escape_plain_text(value)
224-
}
223+
value = "\n".join(signatures) + "\n\n" + value
224+
return {"kind": "plaintext", "value": escape_plain_text(value)}
225225

226226

227227
def clip_column(column, lines, line_number):
@@ -230,7 +230,9 @@ def clip_column(column, lines, line_number):
230230
231231
https://microsoft.github.io/language-server-protocol/specification#position
232232
"""
233-
max_column = len(lines[line_number].rstrip('\r\n')) if len(lines) > line_number else 0
233+
max_column = (
234+
len(lines[line_number].rstrip("\r\n")) if len(lines) > line_number else 0
235+
)
234236
return min(column, max_column)
235237

236238

@@ -242,14 +244,16 @@ def position_to_jedi_linecolumn(document, position):
242244
"""
243245
code_position = {}
244246
if position:
245-
code_position = {'line': position['line'] + 1,
246-
'column': clip_column(position['character'],
247-
document.lines,
248-
position['line'])}
247+
code_position = {
248+
"line": position["line"] + 1,
249+
"column": clip_column(
250+
position["character"], document.lines, position["line"]
251+
),
252+
}
249253
return code_position
250254

251255

252-
if os.name == 'nt':
256+
if os.name == "nt":
253257
import ctypes
254258

255259
kernel32 = ctypes.windll.kernel32

0 commit comments

Comments
 (0)