Skip to content

Commit

Permalink
Merge pull request #22 from haplo/log-errors
Browse files Browse the repository at this point in the history
Log black errors to stderr
  • Loading branch information
haplo authored Nov 30, 2021
2 parents bc86305 + 74ba09d commit ec1e39c
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions pylsp_black/plugin.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import logging
from typing import Dict

import black
import toml
from pylsp import hookimpl

logger = logging.getLogger(__name__)


@hookimpl(tryfirst=True)
def pylsp_format_document(document):
Expand Down Expand Up @@ -34,16 +37,8 @@ def format_document(document, range=None):

try:
formatted_text = format_text(text=text, config=config)
except (
ValueError,
except black.NothingChanged:
# raised when the file is already formatted correctly
black.NothingChanged,
# raised when the file being formatted has an indentation error
IndentationError,
# raised when black produces invalid Python code or formats the file
# differently on the second pass
AssertionError,
):
return []

return [{"range": range, "newText": formatted_text}]
Expand All @@ -56,8 +51,21 @@ def format_text(*, text, config):
is_pyi=config["pyi"],
string_normalization=not config["skip_string_normalization"],
)

return black.format_file_contents(text, fast=config["fast"], mode=mode)
try:
# will raise black.NothingChanged, we want to bubble that exception up
return black.format_file_contents(text, fast=config["fast"], mode=mode)
except (
# raised when the file has syntax errors
ValueError,
# raised when the file being formatted has an indentation error
IndentationError,
# raised when black produces invalid Python code or formats the file
# differently on the second pass
AssertionError,
) as e:
# errors will show on lsp stderr stream
logger.error("Error formatting with black: %s", e)
raise black.NothingChanged from e


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

if not pyproject_filename.is_file():
logger.info("Using defaults: %r", defaults)
return defaults

try:
pyproject_toml = toml.load(str(pyproject_filename))
except (toml.TomlDecodeError, OSError):
logger.warning(
"Error decoding pyproject.toml, using defaults: %r",
defaults,
)
return defaults

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

config["target_version"] = target_version

logger.info("Using config from %s: %r", pyproject_filename, config)

return config

0 comments on commit ec1e39c

Please sign in to comment.