Skip to content

Commit

Permalink
fix: keep lock file eol (#9468)
Browse files Browse the repository at this point in the history
Co-authored-by: Randy Döring <[email protected]>
  • Loading branch information
trim21 and radoering committed Aug 18, 2024
1 parent 3175fb0 commit 5d19ab0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/poetry/packages/locker.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,33 @@ def _should_write(self, lock: TOMLDocument) -> bool:
return do_write

def _write_lock_data(self, data: TOMLDocument) -> None:
lockfile = TOMLFile(self.lock)
lockfile.write(data)
if self.lock.exists():
# The following code is roughly equivalent to
# • lockfile = TOMLFile(self.lock)
# • lockfile.read()
# • lockfile.write(data)
# However, lockfile.read() takes more than half a second even
# for a modestly sized project like Poetry itself and the only reason
# for reading the lockfile is to determine the line endings. Thus,
# we do that part for ourselves here, which only takes about 10 ms.

# get original line endings
with open(self.lock, encoding="utf-8", newline="") as f:
line = f.readline()
linesep = "\r\n" if line.endswith("\r\n") else "\n"

# enforce original line endings
content = data.as_string()
if linesep == "\n":
content = content.replace("\r\n", "\n")
elif linesep == "\r\n":
content = re.sub(r"(?<!\r)\n", "\r\n", content)
with open(self.lock, "w", encoding="utf-8", newline="") as f:
f.write(content)

else:
lockfile = TOMLFile(self.lock)
lockfile.write(data)

self._lock_data = None

Expand Down
17 changes: 17 additions & 0 deletions tests/packages/test_locker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1231,3 +1231,20 @@ def test_lockfile_is_not_rewritten_if_only_poetry_version_changed(
content = f.read()

assert content == old_content


def test_lockfile_keep_eol(locker: Locker, root: ProjectPackage) -> None:
sep = "\n" if os.linesep == "\r\n" else "\r\n"

with open(locker.lock, "wb") as f:
f.write((sep * 10).encode())

assert locker.set_lock_data(root, [Package("test", version="0.0.1")])

with locker.lock.open(encoding="utf-8", newline="") as f:
line, *_ = f.read().splitlines(keepends=True)

if sep == "\r\n":
assert line.endswith("\r\n")
else:
assert not line.endswith("\r\n")

0 comments on commit 5d19ab0

Please sign in to comment.