1
+ import logging
1
2
from typing import Dict
2
3
3
4
import black
4
5
import toml
5
6
from pylsp import hookimpl
6
7
8
+ logger = logging .getLogger (__name__ )
9
+
7
10
8
11
@hookimpl (tryfirst = True )
9
12
def pylsp_format_document (document ):
@@ -34,16 +37,8 @@ def format_document(document, range=None):
34
37
35
38
try :
36
39
formatted_text = format_text (text = text , config = config )
37
- except (
38
- ValueError ,
40
+ except black .NothingChanged :
39
41
# raised when the file is already formatted correctly
40
- black .NothingChanged ,
41
- # raised when the file being formatted has an indentation error
42
- IndentationError ,
43
- # raised when black produces invalid Python code or formats the file
44
- # differently on the second pass
45
- AssertionError ,
46
- ):
47
42
return []
48
43
49
44
return [{"range" : range , "newText" : formatted_text }]
@@ -56,8 +51,21 @@ def format_text(*, text, config):
56
51
is_pyi = config ["pyi" ],
57
52
string_normalization = not config ["skip_string_normalization" ],
58
53
)
59
-
60
- return black .format_file_contents (text , fast = config ["fast" ], mode = mode )
54
+ try :
55
+ # will raise black.NothingChanged, we want to bubble that exception up
56
+ return black .format_file_contents (text , fast = config ["fast" ], mode = mode )
57
+ except (
58
+ # raised when the file has syntax errors
59
+ ValueError ,
60
+ # raised when the file being formatted has an indentation error
61
+ IndentationError ,
62
+ # raised when black produces invalid Python code or formats the file
63
+ # differently on the second pass
64
+ AssertionError ,
65
+ ) as e :
66
+ # errors will show on lsp stderr stream
67
+ logger .error ("Error formatting with black: %s" , e )
68
+ raise black .NothingChanged from e
61
69
62
70
63
71
def load_config (filename : str ) -> Dict :
@@ -74,11 +82,16 @@ def load_config(filename: str) -> Dict:
74
82
pyproject_filename = root / "pyproject.toml"
75
83
76
84
if not pyproject_filename .is_file ():
85
+ logger .info ("Using defaults: %r" , defaults )
77
86
return defaults
78
87
79
88
try :
80
89
pyproject_toml = toml .load (str (pyproject_filename ))
81
90
except (toml .TomlDecodeError , OSError ):
91
+ logger .warning (
92
+ "Error decoding pyproject.toml, using defaults: %r" ,
93
+ defaults ,
94
+ )
82
95
return defaults
83
96
84
97
file_config = pyproject_toml .get ("tool" , {}).get ("black" , {})
@@ -108,4 +121,6 @@ def load_config(filename: str) -> Dict:
108
121
109
122
config ["target_version" ] = target_version
110
123
124
+ logger .info ("Using config from %s: %r" , pyproject_filename , config )
125
+
111
126
return config
0 commit comments