|
| 1 | +import os |
| 2 | +import sys |
| 3 | +import re |
| 4 | +import itertools |
| 5 | +import requests |
| 6 | +import hashlib |
| 7 | + |
| 8 | +from urllib.parse import quote |
| 9 | +from pathlib import Path |
| 10 | +from github import Github |
| 11 | +from typing import List, Dict |
| 12 | + |
| 13 | +HTML_TEMPLATE = """<!DOCTYPE html> |
| 14 | + <html> |
| 15 | + <head> |
| 16 | + <title>{package_name}</title> |
| 17 | + </head> |
| 18 | + <body> |
| 19 | + <h1>{package_name}</h1> |
| 20 | + {package_links} |
| 21 | + </body> |
| 22 | + </html> |
| 23 | +""" |
| 24 | + |
| 25 | +def normalize(name): |
| 26 | + """Normalize package name according to PEP 503.""" |
| 27 | + return re.sub(r"[-_.]+", "-", name).lower() |
| 28 | + |
| 29 | +def calculate_sha256(file_path): |
| 30 | + with open(file_path, "rb") as f: |
| 31 | + digest = hashlib.file_digest(f, "sha256") |
| 32 | + |
| 33 | + return digest.hexdigest() |
| 34 | + |
| 35 | +class PackageIndexBuilder: |
| 36 | + def __init__(self, token: str, repo_name: str, output_dir: str): |
| 37 | + self.github = Github(token) |
| 38 | + self.repo = self.github.get_repo(repo_name) |
| 39 | + self.output_dir = Path(output_dir) |
| 40 | + self.packages: Dict[str, List[Dict]] = {} |
| 41 | + |
| 42 | + # Set up authenticated session |
| 43 | + self.session = requests.Session() |
| 44 | + self.session.headers.update({ |
| 45 | + "Authorization": f"token {token}", |
| 46 | + "Accept": "application/octet-stream", |
| 47 | + }) |
| 48 | + |
| 49 | + def collect_packages(self): |
| 50 | + |
| 51 | + print ("Query release assets") |
| 52 | + |
| 53 | + for release in self.repo.get_releases(): |
| 54 | + for asset in release.get_assets(): |
| 55 | + if asset.name.endswith(('.whl', '.tar.gz')): |
| 56 | + package_name = normalize(asset.name.split('-')[0]) |
| 57 | + if package_name not in self.packages: |
| 58 | + self.packages[package_name] = [] |
| 59 | + |
| 60 | + self.packages[package_name].append({ |
| 61 | + 'filename': asset.name, |
| 62 | + 'url': asset.url, |
| 63 | + 'size': asset.size, |
| 64 | + 'upload_time': asset.created_at.strftime('%Y-%m-%d %H:%M:%S'), |
| 65 | + }) |
| 66 | + |
| 67 | + def generate_index_html(self): |
| 68 | + # Generate main index |
| 69 | + package_list = self.packages.keys() |
| 70 | + main_index = HTML_TEMPLATE.format( |
| 71 | + package_name="Simple Package Index", |
| 72 | + package_links="\n".join([f'<a href="{x}/">{x}</a><br/>' for x in package_list]) |
| 73 | + ) |
| 74 | + |
| 75 | + with open(self.output_dir / "index.html", "w") as f: |
| 76 | + f.write(main_index) |
| 77 | + |
| 78 | + for package, assets in self.packages.items(): |
| 79 | + |
| 80 | + package_dir = self.output_dir / package |
| 81 | + package_dir.mkdir(exist_ok=True) |
| 82 | + |
| 83 | + # Generate package-specific index.html |
| 84 | + file_links = [] |
| 85 | + assets = sorted(assets, key=lambda x: x["filename"]) |
| 86 | + for filename, items in itertools.groupby(assets, key=lambda x: x["filename"]): |
| 87 | + url = next(items)['url'] |
| 88 | + |
| 89 | + # Download the file |
| 90 | + with open(package_dir / filename, 'wb') as f: |
| 91 | + print (f"Downloading '{filename}' from '{url}'") |
| 92 | + response = self.session.get(url, stream=True) |
| 93 | + response.raise_for_status() |
| 94 | + for chunk in response.iter_content(chunk_size=8192): |
| 95 | + if chunk: |
| 96 | + f.write(chunk) |
| 97 | + |
| 98 | + sha256_hash = calculate_sha256(package_dir / filename) |
| 99 | + file_links.append(f'<a href="{quote(filename)}#sha256={sha256_hash}">{filename}</a><br/>') |
| 100 | + |
| 101 | + package_index = HTML_TEMPLATE.format( |
| 102 | + package_name=f"Links for {package}", |
| 103 | + package_links="\n".join(file_links) |
| 104 | + ) |
| 105 | + |
| 106 | + with open(package_dir / "index.html", "w") as f: |
| 107 | + f.write(package_index) |
| 108 | + |
| 109 | + def build(self): |
| 110 | + # Create output directory |
| 111 | + self.output_dir.mkdir(parents=True, exist_ok=True) |
| 112 | + |
| 113 | + # Collect and generate |
| 114 | + self.collect_packages() |
| 115 | + self.generate_index_html() |
| 116 | + |
| 117 | + |
| 118 | +def main(): |
| 119 | + # Get environment variables |
| 120 | + token = os.environ.get("GITHUB_TOKEN") |
| 121 | + repo = os.environ.get("GITHUB_REPOSITORY") |
| 122 | + print (repo) |
| 123 | + output_dir = os.environ.get("OUTPUT_DIR", "dist") |
| 124 | + |
| 125 | + if not all([token, repo]): |
| 126 | + print ("Missing required environment variables") |
| 127 | + sys.exit(1) |
| 128 | + |
| 129 | + builder = PackageIndexBuilder(token, repo, output_dir) |
| 130 | + builder.build() |
| 131 | + |
| 132 | +if __name__ == "__main__": |
| 133 | + main() |
0 commit comments