-
Notifications
You must be signed in to change notification settings - Fork 7
/
blackify.py
31 lines (24 loc) · 832 Bytes
/
blackify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# pylint: disable=no-name-in-module
from black import format_file_contents
from black.mode import Mode
from black.parsing import InvalidInput
from black.report import NothingChanged
from handsdown.exceptions import ParserError
def blackify(content: str) -> str:
"""
Format `content` with `black`.
Arguments:
content -- Python code to format.
Returns:
Formatted python code.
Raises:
ValueError -- If `content` is not a valid Python code.
"""
file_mode = Mode(is_pyi=False, line_length=89, preview=True)
try:
content = format_file_contents(content, fast=True, mode=file_mode)
except NothingChanged:
pass
except (IndentationError, InvalidInput) as e:
raise ParserError(f"Cannot parse {content}: {e}") from e
return content.rstrip("\n")