|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Download the latest published LoopAI UI dist from GitHub Releases.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import json |
| 8 | +import os |
| 9 | +import shutil |
| 10 | +import sys |
| 11 | +import tarfile |
| 12 | +import tempfile |
| 13 | +import urllib.error |
| 14 | +import urllib.request |
| 15 | +import zipfile |
| 16 | +from pathlib import Path |
| 17 | + |
| 18 | + |
| 19 | +DEFAULT_REPO = "OpenDCAI/Dataflow-LoopAI" |
| 20 | +DEFAULT_TAG_PREFIX = "ui-v" |
| 21 | +DEFAULT_ASSET_NAMES = ("loopai-ui-dist.tar.gz", "loopai-ui-dist.zip") |
| 22 | +ROOT_DIR = Path(__file__).resolve().parents[1] |
| 23 | +DEFAULT_OUTPUT_DIR = ROOT_DIR / "api" / "dist" |
| 24 | + |
| 25 | + |
| 26 | +def request_json(url: str, token: str | None) -> object: |
| 27 | + request = urllib.request.Request( |
| 28 | + url, |
| 29 | + headers={ |
| 30 | + "Accept": "application/vnd.github+json", |
| 31 | + "User-Agent": "Dataflow-LoopAI-ui-release-downloader", |
| 32 | + **({"Authorization": f"Bearer {token}"} if token else {}), |
| 33 | + }, |
| 34 | + ) |
| 35 | + with urllib.request.urlopen(request, timeout=30) as response: |
| 36 | + return json.load(response) |
| 37 | + |
| 38 | + |
| 39 | +def download_file(url: str, target: Path, token: str | None) -> None: |
| 40 | + request = urllib.request.Request( |
| 41 | + url, |
| 42 | + headers={ |
| 43 | + "Accept": "application/octet-stream", |
| 44 | + "User-Agent": "Dataflow-LoopAI-ui-release-downloader", |
| 45 | + **({"Authorization": f"Bearer {token}"} if token else {}), |
| 46 | + }, |
| 47 | + ) |
| 48 | + with urllib.request.urlopen(request, timeout=60) as response: |
| 49 | + with target.open("wb") as handle: |
| 50 | + shutil.copyfileobj(response, handle) |
| 51 | + |
| 52 | + |
| 53 | +def find_release(repo: str, tag_prefix: str, include_prerelease: bool, token: str | None) -> dict: |
| 54 | + releases = request_json(f"https://api.github.com/repos/{repo}/releases?per_page=100", token) |
| 55 | + if not isinstance(releases, list): |
| 56 | + raise RuntimeError("GitHub releases response is not a list") |
| 57 | + |
| 58 | + for release in releases: |
| 59 | + if not isinstance(release, dict): |
| 60 | + continue |
| 61 | + tag_name = str(release.get("tag_name", "")) |
| 62 | + if tag_prefix and not tag_name.startswith(tag_prefix): |
| 63 | + continue |
| 64 | + if release.get("draft"): |
| 65 | + continue |
| 66 | + if release.get("prerelease") and not include_prerelease: |
| 67 | + continue |
| 68 | + return release |
| 69 | + |
| 70 | + raise RuntimeError(f"No public release found for {repo} with tag prefix {tag_prefix!r}") |
| 71 | + |
| 72 | + |
| 73 | +def find_asset(release: dict, asset_names: tuple[str, ...]) -> dict: |
| 74 | + assets = release.get("assets", []) |
| 75 | + if not isinstance(assets, list): |
| 76 | + raise RuntimeError("Release assets response is not a list") |
| 77 | + |
| 78 | + for asset_name in asset_names: |
| 79 | + for asset in assets: |
| 80 | + if isinstance(asset, dict) and asset.get("name") == asset_name: |
| 81 | + return asset |
| 82 | + |
| 83 | + for asset in assets: |
| 84 | + if not isinstance(asset, dict): |
| 85 | + continue |
| 86 | + name = str(asset.get("name", "")) |
| 87 | + if "ui" in name and name.endswith((".tar.gz", ".tgz", ".zip")): |
| 88 | + return asset |
| 89 | + |
| 90 | + names = ", ".join(str(asset.get("name", "")) for asset in assets if isinstance(asset, dict)) |
| 91 | + raise RuntimeError(f"No UI dist asset found in release {release.get('tag_name')}. Assets: {names}") |
| 92 | + |
| 93 | + |
| 94 | +def extract_archive(archive_path: Path, extract_dir: Path) -> None: |
| 95 | + name = archive_path.name |
| 96 | + if name.endswith((".tar.gz", ".tgz")): |
| 97 | + with tarfile.open(archive_path, "r:gz") as archive: |
| 98 | + archive.extractall(extract_dir) |
| 99 | + return |
| 100 | + if name.endswith(".zip"): |
| 101 | + with zipfile.ZipFile(archive_path) as archive: |
| 102 | + archive.extractall(extract_dir) |
| 103 | + return |
| 104 | + raise RuntimeError(f"Unsupported archive type: {archive_path.name}") |
| 105 | + |
| 106 | + |
| 107 | +def locate_dist_dir(extract_dir: Path) -> Path: |
| 108 | + candidates = [extract_dir, *extract_dir.rglob("dist")] |
| 109 | + for candidate in candidates: |
| 110 | + if (candidate / "index.html").is_file(): |
| 111 | + return candidate |
| 112 | + for candidate in extract_dir.rglob("index.html"): |
| 113 | + return candidate.parent |
| 114 | + raise RuntimeError("Downloaded archive does not contain index.html") |
| 115 | + |
| 116 | + |
| 117 | +def replace_dist(source_dir: Path, output_dir: Path) -> None: |
| 118 | + output_dir.parent.mkdir(parents=True, exist_ok=True) |
| 119 | + staging_dir = output_dir.with_name(f".{output_dir.name}.staging") |
| 120 | + backup_dir = output_dir.with_name(f".{output_dir.name}.backup") |
| 121 | + |
| 122 | + if staging_dir.exists(): |
| 123 | + shutil.rmtree(staging_dir) |
| 124 | + if backup_dir.exists(): |
| 125 | + shutil.rmtree(backup_dir) |
| 126 | + |
| 127 | + shutil.copytree(source_dir, staging_dir) |
| 128 | + if output_dir.exists(): |
| 129 | + output_dir.rename(backup_dir) |
| 130 | + staging_dir.rename(output_dir) |
| 131 | + if backup_dir.exists(): |
| 132 | + shutil.rmtree(backup_dir) |
| 133 | + |
| 134 | + |
| 135 | +def parse_args() -> argparse.Namespace: |
| 136 | + parser = argparse.ArgumentParser(description=__doc__) |
| 137 | + parser.add_argument("--repo", default=DEFAULT_REPO, help="GitHub repo in owner/name form") |
| 138 | + parser.add_argument("--tag-prefix", default=DEFAULT_TAG_PREFIX, help="Release tag prefix for UI builds") |
| 139 | + parser.add_argument( |
| 140 | + "--asset-name", |
| 141 | + action="append", |
| 142 | + dest="asset_names", |
| 143 | + help="Expected release asset name. Can be passed multiple times.", |
| 144 | + ) |
| 145 | + parser.add_argument("--output-dir", default=str(DEFAULT_OUTPUT_DIR), help="Where to install the dist files") |
| 146 | + parser.add_argument("--include-prerelease", action="store_true", help="Allow prerelease UI builds") |
| 147 | + return parser.parse_args() |
| 148 | + |
| 149 | + |
| 150 | +def main() -> int: |
| 151 | + args = parse_args() |
| 152 | + token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") |
| 153 | + asset_names = tuple(args.asset_names or DEFAULT_ASSET_NAMES) |
| 154 | + output_dir = Path(args.output_dir).resolve() |
| 155 | + |
| 156 | + try: |
| 157 | + release = find_release(args.repo, args.tag_prefix, args.include_prerelease, token) |
| 158 | + asset = find_asset(release, asset_names) |
| 159 | + download_url = asset.get("browser_download_url") |
| 160 | + if not download_url: |
| 161 | + raise RuntimeError(f"Asset {asset.get('name')} has no browser_download_url") |
| 162 | + |
| 163 | + with tempfile.TemporaryDirectory(prefix="loopai-ui-dist-") as temp_dir_name: |
| 164 | + temp_dir = Path(temp_dir_name) |
| 165 | + archive_path = temp_dir / str(asset["name"]) |
| 166 | + download_file(str(download_url), archive_path, token) |
| 167 | + |
| 168 | + extract_dir = temp_dir / "extract" |
| 169 | + extract_dir.mkdir() |
| 170 | + extract_archive(archive_path, extract_dir) |
| 171 | + dist_dir = locate_dist_dir(extract_dir) |
| 172 | + replace_dist(dist_dir, output_dir) |
| 173 | + |
| 174 | + print(f"Installed UI {release.get('tag_name')} from {asset.get('name')} into {output_dir}") |
| 175 | + return 0 |
| 176 | + except (RuntimeError, urllib.error.URLError, urllib.error.HTTPError) as exc: |
| 177 | + print(f"download_ui_release.py: {exc}", file=sys.stderr) |
| 178 | + return 1 |
| 179 | + |
| 180 | + |
| 181 | +if __name__ == "__main__": |
| 182 | + raise SystemExit(main()) |
0 commit comments