Created
January 1, 2025 03:57
-
-
Save codeperfectplus/d684ca84bf015cae9d21d56ea8a2e4a1 to your computer and use it in GitHub Desktop.
update_requirements
This file contains hidden or 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
# update_requirements.py | |
import requests | |
import re | |
from typing import List | |
def fetch_latest_version(package_name: str) -> str: | |
"""Fetch the latest version of a package from PyPI.""" | |
url = f"https://pypi.org/pypi/{package_name}/json" | |
try: | |
response = requests.get(url) | |
response.raise_for_status() | |
data = response.json() | |
return data["info"]["version"] | |
except requests.exceptions.RequestException as e: | |
print(f"Error fetching latest version for {package_name}: {e}") | |
return None | |
def parse_requirements(file_path: str) -> List[str]: | |
"""Read and parse a requirements.txt file.""" | |
with open(file_path, "r") as file: | |
return file.readlines() | |
def update_requirements(file_path: str): | |
"""Update the requirements.txt file with the latest package versions.""" | |
requirements = parse_requirements(file_path) | |
updated_requirements = [] | |
for line in requirements: | |
# Ignore comments and empty lines | |
if line.startswith("#") or not line.strip(): | |
updated_requirements.append(line) | |
continue | |
# Extract the package name | |
match = re.match(r"([a-zA-Z0-9\-_.]+)([<>=!~]+[\d.]+)?", line) | |
if not match: | |
updated_requirements.append(line) | |
continue | |
package_name = match.group(1) | |
latest_version = fetch_latest_version(package_name) | |
if latest_version: | |
updated_requirements.append(f"{package_name}=={latest_version}\n") | |
else: | |
updated_requirements.append(line) # Retain the original line if the version can't be fetched | |
# Write updated requirements back to the file | |
with open(file_path, "w") as file: | |
file.writelines(updated_requirements) | |
print(f"Updated requirements file saved at: {file_path}") | |
if __name__ == "__main__": | |
import argparse | |
parser = argparse.ArgumentParser(description="Update requirements.txt with the latest package versions.") | |
parser.add_argument("file", type=str, help="Path to the requirements.txt file") | |
args = parser.parse_args() | |
update_requirements(args.file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment