Keep consistent line endings when changing files and use os.linesep as default for new files (#201)
GitOrigin-RevId: 01e56ea366e5eea2b4b9ef436ad6c99a0b8569ec
Change-Id: Ic149076bb58c7fbc5591a2dbc1a59637d8fdf371
diff --git a/tomlkit/toml_file.py b/tomlkit/toml_file.py
index 47c9f2c..5b28cb0 100644
--- a/tomlkit/toml_file.py
+++ b/tomlkit/toml_file.py
@@ -1,3 +1,6 @@
+import os
+import re
+
from .api import loads
from .toml_document import TOMLDocument
@@ -11,13 +14,35 @@
def __init__(self, path: str) -> None:
self._path = path
+ self._linesep = os.linesep
def read(self) -> TOMLDocument:
"""Read the file content as a :class:`tomlkit.toml_document.TOMLDocument`."""
with open(self._path, encoding="utf-8", newline="") as f:
- return loads(f.read())
+ content = f.read()
+
+ # check if consistent line endings
+ num_newline = content.count("\n")
+ if num_newline > 0:
+ num_win_eol = content.count("\r\n")
+ if num_win_eol == num_newline:
+ self._linesep = "\r\n"
+ elif num_win_eol == 0:
+ self._linesep = "\n"
+ else:
+ self._linesep = "mixed"
+
+ return loads(content)
def write(self, data: TOMLDocument) -> None:
"""Write the TOMLDocument to the file."""
+ content = data.as_string()
+
+ # apply linesep
+ if self._linesep == "\n":
+ content = content.replace("\r\n", "\n")
+ elif self._linesep == "\r\n":
+ content = re.sub(r"(?<!\r)\n", "\r\n", content)
+
with open(self._path, "w", encoding="utf-8", newline="") as f:
- f.write(data.as_string())
+ f.write(content)