|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import re |
| 6 | +import json |
| 7 | +import requests |
| 8 | + |
| 9 | +def get(url, file_name=None, dir_name=None): |
| 10 | + ''' |
| 11 | + Get the files in the given URL |
| 12 | + :param url: The URL is a github API URL that returns a JSON object |
| 13 | + :param file_name: if specified, url will be github download_url |
| 14 | + :return: None |
| 15 | + :raises: Exception if the download fails |
| 16 | + ''' |
| 17 | + try: |
| 18 | + response = requests.get(url) |
| 19 | + response.raise_for_status() |
| 20 | + except requests.exceptions.RequestException as e: |
| 21 | + raise Exception(f"Request failed: {e}") |
| 22 | + |
| 23 | + if file_name: |
| 24 | + with open(file_name, 'wb') as file: |
| 25 | + file.write(response.content) |
| 26 | + return |
| 27 | + |
| 28 | + def get_file(file): |
| 29 | + if file['download_url']: |
| 30 | + get(file['download_url'], file_name=file['name']) |
| 31 | + else: |
| 32 | + if file['type'] == 'dir': |
| 33 | + get(file['url'], dir_name=file['name']) |
| 34 | + else: |
| 35 | + get(file['git_url'].replace('/git/trees/', '/contents?ref=')) |
| 36 | + |
| 37 | + try: |
| 38 | + data = response.json() |
| 39 | + except json.JSONDecodeError as e: |
| 40 | + raise Exception(f"JSON decode error: {e}") |
| 41 | + |
| 42 | + if isinstance(data, list): |
| 43 | + if not dir_name: |
| 44 | + pattern = r"https://api\.github\.com/repos/[^/]+/([^/]+)/contents(.*)" |
| 45 | + repo_name, path = re.search(pattern, url).groups() |
| 46 | + path = path.split('/')[-1].split('?')[0] |
| 47 | + dir_name = path if path else repo_name |
| 48 | + |
| 49 | + cur = os.getcwd() |
| 50 | + os.mkdir(dir_name) |
| 51 | + os.chdir(dir_name) |
| 52 | + for item in data: |
| 53 | + get_file(item) |
| 54 | + os.chdir(cur) |
| 55 | + else: |
| 56 | + get_file(data) |
| 57 | + |
| 58 | +def help(): |
| 59 | + print(f"Usage: {sys.argv[0]} <github REST API url>") |
| 60 | + print(" url format: https://api.github.com/repos/{owner}/{repo}/contents/{directory}?ref={branch}") |
| 61 | + print(f" url example: https://api.github.com/repos/sonic-net/DASH/contents/dash-pipeline/utils?ref=main") |
| 62 | + sys.exit(1) |
| 63 | + |
| 64 | +if __name__ == '__main__': |
| 65 | + if len(sys.argv) < 2 or sys.argv[1] == '-h': |
| 66 | + help() |
| 67 | + |
| 68 | + try: |
| 69 | + get(sys.argv[1]) |
| 70 | + except Exception as e: |
| 71 | + print(e) |
| 72 | + sys.exit(1) |
0 commit comments