Skip to content

Commit 3e70574

Browse files
committed
Respect source file EOL chars instead of imposing platform default
1 parent ade34c1 commit 3e70574

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

docstrfmt/main.py

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,13 @@ def _format_file(
295295
file, encoding="utf-8"
296296
) as f:
297297
input_string = f.read()
298+
try:
299+
newline = f.newlines
300+
except AttributeError:
301+
newline = None
302+
# If mixed or unknown newlines, fall back to the platform default
303+
if not isinstance(newline, str):
304+
newline = None
298305
try:
299306
if file.suffix == ".py" or (file_type == "py" and file.name == "-"):
300307
misformatted, errors = _process_python(
@@ -305,6 +312,7 @@ def _format_file(
305312
manager,
306313
raw_output,
307314
lock,
315+
newline,
308316
)
309317
error_count += errors
310318
elif (
@@ -319,6 +327,7 @@ def _format_file(
319327
manager,
320328
raw_output,
321329
lock,
330+
newline,
322331
)
323332
error_count += errors
324333
except InvalidRstErrors as errors:
@@ -415,7 +424,14 @@ def _parse_sources(
415424

416425

417426
def _process_python(
418-
check, file, input_string, line_length, manager, raw_output, lock=None
427+
check,
428+
file,
429+
input_string,
430+
line_length,
431+
manager,
432+
raw_output,
433+
lock=None,
434+
newline=None,
419435
):
420436
filename = basename(file)
421437
object_name = filename.split(".")[0]
@@ -437,7 +453,10 @@ def _process_python(
437453
)
438454
else:
439455
_write_output(
440-
file, result.code, open(file, "w", encoding="utf-8"), raw_output
456+
file,
457+
result.code,
458+
open(file, "w", encoding="utf-8", newline=newline),
459+
raw_output,
441460
)
442461
elif raw_output:
443462
with lock or nullcontext():
@@ -446,7 +465,14 @@ def _process_python(
446465

447466

448467
def _process_rst(
449-
check, file, input_string, line_length, manager, raw_output, lock=None
468+
check,
469+
file,
470+
input_string,
471+
line_length,
472+
manager,
473+
raw_output,
474+
lock=None,
475+
newline=None,
450476
):
451477
doc = manager.parse_string(file, input_string)
452478
if reporter.level >= 3:
@@ -470,7 +496,10 @@ def _process_rst(
470496
_write_output(file, output, nullcontext(sys.stdout), raw_output)
471497
else:
472498
_write_output(
473-
file, output, open(file, "w", encoding="utf-8"), raw_output
499+
file,
500+
output,
501+
open(file, "w", encoding="utf-8", newline=newline),
502+
raw_output,
474503
)
475504
return misformatted, error_count
476505

0 commit comments

Comments
 (0)