Skip to content

Commit

Permalink
Add a setup file context manager in sdist builder
Browse files Browse the repository at this point in the history
A temporary setup file is required for various scenarios
at the moment. This change introduces a context manager
such that generates a temporary setup.py file and handles
cleanup on exiting the context.
  • Loading branch information
abn committed Apr 6, 2020
1 parent d39182a commit a69e583
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
21 changes: 21 additions & 0 deletions poetry/core/masonry/builders/sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@
import time

from collections import defaultdict
from contextlib import contextmanager
from copy import copy
from gzip import GzipFile
from io import BytesIO
from posixpath import join as pjoin
from pprint import pformat
from typing import Iterator

from poetry.core.utils._compat import Path
from poetry.core.utils._compat import decode
from poetry.core.utils._compat import encode
from poetry.core.utils._compat import to_str

Expand Down Expand Up @@ -198,6 +201,24 @@ def build_setup(self): # type: () -> bytes
)
)

@contextmanager
def setup_py(self): # type: () -> Iterator[Path]
setup = self._path / "setup.py"
has_setup = setup.exists()

if has_setup:
logger.info(
" - <warning>A setup.py file already exists. Using it.</warning>"
)
else:
with setup.open("w", encoding="utf-8") as f:
f.write(decode(self.build_setup()))

yield setup

if not has_setup:
setup.unlink()

def build_pkg_info(self):
return encode(self.get_metadata_content())

Expand Down
26 changes: 26 additions & 0 deletions tests/masonry/builders/test_sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.vcs_dependency import VCSDependency
from poetry.core.utils._compat import Path
from poetry.core.utils._compat import encode
from poetry.core.utils._compat import to_str


Expand Down Expand Up @@ -247,6 +248,31 @@ def test_package():
assert "my-package-1.2.3/LICENSE" in tar.getnames()


def test_setup_py_context():
poetry = Factory().create_poetry(project("complete"))

builder = SdistBuilder(poetry)

project_setup_py = poetry.file.parent / "setup.py"

assert not project_setup_py.exists()

try:
with builder.setup_py() as setup:
assert setup.exists()
assert project_setup_py == setup

with open(str(setup), "rb") as f:
# we convert to string and replace line endings here for compatibility
data = to_str(encode(f.read())).replace("\r\n", "\n")
assert data == to_str(builder.build_setup())

assert not project_setup_py.exists()
finally:
if project_setup_py.exists():
project_setup_py.unlink()


def test_module():
poetry = Factory().create_poetry(project("module1"))

Expand Down

0 comments on commit a69e583

Please sign in to comment.