1
0
Fork 0
mirror of https://github.com/YunoHost-Apps/mediawiki_ynh.git synced 2024-09-03 19:46:05 +02:00
mediawiki_ynh/.github/workflows/updater.py

125 lines
4.4 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
2022-08-11 16:08:33 +02:00
"""
This script is meant to be run by GitHub Actions.
It comes with a Github Action updater.yml to run this script periodically.
Since each app is different, maintainers can adapt its contents to perform
automatic actions when a new upstream release is detected.
You need to enable the action by removing `if ${{ false }}` in updater.yml!
"""
import hashlib
import logging
import os
import textwrap
2023-09-15 17:01:49 +02:00
from subprocess import PIPE, run
from typing import Any, List, Optional, Tuple
2023-09-15 17:01:49 +02:00
import requests
2023-06-08 21:54:39 +02:00
import tomlkit
2023-09-15 17:01:49 +02:00
from packaging import version
2023-06-08 21:54:39 +02:00
logging.getLogger().setLevel(logging.INFO)
2022-08-11 16:08:33 +02:00
# ========================================================================== #
# Functions customizable by app maintainer
2023-06-08 21:54:39 +02:00
def get_latest_version(repo: str) -> Tuple[version.Version, Any]:
2022-08-11 16:08:33 +02:00
"""May be customized by maintainers for other forges than Github"""
api_url = repo.replace("github.com", "api.github.com/repos")
# May use {api_url}/tags and release["name"] for tag-based upstream
releases = requests.get(f"{api_url}/tags").json()
2022-08-11 16:08:33 +02:00
release_info = next(
release for release in releases
if "-rc" not in release["name"] and "REL" not in release["name"]
2022-08-11 16:08:33 +02:00
)
return version.Version(release_info["name"]), release_info
2023-06-08 21:54:39 +02:00
2022-08-11 16:08:33 +02:00
def get_asset_urls_of_release(repo: str, release: Any) -> List[str]:
"""May be customized by maintainers for custom urls"""
2022-08-11 16:08:33 +02:00
rel = release['name']
short_rel = '.'.join(rel.split('.')[:2])
2022-08-11 16:08:33 +02:00
return [
f"https://releases.wikimedia.org/mediawiki/{short_rel}/mediawiki-{rel}.tar.gz"
]
2023-06-08 21:54:39 +02:00
def handle_asset(asset_url: str) -> Optional[str]:
2022-08-11 16:08:33 +02:00
"""This should be customized by the maintainer according to upstream"""
logging.info("Handling asset at %s", asset_url)
if asset_url.endswith(".tar.gz"):
2023-06-08 21:54:39 +02:00
return "main"
logging.info("Asset ignored")
return None
2022-08-11 16:08:33 +02:00
# ========================================================================== #
# Core generic code of the script
2023-06-08 21:54:39 +02:00
def sha256sum_of_url(url: str) -> str:
"""Compute checksum without saving the file"""
checksum = hashlib.sha256()
2023-06-08 21:54:39 +02:00
for chunk in requests.get(url, stream=True, timeout=100).iter_content(chunk_size=4096):
checksum.update(chunk)
return checksum.hexdigest()
2022-08-11 16:08:33 +02:00
def write_github_env(proceed: bool, new_version: str, branch: str):
"""Those values will be used later in the workflow"""
if "GITHUB_ENV" not in os.environ:
logging.warning("GITHUB_ENV is not in the envvars, assuming not in CI")
return
with open(os.environ["GITHUB_ENV"], "w", encoding="utf-8") as github_env:
2022-08-11 16:08:33 +02:00
github_env.write(textwrap.dedent(f"""\
VERSION={new_version}
BRANCH={branch}
PROCEED={str(proceed).lower()}
"""))
2023-06-08 21:54:39 +02:00
2022-08-11 16:08:33 +02:00
def main():
2023-06-08 21:54:39 +02:00
with open("manifest.toml", "r", encoding="utf-8") as manifest_file:
manifest = tomlkit.loads(manifest_file.read())
repo = manifest["upstream"]["code"]
2023-06-08 21:54:39 +02:00
current_version = version.Version(manifest["version"].value.split("~")[0])
latest_version, release_info = get_latest_version(repo)
2022-08-11 16:08:33 +02:00
logging.info("Current version: %s", current_version)
logging.info("Latest upstream version: %s", latest_version)
# Proceed only if the retrieved version is greater than the current one
if latest_version <= current_version:
logging.warning("No new version available")
2022-08-11 16:08:33 +02:00
write_github_env(False, "", "")
return
# Proceed only if a PR for this new version does not already exist
2022-08-11 16:08:33 +02:00
branch = f"ci-auto-update-v{latest_version}"
2023-07-19 19:46:42 +02:00
command = ["git", "ls-remote", "--exit-code", "-h", f"https://github.com/{os.environ['GITHUB_REPOSITORY']}.git", branch]
2022-08-11 16:08:33 +02:00
if run(command, stderr=PIPE, stdout=PIPE, check=False).returncode == 0:
logging.warning("A branch already exists for this update")
2022-08-11 16:08:33 +02:00
write_github_env(False, "", "")
return
2022-08-11 16:08:33 +02:00
assets = get_asset_urls_of_release(repo, release_info)
2023-06-08 21:54:39 +02:00
logging.info("%d available asset(s)", len(assets))
for asset in assets:
2023-06-08 21:54:39 +02:00
name = handle_asset(asset)
if name:
manifest["resources"]["sources"][name]["url"] = asset
manifest["resources"]["sources"][name]["sha256"] = sha256sum_of_url(asset)
manifest["version"] = f"{latest_version}~ynh1"
2023-06-08 21:54:39 +02:00
with open("manifest.toml", "w", encoding="utf-8") as manifest_file:
manifest_file.write(tomlkit.dumps(manifest))
2022-08-11 16:08:33 +02:00
write_github_env(True, latest_version, branch)
if __name__ == "__main__":
main()