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

Fix for tomlkit regression resulting in inconsistent line endings #403

Closed
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
49 changes: 48 additions & 1 deletion src/poetry/core/toml/file.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,64 @@
from __future__ import annotations

import os
import re

from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any

from tomlkit import loads
from tomlkit.toml_file import TOMLFile as BaseTOMLFile


if TYPE_CHECKING:
from tomlkit.toml_document import TOMLDocument


class TOMLFile(BaseTOMLFile): # type: ignore[misc]
class PatchedBaseTOMLFile(BaseTOMLFile): # type: ignore[misc]
"""
This class can be removed when https://github.com/sdispater/tomlkit/issues/200 is
resolved and changes from https://github.com/sdispater/tomlkit/pull/201 are
available.
"""

def __init__(self, path: str) -> None:
super().__init__(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:
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(content)


class TOMLFile(PatchedBaseTOMLFile):
def __init__(self, path: str | Path) -> None:
if isinstance(path, str):
path = Path(path)
Expand Down