Skip to content

Instantly share code, notes, and snippets.

@danilogco
Last active June 23, 2025 21:20
Show Gist options
  • Save danilogco/ad468c4854f7235dae31c24544a4ef33 to your computer and use it in GitHub Desktop.
Save danilogco/ad468c4854f7235dae31c24544a4ef33 to your computer and use it in GitHub Desktop.
Poetry order and update all dependencies
# pip install pyinstaller
# pyinstaller --onefile update.py
# sudo mv dist/update /usr/local/bin/poetry-update
# chmod +x /usr/local/bin/poetry-update
import tomlkit
import requests
from pathlib import Path
import subprocess
PYPROJECT_PATH = Path("pyproject.toml")
def get_latest_version(package_name):
try:
resp = requests.get(f"https://pypi.org/pypi/{package_name}/json", timeout=5)
resp.raise_for_status()
return resp.json()["info"]["version"]
except Exception:
return None
def sort_dependencies(dep_section):
# dep_section é tomlkit.items.Table
regular_deps = {}
other_deps = {}
for k, v in dep_section.items():
# Preservar exatamente se for dict com path, extras ou develop
if isinstance(v, tomlkit.items.Table):
keys = v.keys()
if "path" in keys or "git" in keys or "extras" in keys or "develop" in keys:
other_deps[k] = v
else:
# Se for objeto mas sem keys especiais, não mexe
other_deps[k] = v
else:
# Se for string, tenta pegar última versão e atualizar
if isinstance(v, str):
latest = get_latest_version(k)
if latest:
regular_deps[k] = f"^{latest}"
else:
regular_deps[k] = v
else:
# Outros tipos, preserva
other_deps[k] = v
# Ordenar alfabeticamente
sorted_regular = dict(sorted(regular_deps.items()))
sorted_other = dict(sorted(other_deps.items()))
new_table = tomlkit.table()
# Adiciona primeiro as regulares atualizadas
for k, v in sorted_regular.items():
new_table.add(k, v)
# Depois as especiais, preservando ordem alfa
for k, v in sorted_other.items():
new_table.add(k, v)
return new_table
def main():
if not PYPROJECT_PATH.exists():
print("pyproject.toml não encontrado.")
return
with open(PYPROJECT_PATH, "r", encoding="utf-8") as f:
doc = tomlkit.parse(f.read())
if "tool" in doc and "poetry" in doc["tool"]:
poetry = doc["tool"]["poetry"]
if "dependencies" in poetry:
poetry["dependencies"] = sort_dependencies(poetry["dependencies"])
if "group" in poetry:
for group_name, group in poetry["group"].items():
if "dependencies" in group:
group["dependencies"] = sort_dependencies(group["dependencies"])
with open(PYPROJECT_PATH, "w", encoding="utf-8") as f:
f.write(tomlkit.dumps(doc))
print("✅ pyproject.toml atualizado e ordenado.")
try:
subprocess.run(["poetry", "update"], check=True)
print("✅ poetry update executado com sucesso.")
except subprocess.CalledProcessError:
print("⚠️ Falha ao executar 'poetry update'. Verifique se o Poetry está instalado e configurado.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment