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
4 changes: 4 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
Changelog
=========

v0.15.3
-----------
- Add support for PEP 751 pylock.toml lock files as input.

v0.15.2
-----------
- Correct the version number in the CLI and setup.cfg.
Expand Down
4 changes: 2 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ python-inspector - inspect Python package dependencies and metadata

- resolve PyPI packages dependencies

- parse various requirements.txt files and setup.py files as input
for resolving dependencies.
- parse various requirements.txt files, setup.py files and PEP 751
pylock.toml lock files as input for resolving dependencies.

- parse various manifests and packages files such as
Pipfile, pyproject.toml, poetry.lock and setup.cfg and legacy and
Expand Down
27 changes: 25 additions & 2 deletions src/python_inspector/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from _packagedcode.pypi import get_resolved_purl
from python_inspector import dependencies
from python_inspector import pyinspector_settings
from python_inspector import pylock_toml
from python_inspector import utils
from python_inspector import utils_pypi
from python_inspector.package_data import get_pypi_data_from_purl
Expand Down Expand Up @@ -78,6 +79,7 @@ def to_dict(self, generic_paths=False):

def resolve_dependencies(
requirement_files=tuple(),
pylock_files=tuple(),
setup_py_file=None,
specifiers=tuple(),
python_version=None,
Expand All @@ -97,8 +99,8 @@ def resolve_dependencies(
):
"""
Resolve the dependencies for the package requirements listed in one or
more ``requirement_files``, one or more ``specifiers`` and one setuptools
``setup_py_file`` file.
more ``requirement_files``, one or more PEP 751 ``pylock_files``, one or
more ``specifiers`` and one setuptools ``setup_py_file`` file.

Resolve the dependencies for the requested ``python_version`` PYVER and
``operating_system`` OS combination defaulting Python version 3.8 and
Expand Down Expand Up @@ -171,6 +173,27 @@ def resolve_dependencies(
)
)

# pylock.toml
for pylock_file in pylock_files:
package_data = pylock_toml.parse_pylock_toml(location=pylock_file)
pylock_toml.validate_pylock_for_environment(
extra_data=package_data.extra_data,
python_version=python_version,
operating_system=operating_system,
)
index_urls = get_index_urls(index_urls, package_data.extra_data)
direct_dependencies.extend(package_data.dependencies)
pylock_path = pylock_file
if generic_paths:
pylock_path = utils.remove_test_data_dir_variable_prefix(path=pylock_file)
files.append(
dict(
type="file",
path=pylock_path,
package_data=[package_data.to_dict()],
)
)

# specs
for specifier in specifiers:
dep = dependencies.get_dependency(specifier=specifier)
Expand Down
146 changes: 146 additions & 0 deletions src/python_inspector/pylock_toml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/aboutcode-org/python-inspector for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#

from typing import Iterable
from typing import Mapping

from packvers.markers import Marker

from _packagedcode import models
from python_inspector.dependencies import get_dependency
from python_inspector.resolution import get_environment_marker_from_environment
from python_inspector.resolution import get_python_version_from_env_tag
from python_inspector.utils_pypi import Environment
from python_inspector.utils_pypi import valid_python_version

# PEP 751 pylock.toml major version this parser implements.
# 1.x files are accepted; a higher major version is a breaking format change.
SUPPORTED_LOCK_VERSION_MAJOR = 1


def load_toml(location: str) -> dict:
"""
Return a mapping parsed from the TOML file at ``location``.
"""
try:
import tomllib

with open(location, "rb") as f:
return tomllib.load(f)
except ImportError:
import toml

return toml.load(location)


def parse_pylock_toml(location: str) -> models.PackageData:
"""
Return PackageData parsed from a PEP 751 pylock.toml file at ``location``.
"""
data = load_toml(location)
lock_version = str(data.get("lock-version") or "")
if lock_version:
major = lock_version.split(".", 1)[0]
if major != str(SUPPORTED_LOCK_VERSION_MAJOR):
raise ValueError(
f"Unsupported pylock.toml lock-version {lock_version!r}. "
f"Only {SUPPORTED_LOCK_VERSION_MAJOR}.x is supported."
)

extra_index_urls = []
dependent_packages = []
for package in data.get("packages") or []:
name = package.get("name")
if not name:
continue
version = package.get("version")
if not version:
continue
specifier = f"{name}=={version}"
marker = package.get("marker")
if marker:
specifier = f"{specifier}; {marker}"
dependent_packages.append(get_dependency(specifier=specifier))
index_url = package.get("index")
if index_url and index_url not in extra_index_urls:
extra_index_urls.append(index_url)

extra_data = {}
for key in (
"lock-version",
"created-by",
"requires-python",
"environments",
"extras",
"dependency-groups",
"default-groups",
):
value = data.get(key)
if value:
extra_data[key] = value
if extra_index_urls:
extra_data["extra_index_urls"] = extra_index_urls

return models.PackageData(
datasource_id="pypi_pylock_toml",
type="pypi",
primary_language="Python",
dependencies=dependent_packages,
extra_data=extra_data,
)


def get_dependencies_from_pylock(pylock_file: str) -> Iterable[models.DependentPackage]:
"""
Yield DependentPackage for each locked package in a pylock.toml file.
"""
yield from parse_pylock_toml(location=pylock_file).dependencies


def get_extra_data_from_pylock(pylock_file: str) -> Iterable[Mapping]:
"""
Yield extra_data parsed from a pylock.toml file.
"""
yield parse_pylock_toml(location=pylock_file).extra_data


def validate_pylock_for_environment(extra_data, python_version, operating_system):
"""
Raise ValueError if the pylock metadata does not apply to ``python_version``
and ``operating_system``.
"""
extra_data = extra_data or {}
python_dot_version = get_python_version_from_env_tag(python_version=python_version)
requires_python = extra_data.get("requires-python")
if requires_python and not valid_python_version(python_dot_version, requires_python):
raise ValueError(
f"Python version {python_dot_version} is not compatible with "
f"pylock.toml requires-python {requires_python}"
)

environments = extra_data.get("environments") or []
if not environments:
return

environment = Environment.from_pyver_and_os(
python_version=python_version, operating_system=operating_system
)
environment_marker = get_environment_marker_from_environment(environment)
for expression in environments:
try:
if Marker(expression).evaluate(environment_marker):
return
except Exception:
continue
raise ValueError(
f"No pylock.toml environments marker matches python {python_dot_version} "
f"on {operating_system}: {environments}"
)
17 changes: 15 additions & 2 deletions src/python_inspector/resolve_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ def print_version(ctx, param, value):
help="Path to pip requirements file listing thirdparty packages. "
"This option can be used multiple times.",
)
@click.option(
"--pylock",
"pylock_files",
type=click.Path(exists=True, readable=True, path_type=str, dir_okay=False),
metavar="PYLOCK-FILE",
multiple=True,
required=False,
help="Path to a PEP 751 pylock.toml lock file listing locked thirdparty packages. "
"This option can be used multiple times.",
)
@click.option(
"-s",
"--setup-py",
Expand Down Expand Up @@ -190,6 +200,7 @@ def print_version(ctx, param, value):
def resolve_dependencies(
ctx,
requirement_files,
pylock_files,
setup_py_file,
specifiers,
python_version,
Expand All @@ -209,8 +220,9 @@ def resolve_dependencies(
):
"""
Resolve the dependencies for the package requirements listed in one or
more REQUIREMENT-FILE file, one or more SPECIFIER and one setuptools
SETUP-PY-FILE file and save the results as JSON to FILE.
more REQUIREMENT-FILE file, one or more PYLOCK-FILE file, one or more
SPECIFIER and one setuptools SETUP-PY-FILE file and save the results as
JSON to FILE.

Resolve the dependencies for the requested ``--python-version`` PYVER and
``--operating_system`` OS combination.
Expand Down Expand Up @@ -259,6 +271,7 @@ def resolve_dependencies(
try:
resolution_result: Dict = resolver_api(
requirement_files=requirement_files,
pylock_files=pylock_files,
setup_py_file=setup_py_file,
specifiers=specifiers,
python_version=python_version,
Expand Down
7 changes: 7 additions & 0 deletions tests/data/pylock-requires-python.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
lock-version = "1.0"
created-by = "python-inspector-tests"
requires-python = ">=3.12"

[[packages]]
name = "zipp"
version = "3.8.0"
25 changes: 25 additions & 0 deletions tests/data/pylock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
lock-version = "1.0"
created-by = "python-inspector-tests"
requires-python = ">=3.8"
environments = [
"sys_platform == 'linux'",
"sys_platform == 'windows'",
"sys_platform == 'macos'",
]

[[packages]]
name = "zipp"
version = "3.8.0"
index = "https://pypi.org/simple"
wheels = [
{name = "zipp-3.8.0-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/3b/39/874eea436a67c793ee70723cf5bb80b0dd36610c21748316ece6e885edc0/zipp-3.8.0-py3-none-any.whl", hashes = {sha256 = "56c5515d303a88fe4615cfe1e30145c483f9dc5a79747d59e28348d63902e795"}},
]

[[packages]]
name = "windows-only"
version = "1.0.0"
marker = "sys_platform == 'win32'"

[[packages]]
name = "local-src"
directory = {path = "./vendor/local-src"}
Loading
Loading