1+ import logging
12import os
23from pathlib import Path
34from typing import Dict
67import toml
78from pylsp import hookimpl
89
10+ logger = logging .getLogger (__name__ )
11+
912GLOBAL_CONFIG : Path
1013if os .name == "nt" :
1114 GLOBAL_CONFIG = Path .home () / ".black"
@@ -44,16 +47,8 @@ def format_document(document, range=None):
4447
4548 try :
4649 formatted_text = format_text (text = text , config = config )
47- except (
48- ValueError ,
50+ except black .NothingChanged :
4951 # raised when the file is already formatted correctly
50- black .NothingChanged ,
51- # raised when the file being formatted has an indentation error
52- IndentationError ,
53- # raised when black produces invalid Python code or formats the file
54- # differently on the second pass
55- AssertionError ,
56- ):
5752 return []
5853
5954 return [{"range" : range , "newText" : formatted_text }]
@@ -66,8 +61,21 @@ def format_text(*, text, config):
6661 is_pyi = config ["pyi" ],
6762 string_normalization = not config ["skip_string_normalization" ],
6863 )
69-
70- return black .format_file_contents (text , fast = config ["fast" ], mode = mode )
64+ try :
65+ # will raise black.NothingChanged, we want to bubble that exception up
66+ return black .format_file_contents (text , fast = config ["fast" ], mode = mode )
67+ except (
68+ # raised when the file has syntax errors
69+ ValueError ,
70+ # raised when the file being formatted has an indentation error
71+ IndentationError ,
72+ # raised when black produces invalid Python code or formats the file
73+ # differently on the second pass
74+ AssertionError ,
75+ ) as e :
76+ # errors will show on lsp stderr stream
77+ logger .error ("Error formatting with black: %s" , e )
78+ raise black .NothingChanged from e
7179
7280
7381def load_config (filename : str ) -> Dict :
@@ -86,12 +94,18 @@ def load_config(filename: str) -> Dict:
8694 if not pyproject_filename .is_file ():
8795 if GLOBAL_CONFIG .exists ():
8896 pyproject_filename = GLOBAL_CONFIG
97+ logger .info ("Using global black config at %s" , pyproject_filename )
8998 else :
99+ logger .info ("Using defaults: %r" , defaults )
90100 return defaults
91101
92102 try :
93103 pyproject_toml = toml .load (str (pyproject_filename ))
94104 except (toml .TomlDecodeError , OSError ):
105+ logger .warning (
106+ "Error decoding pyproject.toml, using defaults: %r" ,
107+ defaults ,
108+ )
95109 return defaults
96110
97111 file_config = pyproject_toml .get ("tool" , {}).get ("black" , {})
@@ -121,4 +135,6 @@ def load_config(filename: str) -> Dict:
121135
122136 config ["target_version" ] = target_version
123137
138+ logger .info ("Using config from %s: %r" , pyproject_filename , config )
139+
124140 return config
0 commit comments