Skip to content

Commit ec1e39c

Browse files
authored
Merge pull request #22 from haplo/log-errors
Log black errors to stderr
2 parents bc86305 + 74ba09d commit ec1e39c

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

pylsp_black/plugin.py

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1+
import logging
12
from typing import Dict
23

34
import black
45
import toml
56
from pylsp import hookimpl
67

8+
logger = logging.getLogger(__name__)
9+
710

811
@hookimpl(tryfirst=True)
912
def pylsp_format_document(document):
@@ -34,16 +37,8 @@ def format_document(document, range=None):
3437

3538
try:
3639
formatted_text = format_text(text=text, config=config)
37-
except (
38-
ValueError,
40+
except black.NothingChanged:
3941
# 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-
):
4742
return []
4843

4944
return [{"range": range, "newText": formatted_text}]
@@ -56,8 +51,21 @@ def format_text(*, text, config):
5651
is_pyi=config["pyi"],
5752
string_normalization=not config["skip_string_normalization"],
5853
)
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
6169

6270

6371
def load_config(filename: str) -> Dict:
@@ -74,11 +82,16 @@ def load_config(filename: str) -> Dict:
7482
pyproject_filename = root / "pyproject.toml"
7583

7684
if not pyproject_filename.is_file():
85+
logger.info("Using defaults: %r", defaults)
7786
return defaults
7887

7988
try:
8089
pyproject_toml = toml.load(str(pyproject_filename))
8190
except (toml.TomlDecodeError, OSError):
91+
logger.warning(
92+
"Error decoding pyproject.toml, using defaults: %r",
93+
defaults,
94+
)
8295
return defaults
8396

8497
file_config = pyproject_toml.get("tool", {}).get("black", {})
@@ -108,4 +121,6 @@ def load_config(filename: str) -> Dict:
108121

109122
config["target_version"] = target_version
110123

124+
logger.info("Using config from %s: %r", pyproject_filename, config)
125+
111126
return config

0 commit comments

Comments
 (0)