Last active
September 24, 2024 20:14
-
-
Save danilogco/149c155403aa9df1720a2e3821f3427e to your computer and use it in GitHub Desktop.
Script to update and organize all poetry dependencies at once
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
import requests | |
import tomlkit | |
def get_latest_version(package_name): | |
response = requests.get(f"https://pypi.org/pypi/{package_name}/json") | |
if response.status_code == 200: | |
data = response.json() | |
return data['info']['version'] | |
else: | |
print(f"Failed to fetch latest version for {package_name}") | |
return None | |
def update_dependency_section(dependencies): | |
sorted_dependencies = dict(sorted(dependencies.items())) | |
for package, current_version in sorted_dependencies.items(): | |
if package == "python": | |
continue # Skip the python version specification | |
latest_version = get_latest_version(package) | |
if latest_version: | |
if isinstance(current_version, str): | |
if current_version.startswith('^'): | |
sorted_dependencies[package] = f"^{latest_version}" | |
else: | |
sorted_dependencies[package] = latest_version | |
elif isinstance(current_version, dict) and 'version' in current_version: | |
version = current_version['version'] | |
if version.startswith('^'): | |
current_version['version'] = f"^{latest_version}" | |
else: | |
current_version['version'] = latest_version | |
print(f"Updated {package} from {current_version} to {sorted_dependencies[package]}") | |
return sorted_dependencies | |
def update_dependencies(file_path): | |
with open(file_path, 'r') as file: | |
pyproject = tomlkit.parse(file.read()) | |
# Update main dependencies | |
dependencies = pyproject.get('tool', {}).get('poetry', {}).get('dependencies', {}) | |
pyproject['tool']['poetry']['dependencies'] = update_dependency_section(dependencies) | |
# Update development dependencies | |
dev_dependencies = pyproject.get('tool', {}).get('poetry', {}).get('group', {}).get('dev', {}).get('dependencies', {}) | |
pyproject['tool']['poetry']['group']['dev']['dependencies'] = update_dependency_section(dev_dependencies) | |
with open(file_path, 'w') as file: | |
file.write(tomlkit.dumps(pyproject)) | |
if __name__ == "__main__": | |
update_dependencies('pyproject.toml') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment