Last active
September 14, 2022 18:27
-
-
Save nikoheikkila/a5203186f9cf7fe0af6d154db328e336 to your computer and use it in GitHub Desktop.
Python: Quick script to update all the existing Poetry packages by traversing pyproject.toml file.
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
#!/usr/bin/env python3 | |
""" | |
Quick script to update all the existing Poetry packages by traversing pyproject.toml file. | |
Requires external package `tomli` to parse TOML file. | |
""" | |
import sys | |
from pathlib import Path | |
from shlex import split | |
from subprocess import CompletedProcess, run | |
from typing import Any | |
import tomli | |
skip_packages = "python" | |
def main() -> int: | |
try: | |
check_python_version() | |
dependencies = fetch_dependencies() | |
command = build_update_command(dependencies) | |
print(f'Attempting to update packages: {", ".join(dependencies)}') | |
print(f"$ {command}") | |
print(shell(command)) | |
except Exception as error: | |
return error | |
return 0 | |
def check_python_version() -> None: | |
major = sys.version_info.major | |
minor = sys.version_info.minor | |
assert major >= 3 and minor >= 9, "Python 3.9+ required" | |
def shell(command: str) -> str: | |
result: CompletedProcess[str] = run( | |
split(command), capture_output=True, check=True, text=True | |
) | |
assert not result.stderr | |
return result.stdout | |
def fetch_dependencies() -> list[str]: | |
path = Path.cwd() / "pyproject.toml" | |
assert path.is_file(), f"File not found: {path}" | |
with path.open(mode="rb") as f: | |
project = tomli.load(f) | |
dependencies: dict[str, Any] = project["tool"]["poetry"]["dependencies"] | |
assert dependencies, "No dependencies found" | |
return [ | |
dependency | |
for dependency in dependencies.keys() | |
if dependency not in skip_packages | |
] | |
def build_update_command(dependencies: list[str]) -> str: | |
updates = " ".join(f"{name}@latest" for name in dependencies) | |
return f"poetry add {updates}" | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment