|
| 1 | +"""Functions to get GitHub downloads from GitHub.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +import os |
| 5 | +from collections import defaultdict |
| 6 | + |
| 7 | +import pandas as pd |
| 8 | +from tqdm import tqdm |
| 9 | + |
| 10 | +from pymetrics.github import GithubClient |
| 11 | +from pymetrics.output import append_row, create_csv, get_path, load_csv |
| 12 | +from pymetrics.time_utils import drop_duplicates_by_date, get_current_utc |
| 13 | + |
| 14 | +LOGGER = logging.getLogger(__name__) |
| 15 | +dir_path = os.path.dirname(os.path.realpath(__file__)) |
| 16 | +TIME_COLUMN = 'timestamp' |
| 17 | + |
| 18 | +GITHUB_DOWNLOAD_COUNT_FILENAME = 'github_download_counts.csv' |
| 19 | + |
| 20 | + |
| 21 | +def get_previous_github_downloads(output_folder, dry_run=False): |
| 22 | + """Get previous GitHub Downloads.""" |
| 23 | + csv_path = get_path(output_folder, GITHUB_DOWNLOAD_COUNT_FILENAME) |
| 24 | + read_csv_kwargs = { |
| 25 | + 'parse_dates': [ |
| 26 | + TIME_COLUMN, |
| 27 | + 'created_at', |
| 28 | + ], |
| 29 | + 'dtype': { |
| 30 | + 'ecosystem_name': pd.CategoricalDtype(), |
| 31 | + 'org_repo': pd.CategoricalDtype(), |
| 32 | + 'tag_name': pd.CategoricalDtype(), |
| 33 | + 'prerelease': pd.BooleanDtype(), |
| 34 | + 'download_count': pd.Int64Dtype(), |
| 35 | + }, |
| 36 | + } |
| 37 | + data = load_csv(csv_path, read_csv_kwargs=read_csv_kwargs) |
| 38 | + return data |
| 39 | + |
| 40 | + |
| 41 | +def collect_github_downloads( |
| 42 | + projects: dict[str, list[str]], output_folder: str, dry_run: bool = False, verbose: bool = False |
| 43 | +): |
| 44 | + """Pull data about the downloads of a GitHub project. |
| 45 | +
|
| 46 | + Args: |
| 47 | + projects (dict[str, list[str]]): |
| 48 | + List of projects to analyze. Each key is the name of the ecosystem, and |
| 49 | + each value is a list of github repositories (including organization). |
| 50 | + output_folder (str): |
| 51 | + Folder in which project downloads will be stored. |
| 52 | + It can be passed as a local folder or as a Google Drive path in the format |
| 53 | + `gdrive://{folder_id}`. |
| 54 | + The folder must contain 'github_download_counts.csv' |
| 55 | + dry_run (bool): |
| 56 | + If `True`, do not upload the results. Defaults to `False`. |
| 57 | + verbose (bool): |
| 58 | + If `True`, will output dataframes heads of github download data. Defaults to `False`. |
| 59 | + """ |
| 60 | + overall_df = get_previous_github_downloads(output_folder=output_folder) |
| 61 | + |
| 62 | + gh_client = GithubClient() |
| 63 | + download_counts = defaultdict(int) |
| 64 | + |
| 65 | + for ecosystem_name, repositories in projects.items(): |
| 66 | + for org_repo in tqdm(repositories, position=1, desc=f'Ecosystem: {ecosystem_name}'): |
| 67 | + pages_remain = True |
| 68 | + page = 1 |
| 69 | + per_page = 100 |
| 70 | + download_counts[org_repo] = 0 |
| 71 | + |
| 72 | + github_org = org_repo.split('/')[0] |
| 73 | + repo = org_repo.split('/')[1] |
| 74 | + |
| 75 | + while pages_remain is True: |
| 76 | + response = gh_client.get( |
| 77 | + github_org, |
| 78 | + repo, |
| 79 | + endpoint='releases', |
| 80 | + query_params={'per_page': per_page, 'page': page}, |
| 81 | + ) |
| 82 | + release_data = response.json() |
| 83 | + link_header = response.headers.get('link') |
| 84 | + |
| 85 | + if response.status_code == 404: |
| 86 | + LOGGER.debug(f'Skipping: {org_repo} because org/repo does not exist') |
| 87 | + pages_remain = False |
| 88 | + break |
| 89 | + |
| 90 | + # Get download count |
| 91 | + for release_info in tqdm( |
| 92 | + release_data, position=0, desc=f'{repo} releases, page={page}' |
| 93 | + ): |
| 94 | + release_id = release_info.get('id') |
| 95 | + tag_name = release_info.get('tag_name') |
| 96 | + prerelease = release_info.get('prerelease') |
| 97 | + created_at = release_info.get('created_at') |
| 98 | + endpoint = f'releases/{release_id}' |
| 99 | + |
| 100 | + timestamp = get_current_utc() |
| 101 | + response = gh_client.get(github_org, repo, endpoint=endpoint) |
| 102 | + data = response.json() |
| 103 | + assets = data.get('assets') |
| 104 | + |
| 105 | + tag_row = { |
| 106 | + 'ecosystem_name': [ecosystem_name], |
| 107 | + 'org_repo': [org_repo], |
| 108 | + 'timestamp': [timestamp], |
| 109 | + 'tag_name': [tag_name], |
| 110 | + 'prerelease': [prerelease], |
| 111 | + 'created_at': [created_at], |
| 112 | + 'download_count': 0, |
| 113 | + } |
| 114 | + if assets and len(assets) > 0: |
| 115 | + for asset in assets: |
| 116 | + tag_row['download_count'] += asset.get('download_count', 0) |
| 117 | + |
| 118 | + overall_df = append_row(overall_df, tag_row) |
| 119 | + |
| 120 | + # Check pagination |
| 121 | + if link_header and 'rel="next"' in link_header: |
| 122 | + page += 1 |
| 123 | + else: |
| 124 | + break |
| 125 | + overall_df = drop_duplicates_by_date( |
| 126 | + overall_df, |
| 127 | + time_column=TIME_COLUMN, |
| 128 | + group_by_columns=['ecosystem_name', 'org_repo', 'tag_name'], |
| 129 | + ) |
| 130 | + if verbose: |
| 131 | + LOGGER.info(f'{GITHUB_DOWNLOAD_COUNT_FILENAME} tail') |
| 132 | + LOGGER.info(overall_df.tail(5).to_string()) |
| 133 | + |
| 134 | + overall_df.to_csv('github_download_counts.csv', index=False) |
| 135 | + |
| 136 | + if not dry_run: |
| 137 | + gfolder_path = f'{output_folder}/{GITHUB_DOWNLOAD_COUNT_FILENAME}' |
| 138 | + create_csv(output_path=gfolder_path, data=overall_df) |
0 commit comments