8000 Correctly format files with line endings other than LF · python-lsp/python-lsp-black@450ce31 · GitHub
[go: up one dir, main page]

Skip to content

Commit 450ce31

Browse files
committed
Correctly format files with line endings other than LF
1 parent 26cfadf commit 450ce31

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

pylsp_black/_utils.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Eol chars accepted by the LSP protocol
2+
EOL_CHARS = ["\r\n", "\r", "\n"]
3+
4+
5+
def get_eol_chars(text):
6+
for eol_chars in EOL_CHARS:
7+
if text.find(eol_chars) > -1:
8+
break
9+
else:
10+
return None
11+
return eol_chars

pylsp_black/plugin.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@
77
import toml
88
from pylsp import hookimpl
99

10+
from pylsp_black._utils import get_eol_chars
11+
1012
logger = logging.getLogger(__name__)
1113

14+
1215
GLOBAL_CONFIG: Optional[Path] = None
1316
try:
1417
if os.name == "nt":
@@ -68,8 +71,25 @@ def format_text(*, text, config):
6871
string_normalization=not config["skip_string_normalization"],
6972
)
7073
try:
71-
# will raise black.NothingChanged, we want to bubble that exception up
72-
return black.format_file_contents(text, fast=config["fast"], mode=mode)
74+
# Black's format_file_contents only works reliably when eols are '\n'. It gives
75+
# an error for '\r' and produces wrong formatting for '\r\n'. So we replace
76+
# those eols by '\n' before formatting and restore them afterwards.
77+
replace_eols = False
78+
eol_chars = get_eol_chars(text)
79+
if eol_chars is not None and eol_chars != "\n":
80+
replace_eols = True
81+
text = text.replace(eol_chars, "\n")
82+
83+
# Will raise black.NothingChanged, we want to bubble that exception up
84+
formatted_text = black.format_file_contents(
85+
text, fast=config["fast"], mode=mode
86+
)
87+
88+
# Restore eols if necessary.
89+
if replace_eols:
90+
formatted_text = formatted_text.replace("\n", eol_chars)
91+
92+
return formatted_text
7393
except (
7494
# raised when the file has syntax errors
7595
ValueError,

0 commit comments

Comments
 (0)
0