Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

preserve line breaking in TOMLFile #110

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions tests/test_toml_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,30 @@ def test_toml_file(example):
finally:
with io.open(toml_file, "w", encoding="utf-8") as f:
assert f.write(original_content)


def test_keep_old_eol(tmpdir):
toml_path = str(tmpdir / "pyproject.toml")
with io.open(toml_path, "wb+") as f:
f.write(b"a = 1\r\nb = 2\r\n")

f = TOMLFile(toml_path)
content = f.read()
assert f._line_ending == "\r\n"
content["b"] = 3
f.write(content)

with io.open(toml_path, "rb") as f:
assert f.read() == b"a = 1\r\nb = 3\r\n"


def test_mixed_eol(tmpdir):
toml_path = str(tmpdir / "pyproject.toml")
with io.open(toml_path, "wb+") as f:
f.write(b"a = 1\rb = 2\r\nc = 3\n")

f = TOMLFile(toml_path)
f.write(f.read())

with io.open(toml_path, "rb") as f:
assert f.read() == "a = 1{0}b = 2{0}c = 3{0}".format(os.linesep).encode()
15 changes: 9 additions & 6 deletions tomlkit/toml_file.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import io

from typing import Any
from typing import Dict
import os

from .api import loads
from .toml_document import TOMLDocument
Expand All @@ -14,11 +12,16 @@ class TOMLFile(object):

def __init__(self, path): # type: (str) -> None
self._path = path
self._line_ending = os.linesep

def read(self): # type: () -> TOMLDocument
with io.open(self._path, encoding="utf-8") as f:
return loads(f.read())
with io.open(self._path, "r", encoding="utf-8", newline=None) as f:
content = f.read()
if not isinstance(f.newlines, tuple):
# mixed line endings
self._line_ending = f.newlines
return loads(content)

def write(self, data): # type: (TOMLDocument) -> None
with io.open(self._path, "w", encoding="utf-8") as f:
with io.open(self._path, "w", encoding="utf-8", newline=self._line_ending) as f:
f.write(data.as_string())