66 lines
2.7 KiB
Python
Executable File
66 lines
2.7 KiB
Python
Executable File
"""Tells Packagist that the package has a new version, and submits the package when it is not there yet.
|
|
|
|
Packagist reads the tags of the repository; this asks it to do that now, instead of waiting for its
|
|
own poll. The first time Packagist answers 404 (it does not know the package): then the package is
|
|
submitted through the create-package API, and Packagist reads every tag that is already there.
|
|
While PACKAGIST_USERNAME and PACKAGIST_TOKEN are not set, this only says so and succeeds.
|
|
|
|
Environment: PACKAGIST_USERNAME, PACKAGIST_TOKEN (the API token of the Packagist account, a secret
|
|
of the repository), PACKAGE_URL (the public address of the repository).
|
|
The token goes in the request and never in the log. Standard library only.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
USER = os.environ.get("PACKAGIST_USERNAME", "").strip()
|
|
TOKEN = os.environ.get("PACKAGIST_TOKEN", "").strip()
|
|
PACKAGE_URL = os.environ.get("PACKAGE_URL", "").strip()
|
|
|
|
|
|
def call(endpoint, user, token, url):
|
|
"""POST to the API of Packagist; returns the HTTP status. Raises HTTPError with the answer on a refusal."""
|
|
query = urllib.parse.urlencode({"username": user, "apiToken": token})
|
|
request = urllib.request.Request(
|
|
f"https://packagist.org/api/{endpoint}?{query}",
|
|
data=json.dumps({"repository": {"url": url}}).encode(),
|
|
method="POST",
|
|
headers={"Content-Type": "application/json"},
|
|
)
|
|
with urllib.request.urlopen(request, timeout=30) as response:
|
|
return response.status
|
|
|
|
|
|
def notify(user, token, url):
|
|
"""Tells Packagist about the package; submits it first when Packagist does not know it. Returns what happened."""
|
|
try:
|
|
return f"Packagist answered {call('update-package', user, token, url)}: it will read the new tag."
|
|
except urllib.error.HTTPError as e:
|
|
# Never echo the request (it holds the token); the answer of Packagist says enough.
|
|
if e.code != 404:
|
|
sys.exit(f"Packagist refused: {e.code} {e.read().decode()[:300]}")
|
|
|
|
try:
|
|
return f"Packagist did not know the package: submitted it (answer {call('create-package', user, token, url)}). It reads every tag that is there."
|
|
except urllib.error.HTTPError as e:
|
|
sys.exit(f"Packagist did not know the package, and refused to submit it: {e.code} {e.read().decode()[:300]}")
|
|
|
|
|
|
def main():
|
|
if not (USER and TOKEN):
|
|
print("PACKAGIST_USERNAME / PACKAGIST_TOKEN are not set: Packagist was not told. "
|
|
"Set both as secrets of the repository.")
|
|
return
|
|
if not PACKAGE_URL.startswith("https://"):
|
|
sys.exit("PACKAGE_URL must be the public https address of the repository.")
|
|
|
|
print(notify(USER, TOKEN, PACKAGE_URL))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|