Created
November 9, 2023 09:35
-
-
Save bartmachielsen/ec96d229313c3079acc93140adbddd05 to your computer and use it in GitHub Desktop.
Pin dependancies for Poetry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pathlib import Path | |
import pkg_resources | |
import toml | |
def pin_dependency_version(dependency_name, installed_packages): | |
# If the package is in the installed packages and it's not a path or git dependency | |
if dependency_name in installed_packages and isinstance(dependency_name, str): | |
# Pin the version to the one currently installed, allowing compatible updates | |
return f"^{installed_packages[dependency_name]}" | |
else: | |
return None | |
# Load the current pyproject.toml | |
pyproject_path = Path( | |
"pyproject.toml" | |
) # Replace with the path to your pyproject.toml file | |
pyproject_content = toml.load(pyproject_path) | |
# Get a list of currently installed packages and their versions | |
installed_packages = {dist.key: dist.version for dist in pkg_resources.working_set} | |
# Pin versions for the main dependencies | |
for package_name, package_info in pyproject_content["tool"]["poetry"][ | |
"dependencies" | |
].items(): | |
if "*" not in package_info: | |
continue | |
pinned_version = pin_dependency_version(package_name, installed_packages) | |
if pinned_version: | |
pyproject_content["tool"]["poetry"]["dependencies"][ | |
package_name | |
] = pinned_version | |
# Pin versions for dependencies in each group | |
for group_key in pyproject_content["tool"]["poetry"]["group"]: | |
group_dependencies = pyproject_content["tool"]["poetry"]["group"][group_key][ | |
"dependencies" | |
] | |
for package_name, package_info in group_dependencies.items(): | |
if "*" not in package_info: | |
continue | |
pinned_version = pin_dependency_version(package_name, installed_packages) | |
if pinned_version: | |
group_dependencies[package_name] = pinned_version | |
# Save the updated pyproject.toml | |
with pyproject_path.open("w") as pyproject_file: | |
toml.dump(pyproject_content, pyproject_file) | |
print("pyproject.toml has been updated with pinned versions.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment