Created
February 8, 2025 14:25
-
-
Save MtkN1/582da4561ee5387de55f3666bb52b896 to your computer and use it in GitHub Desktop.
Retrieve GitHub repository archive and extract it to the expected directory.
This file contains hidden or 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
# /// script | |
# requires-python = ">=3" | |
# dependencies = [] | |
# /// | |
from __future__ import annotations | |
import shutil | |
import tarfile | |
import urllib.request | |
from pathlib import Path | |
from tempfile import TemporaryDirectory | |
from typing import TYPE_CHECKING | |
if TYPE_CHECKING: | |
from http.client import HTTPResponse | |
TARGET_TAG = "v3.11.12" | |
def main() -> None: | |
"""Retrieve GitHub repository archive and extract it to the expected directory.""" | |
owner = "aio-libs" | |
repo = "aiohttp" | |
url = f"https://github.com/{owner}/{repo}/archive/refs/tags/{TARGET_TAG}.tar.gz" | |
downloads_dir = Path("downloads") | |
expected_dir = downloads_dir / repo | |
response: HTTPResponse | |
with TemporaryDirectory() as temp_dir: | |
with ( | |
urllib.request.urlopen(url) as response, | |
tarfile.open(fileobj=response, mode="r:gz") as tar, | |
): | |
tar.extractall(temp_dir, filter="data") | |
remote_filename = response.headers.get_filename() | |
if remote_filename is None: | |
raise FileNotFoundError | |
predicted_dirname = remote_filename.removesuffix(".tar.gz") | |
predicted_dir = Path(temp_dir, predicted_dirname) | |
if not predicted_dir.is_dir(): | |
raise FileNotFoundError | |
if expected_dir.exists(): | |
shutil.rmtree(expected_dir) | |
expected_dir.parent.mkdir(parents=True, exist_ok=True) | |
predicted_dir.rename(expected_dir) | |
print(f"Downloaded {repo} {TARGET_TAG} to {expected_dir}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment