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

Add a final line-ending if multi-line input string #382

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
10 changes: 9 additions & 1 deletion tomlkit/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,12 @@ class Container(_CustomDict):
This class implements the `dict` interface with copy/deepcopy protocol.
"""

def __init__(self, parsed: bool = False) -> None:
def __init__(self, parsed: bool = False, last_line_newline_added: str = "") -> None:
self._map: dict[SingleKey, int | tuple[int, ...]] = {}
self._body: list[tuple[Key | None, Item]] = []
self._parsed = parsed
self._table_keys = []
self._last_line_newline_added = last_line_newline_added

@property
def body(self) -> list[tuple[Key | None, Item]]:
Expand Down Expand Up @@ -490,6 +491,13 @@ def as_string(self) -> str:
else:
s += self._render_simple_item(k, v)

# If we added a final newline, we must remove it now
if self._last_line_newline_added:
if s.endswith("\r\n"):
s = s[:-2]
else:
s = s[:-1]

return s

def _render_table(self, key: Key, table: Table, prefix: str | None = None) -> str:
Expand Down
18 changes: 16 additions & 2 deletions tomlkit/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,21 @@ class Parser:

def __init__(self, string: str | bytes) -> None:
# Input to parse
self._src = Source(decode(string))
string = decode(string)

# Add correct final line-ending if needed
num_newline = string.count("\n")
self._newline_added = ""
if num_newline and string[-1] != "\n":
num_win_eol = string.count("\r\n")

if num_win_eol == num_newline:
self._newline_added = "\r\n"
else:
self._newline_added = "\n"
string += self._newline_added

self._src = Source(string)

self._aot_stack: list[Key] = []

Expand Down Expand Up @@ -127,7 +141,7 @@ def parse_error(self, exception=ParseError, *args, **kwargs):
return self._src.parse_error(exception, *args, **kwargs)

def parse(self) -> TOMLDocument:
body = TOMLDocument(True)
body = TOMLDocument(True, self._newline_added)

# Take all keyvals outside of tables/AoT's.
while not self.end():
Expand Down
Loading