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

Backport fixes from master #3622

Merged
merged 4 commits into from
Jan 30, 2021
Merged
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
33 changes: 16 additions & 17 deletions poetry/console/commands/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ def handle(self):
packages = [name for name in packages if name not in existing_packages]

if not packages:
self.poetry.file.write(content)
self.line("Nothing to add.")
return 0

Expand Down Expand Up @@ -152,29 +151,29 @@ def handle(self):

poetry_content[section][_constraint["name"]] = constraint

# Write new content
self.poetry.file.write(content)
try:
# Write new content
self.poetry.file.write(content)

# Cosmetic new line
self.line("")
# Cosmetic new line
self.line("")

# Update packages
self.reset_poetry()
# Update packages
self.reset_poetry()

self._installer.set_package(self.poetry.package)
self._installer.dry_run(self.option("dry-run"))
self._installer.verbose(self._io.is_verbose())
self._installer.update(True)
if self.option("lock"):
self._installer.lock()
self._installer.set_package(self.poetry.package)
self._installer.dry_run(self.option("dry-run"))
self._installer.verbose(self._io.is_verbose())
self._installer.update(True)
if self.option("lock"):
self._installer.lock()

self._installer.whitelist([r["name"] for r in requirements])
self._installer.whitelist([r["name"] for r in requirements])

try:
status = self._installer.run()
except Exception:
except BaseException:
# Using BaseException here as some exceptions, eg: KeyboardInterrupt, do not inherit from Exception
self.poetry.file.write(original_content)

raise

if status != 0 or self.option("dry-run"):
Expand Down
13 changes: 11 additions & 2 deletions poetry/repositories/legacy_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,17 @@ def _get(self, endpoint): # type: (str) -> Union[Page, None]

if response.status_code in (401, 403):
self._log(
"Authorization error accessing {url}".format(url=url), level="warn"
"Authorization error accessing {url}".format(url=response.url),
level="warn",
)
return

return Page(url, response.content, response.headers)
if response.url != url:
self._log(
"Response URL {response_url} differs from request URL {url}".format(
response_url=response.url, url=url
),
level="debug",
)

return Page(response.url, response.content, response.headers)
4 changes: 4 additions & 0 deletions poetry/utils/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from poetry.poetry import Poetry
from poetry.utils._compat import Path
from poetry.utils._compat import decode
from poetry.utils._compat import urlparse


class Exporter(object):
Expand Down Expand Up @@ -139,6 +140,9 @@ def _export_requirements_txt(
url = (
repository.authenticated_url if with_credentials else repository.url
)
parsed_url = urlparse.urlsplit(url)
if parsed_url.scheme == "http":
indexes_header += "--trusted-host {}\n".format(parsed_url.netloc)
indexes_header += "--extra-index-url {}\n".format(url)

content = indexes_header + "\n" + content
Expand Down
23 changes: 23 additions & 0 deletions tests/console/commands/test_add.py
Original file line number Diff line number Diff line change
Expand Up @@ -1630,3 +1630,26 @@ def test_add_with_lock_old_installer(app, repo, installer, old_tester):
"""

assert expected == old_tester.io.fetch_output()


def test_add_keyboard_interrupt_restore_content(app, repo, installer, tester, mocker):
mocker.patch(
"poetry.installation.installer.Installer.run", side_effect=KeyboardInterrupt()
)
original_content = app.poetry.file.read()

repo.add_package(get_package("cachy", "0.2.0"))

tester.execute("cachy --dry-run")

assert original_content == app.poetry.file.read()


def test_dry_run_restore_original_content(app, repo, installer, tester):
original_content = app.poetry.file.read()

repo.add_package(get_package("cachy", "0.2.0"))

tester.execute("cachy --dry-run")

assert original_content == app.poetry.file.read()
15 changes: 15 additions & 0 deletions tests/repositories/test_legacy_repository.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import shutil

import pytest
import requests

from poetry.core.packages import Dependency
from poetry.factory import Factory
Expand Down Expand Up @@ -332,3 +333,17 @@ def test_get_4xx_and_5xx_raises(http):
for endpoint in endpoints:
with pytest.raises(RepositoryError):
repo._get(endpoint)


def test_get_redirected_response_url(http, mocker):
repo = MockHttpRepository({"/foo": 200}, http)
redirect_url = "http://legacy.redirect.bar"

def get_mock(url):
response = requests.Response()
response.status_code = 200
response.url = redirect_url + "/foo"
return response

mocker.patch.object(requests.Session, "get", side_effect=get_mock)
assert repo._get("/foo")._url == "http://legacy.redirect.bar/foo/"
46 changes: 46 additions & 0 deletions tests/utils/test_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1028,6 +1028,52 @@ def test_exporter_exports_requirements_txt_with_legacy_packages(tmp_dir, poetry)
assert expected == content


def test_exporter_exports_requirements_txt_with_legacy_packages_trusted_host(
tmp_dir, poetry
):
poetry.pool.add_repository(LegacyRepository("custom", "http://example.com/simple",))
poetry.locker.mock_lock_data(
{
"package": [
{
"name": "bar",
"version": "4.5.6",
"category": "dev",
"optional": False,
"python-versions": "*",
"source": {
"type": "legacy",
"url": "http://example.com/simple",
"reference": "",
},
},
],
"metadata": {
"python-versions": "*",
"content-hash": "123456789",
"hashes": {"bar": ["67890"]},
},
}
)
set_package_requires(poetry)
exporter = Exporter(poetry)

exporter.export("requirements.txt", Path(tmp_dir), "requirements.txt", dev=True)

with (Path(tmp_dir) / "requirements.txt").open(encoding="utf-8") as f:
content = f.read()

expected = """\
--trusted-host example.com
--extra-index-url http://example.com/simple

bar==4.5.6 \\
--hash=sha256:67890
"""

assert expected == content


@pytest.mark.parametrize(
("dev", "expected"),
[
Expand Down