Skip to content
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
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ repos:
| tests/.*\.pyi$
)

- repo: https://github.com/asottile/pyupgrade
rev: v2.29.1
hooks:
- id: pyupgrade
args:
- --py36-plus
exclude: ^poetry/core/_vendor

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
Expand Down
7 changes: 2 additions & 5 deletions poetry/core/factory.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
from __future__ import absolute_import
from __future__ import unicode_literals

import logging

from pathlib import Path
Expand All @@ -23,7 +20,7 @@
logger = logging.getLogger(__name__)


class Factory(object):
class Factory:
"""
Factory class to create various elements needed by Poetry.
"""
Expand All @@ -42,7 +39,7 @@ def create_poetry(
if check_result["errors"]:
message = ""
for error in check_result["errors"]:
message += " - {}\n".format(error)
message += f" - {error}\n"

raise RuntimeError("The Poetry configuration is invalid:\n" + message)

Expand Down
5 changes: 2 additions & 3 deletions poetry/core/json/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import json
import os

from io import open
from typing import List


Expand All @@ -14,10 +13,10 @@ class ValidationError(ValueError):


def validate_object(obj: dict, schema_name: str) -> List[str]:
schema = os.path.join(SCHEMA_DIR, "{}.json".format(schema_name))
schema = os.path.join(SCHEMA_DIR, f"{schema_name}.json")

if not os.path.exists(schema):
raise ValueError("Schema {} does not exist.".format(schema_name))
raise ValueError(f"Schema {schema_name} does not exist.")

with open(schema, encoding="utf-8") as f:
schema = json.loads(f.read())
Expand Down
2 changes: 1 addition & 1 deletion poetry/core/masonry/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def build(self, fmt: str, executable: Optional[Union[str, Path]] = None) -> None
elif fmt == "all":
builders = list(self._formats.values())
else:
raise ValueError("Invalid format: {}".format(fmt))
raise ValueError(f"Invalid format: {fmt}")

for builder in builders:
builder(self._poetry, executable=executable).build()
48 changes: 14 additions & 34 deletions poetry/core/masonry/builders/builder.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import logging
import re
import shutil
import sys
import tempfile
import warnings

from collections import defaultdict
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import ContextManager
from typing import Dict
from typing import List
from typing import Optional
Expand All @@ -34,7 +29,7 @@
logger = logging.getLogger(__name__)


class Builder(object):
class Builder:
format: Optional[str] = None

def __init__(
Expand Down Expand Up @@ -215,7 +210,7 @@ def find_files_to_add(self, exclude_build: bool = True) -> Set["BuildIncludeFile
# Skip duplicates
continue

logger.debug("Adding: {}".format(str(file)))
logger.debug(f"Adding: {str(file)}")
to_add.add(include_file)

# add build script if it is specified and explicitly required
Expand All @@ -239,40 +234,40 @@ def get_metadata_content(self) -> str:

# Optional fields
if self._meta.home_page:
content += "Home-page: {}\n".format(self._meta.home_page)
content += f"Home-page: {self._meta.home_page}\n"

if self._meta.license:
content += "License: {}\n".format(self._meta.license)
content += f"License: {self._meta.license}\n"

if self._meta.keywords:
content += "Keywords: {}\n".format(self._meta.keywords)
content += f"Keywords: {self._meta.keywords}\n"

if self._meta.author:
content += "Author: {}\n".format(str(self._meta.author))
content += f"Author: {str(self._meta.author)}\n"

if self._meta.author_email:
content += "Author-email: {}\n".format(str(self._meta.author_email))
content += f"Author-email: {str(self._meta.author_email)}\n"

if self._meta.maintainer:
content += "Maintainer: {}\n".format(str(self._meta.maintainer))
content += f"Maintainer: {str(self._meta.maintainer)}\n"

if self._meta.maintainer_email:
content += "Maintainer-email: {}\n".format(str(self._meta.maintainer_email))
content += f"Maintainer-email: {str(self._meta.maintainer_email)}\n"

if self._meta.requires_python:
content += "Requires-Python: {}\n".format(self._meta.requires_python)
content += f"Requires-Python: {self._meta.requires_python}\n"

for classifier in self._meta.classifiers:
content += "Classifier: {}\n".format(classifier)
content += f"Classifier: {classifier}\n"

for extra in sorted(self._meta.provides_extra):
content += "Provides-Extra: {}\n".format(extra)
content += f"Provides-Extra: {extra}\n"

for dep in sorted(self._meta.requires_dist):
content += "Requires-Dist: {}\n".format(dep)
content += f"Requires-Dist: {dep}\n"

for url in sorted(self._meta.project_urls, key=lambda u: u[0]):
content += "Project-URL: {}\n".format(str(url))
content += f"Project-URL: {str(url)}\n"

if self._meta.description_content_type:
content += "Description-Content-Type: {}\n".format(
Expand Down Expand Up @@ -361,21 +356,6 @@ def convert_author(cls, author: str) -> Dict[str, str]:

return {"name": name, "email": email}

@classmethod
@contextmanager
def temporary_directory(cls, *args: Any, **kwargs: Any) -> ContextManager[str]:
try:
from tempfile import TemporaryDirectory

with TemporaryDirectory(*args, **kwargs) as name:
yield name
except ImportError:
name = tempfile.mkdtemp(*args, **kwargs)

yield name

shutil.rmtree(name)


class BuildIncludeFile:
def __init__(
Expand Down
30 changes: 14 additions & 16 deletions poetry/core/masonry/builders/sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def build(self, target_dir: Optional[Path] = None) -> Path:
)

try:
tar_dir = "{}-{}".format(self._package.pretty_name, self._meta.version)
tar_dir = f"{self._package.pretty_name}-{self._meta.version}"

files_to_add = self.find_files_to_add(exclude_build=False)

Expand Down Expand Up @@ -111,7 +111,7 @@ def build(self, target_dir: Optional[Path] = None) -> Path:
tar.close()
gz.close()

logger.info("Built <comment>{}</comment>".format(target.name))
logger.info(f"Built <comment>{target.name}</comment>")
return target

def build_setup(self) -> bytes:
Expand Down Expand Up @@ -162,49 +162,47 @@ def build_setup(self) -> bytes:
pass

if package_dir:
before.append("package_dir = \\\n{}\n".format(pformat(package_dir)))
before.append(f"package_dir = \\\n{pformat(package_dir)}\n")
extra.append("'package_dir': package_dir,")

if packages:
before.append("packages = \\\n{}\n".format(pformat(sorted(packages))))
before.append(f"packages = \\\n{pformat(sorted(packages))}\n")
extra.append("'packages': packages,")

if package_data:
before.append("package_data = \\\n{}\n".format(pformat(package_data)))
before.append(f"package_data = \\\n{pformat(package_data)}\n")
extra.append("'package_data': package_data,")

if modules:
before.append("modules = \\\n{}".format(pformat(modules)))
extra.append("'py_modules': modules,".format())
before.append(f"modules = \\\n{pformat(modules)}")
extra.append("'py_modules': modules,")

dependencies, extras = self.convert_dependencies(
self._package, self._package.requires
)
if dependencies:
before.append(
"install_requires = \\\n{}\n".format(pformat(sorted(dependencies)))
)
before.append(f"install_requires = \\\n{pformat(sorted(dependencies))}\n")
extra.append("'install_requires': install_requires,")

if extras:
before.append("extras_require = \\\n{}\n".format(pformat(extras)))
before.append(f"extras_require = \\\n{pformat(extras)}\n")
extra.append("'extras_require': extras_require,")

entry_points = self.convert_entry_points()
if entry_points:
before.append("entry_points = \\\n{}\n".format(pformat(entry_points)))
before.append(f"entry_points = \\\n{pformat(entry_points)}\n")
extra.append("'entry_points': entry_points,")

script_files = self.convert_script_files()
if script_files:
rel_paths = [str(p.relative_to(self._path)) for p in script_files]
before.append("scripts = \\\n{}\n".format(pformat(rel_paths)))
before.append(f"scripts = \\\n{pformat(rel_paths)}\n")
extra.append("'scripts': scripts,")

if self._package.python_versions != "*":
python_requires = self._meta.requires_python

extra.append("'python_requires': {!r},".format(python_requires))
extra.append(f"'python_requires': {python_requires!r},")

return SETUP.format(
before="\n".join(before),
Expand Down Expand Up @@ -320,7 +318,7 @@ def find_nearest_pkg(rel_path: str) -> Tuple[str, str]:
return pkgdir, sorted(packages), pkg_data

def find_files_to_add(self, exclude_build: bool = False) -> Set[BuildIncludeFile]:
to_add = super(SdistBuilder, self).find_files_to_add(exclude_build)
to_add = super().find_files_to_add(exclude_build)

# add any additional files, starting with all LICENSE files
additional_files = set(self._path.glob("LICENSE*"))
Expand All @@ -340,7 +338,7 @@ def find_files_to_add(self, exclude_build: bool = False) -> Set[BuildIncludeFile
path=file, project_root=self._path, source_root=self._path
)
if file.path.exists():
logger.debug("Adding: {}".format(file.relative_to_source_root()))
logger.debug(f"Adding: {file.relative_to_source_root()}")
to_add.add(file)

return to_add
Expand Down
22 changes: 10 additions & 12 deletions poetry/core/masonry/builders/wheel.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import unicode_literals

import contextlib
import csv
import hashlib
Expand Down Expand Up @@ -57,7 +55,7 @@ def __init__(
executable: Optional[str] = None,
editable: bool = False,
) -> None:
super(WheelBuilder, self).__init__(poetry, executable=executable)
super().__init__(poetry, executable=executable)

self._records = []
self._original_path = self._path
Expand Down Expand Up @@ -128,7 +126,7 @@ def build(self) -> None:
wheel_path.unlink()
shutil.move(temp_path, str(wheel_path))

logger.info("Built {}".format(self.wheel_filename))
logger.info(f"Built {self.wheel_filename}")

def _add_pth(self, wheel: zipfile.ZipFile) -> None:
paths = set()
Expand Down Expand Up @@ -190,7 +188,7 @@ def _build(self, wheel: zipfile.ZipFile) -> None:
if rel_path in wheel.namelist():
continue

logger.debug("Adding: {}".format(rel_path))
logger.debug(f"Adding: {rel_path}")

self._add_file(wheel, pkg, rel_path)

Expand All @@ -216,7 +214,7 @@ def _run_build_command(self, setup: Path) -> None:
)

def _run_build_script(self, build_script: str) -> None:
logger.debug("Executing build script: {}".format(build_script))
logger.debug(f"Executing build script: {build_script}")
subprocess.check_call([self.executable.as_posix(), build_script])

def _copy_module(self, wheel: zipfile.ZipFile) -> None:
Expand Down Expand Up @@ -244,10 +242,10 @@ def _write_metadata(self, wheel: zipfile.ZipFile) -> None:

for path in set(license_files_to_add):
if path.is_file():
relative_path = "%s/%s" % (self.dist_info, path.relative_to(self._path))
relative_path = f"{self.dist_info}/{path.relative_to(self._path)}"
self._add_file(wheel, path, relative_path)
else:
logger.debug("Skipping: {}".format(path.as_posix()))
logger.debug(f"Skipping: {path.as_posix()}")

with self._write_to_zip(wheel, self.dist_info + "/WHEEL") as f:
self._write_wheel_file(f)
Expand All @@ -267,7 +265,7 @@ def _write_record(self, wheel: zipfile.ZipFile) -> None:
lineterminator="\n",
)
for path, hash, size in self._records:
csv_writer.writerow((path, "sha256={}".format(hash), size))
csv_writer.writerow((path, f"sha256={hash}", size))

# RECORD itself is recorded with no hash or size
csv_writer.writerow((self.dist_info + "/RECORD", "", ""))
Expand All @@ -280,7 +278,7 @@ def dist_info(self) -> str:

@property
def wheel_data_folder(self) -> str:
return "{}-{}.data".format(self._package.name, self._meta.version)
return f"{self._package.name}-{self._meta.version}.data"

@property
def wheel_filename(self) -> str:
Expand All @@ -299,7 +297,7 @@ def dist_info_name(self, distribution: str, version: str) -> str:
escaped_name = escape_name(distribution)
escaped_version = escape_version(version)

return "{}-{}.dist-info".format(escaped_name, escaped_version)
return f"{escaped_name}-{escaped_version}.dist-info"

@property
def tag(self) -> str:
Expand Down Expand Up @@ -382,7 +380,7 @@ def _write_entry_points(self, fp: TextIO) -> None:
entry_points = self.convert_entry_points()

for group_name in sorted(entry_points):
fp.write("[{}]\n".format(group_name))
fp.write(f"[{group_name}]\n")
for ep in sorted(entry_points[group_name]):
fp.write(ep.replace(" ", "") + "\n")

Expand Down
2 changes: 1 addition & 1 deletion poetry/core/masonry/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,6 @@ def from_package(cls, package: "Package") -> "Metadata":
if name == "Homepage" and meta.home_page == url:
continue

meta.project_urls += ("{}, {}".format(name, url),)
meta.project_urls += (f"{name}, {url}",)

return meta
2 changes: 1 addition & 1 deletion poetry/core/masonry/utils/include.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Optional


class Include(object):
class Include:
"""
Represents an "include" entry.

Expand Down
Loading