From cbd515b47cbb54e60df37b9bf319dbe323f0edd9 Mon Sep 17 00:00:00 2001 From: Bernhard Walle Date: Wed, 19 Apr 2023 11:29:31 +0200 Subject: [PATCH] end_of_file_fixer: write platform native line endings The most common setup for git is to use platform-native line endings in checkout (`core.autocrlf` set to `true`). So the eol file fixer should write native line endings. --- pre_commit_hooks/end_of_file_fixer.py | 3 ++- tests/end_of_file_fixer_test.py | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/pre_commit_hooks/end_of_file_fixer.py b/pre_commit_hooks/end_of_file_fixer.py index a30dce9..bd768f3 100644 --- a/pre_commit_hooks/end_of_file_fixer.py +++ b/pre_commit_hooks/end_of_file_fixer.py @@ -5,6 +5,7 @@ import os from typing import IO from typing import Sequence +platform_eol = os.linesep.encode('ascii') def fix_file(file_obj: IO[bytes]) -> int: # Test for newline at end of file @@ -18,7 +19,7 @@ def fix_file(file_obj: IO[bytes]) -> int: if last_character not in {b'\n', b'\r'} and last_character != b'': # Needs this seek for windows, otherwise IOError file_obj.seek(0, os.SEEK_END) - file_obj.write(b'\n') + file_obj.write(platform_eol) return 1 while last_character in {b'\n', b'\r'}: diff --git a/tests/end_of_file_fixer_test.py b/tests/end_of_file_fixer_test.py index 8a5d889..cb1c64b 100644 --- a/tests/end_of_file_fixer_test.py +++ b/tests/end_of_file_fixer_test.py @@ -1,6 +1,7 @@ from __future__ import annotations import io +import os import pytest @@ -9,14 +10,15 @@ from pre_commit_hooks.end_of_file_fixer import main # Input, expected return value, expected output +platform_eol = os.linesep.encode('ascii') TESTS = ( (b'foo\n', 0, b'foo\n'), (b'', 0, b''), (b'\n\n', 1, b''), (b'\n\n\n\n', 1, b''), - (b'foo', 1, b'foo\n'), + (b'foo', 1, b'foo' + platform_eol), (b'foo\n\n\n', 1, b'foo\n'), - (b'\xe2\x98\x83', 1, b'\xe2\x98\x83\n'), + (b'\xe2\x98\x83', 1, b'\xe2\x98\x83' + platform_eol), (b'foo\r\n', 0, b'foo\r\n'), (b'foo\r\n\r\n\r\n', 1, b'foo\r\n'), (b'foo\r', 0, b'foo\r'),