@@ -295,6 +295,13 @@ def _format_file(
295
295
file , encoding = "utf-8"
296
296
) as f :
297
297
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
298
305
try :
299
306
if file .suffix == ".py" or (file_type == "py" and file .name == "-" ):
300
307
misformatted , errors = _process_python (
@@ -305,6 +312,7 @@ def _format_file(
305
312
manager ,
306
313
raw_output ,
307
314
lock ,
315
+ newline ,
308
316
)
309
317
error_count += errors
310
318
elif (
@@ -319,6 +327,7 @@ def _format_file(
319
327
manager ,
320
328
raw_output ,
321
329
lock ,
330
+ newline ,
322
331
)
323
332
error_count += errors
324
333
except InvalidRstErrors as errors :
@@ -415,7 +424,14 @@ def _parse_sources(
415
424
416
425
417
426
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 ,
419
435
):
420
436
filename = basename (file )
421
437
object_name = filename .split ("." )[0 ]
@@ -437,7 +453,10 @@ def _process_python(
437
453
)
438
454
else :
439
455
_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 ,
441
460
)
442
461
elif raw_output :
443
462
with lock or nullcontext ():
@@ -446,7 +465,14 @@ def _process_python(
446
465
447
466
448
467
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 ,
450
476
):
451
477
doc = manager .parse_string (file , input_string )
452
478
if reporter .level >= 3 :
@@ -470,7 +496,10 @@ def _process_rst(
470
496
_write_output (file , output , nullcontext (sys .stdout ), raw_output )
471
497
else :
472
498
_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 ,
474
503
)
475
504
return misformatted , error_count
476
505
0 commit comments