import requests import time import csv import os import sys import pandas as pd from github_tokens import init_rest_client_auth tokens: list[str] = [] authorization_headers: list[dict[str, str]] = [] token_index = 0 last_request_time = {} # Tracks last request time per token def _ensure_auth() -> None: global tokens, authorization_headers if not tokens: tokens, authorization_headers = init_rest_client_auth() def makeRequest(api_url, params): global token_index _ensure_auth() num_tries = 0 max_tries = 3 while True: num_tries += 1 if num_tries > max_tries: print(' -- Max retries reached. Exiting...', end='') break # Find the first available token available_token = None current_time = time.time() for i in range(len(authorization_headers)): if i not in last_request_time or (current_time - last_request_time[i] >= 1): available_token = i break if available_token is None: min_wait = min(last_request_time.values()) + 1 - current_time time.sleep(max(min_wait, 1)) continue token_index = available_token headers = authorization_headers[token_index] last_request_time[token_index] = time.time() while True: try: response = requests.get(api_url, headers=headers, params=params, timeout=30) break except requests.exceptions.RequestException as e: print(f' -- Request error: {e}. Retrying in 60 seconds...', end='') time.sleep(60) except Exception as e: print(f' -- Another request error: {e}. Retrying in 60 seconds...', end='') time.sleep(60) if response.status_code == 200: return response.json() elif response.status_code == 403 and ('message' in response.json() and 'rate limit' in response.json()['message'].lower()): last_request_time[token_index] = time.time() elif response.status_code == 422 or response.status_code == 401: return None else: print(f' -- Request failed with status code {response.status_code}. Retrying... ' + api_url, end='') time.sleep(1) def search_repo_commits_by_ci_file_path(repo_name, ci_file_path, csv_file, csv_writer): ''' Perform a GitHub Search API query for commits per repository based on the path to a CI configuration file. Write results directly to a file. ''' GITHUB_API_URL = f'https://api.github.com/repos/{repo_name}/commits' page = 1 per_page = 100 num_commits = 0 while True: params = { 'path': ci_file_path, 'per_page': per_page, 'page': page, } data = makeRequest(GITHUB_API_URL, params) if not data or len(data) == 0: #print(f'No commits found.') return num_commits #print(f' Page {page} for query: {GITHUB_API_URL}?path={ci_file_path}&per_page={per_page}&page={page}') for commit in data: num_commits += 1 commit_info = { 'repo_name': repo_name, 'configuration_file': ci_file_path, 'commit_sha': commit['sha'], 'parent_sha': ', '.join([parent['sha'] for parent in commit['parents']]) if commit['parents'] else '', 'commit_message': commit['commit']['message'].lstrip().rstrip().replace('\n', '\\n'), 'author_login': commit['author']['login'] if commit['author'] else '', 'author_name': commit['commit']['author']['name'], 'author_email': commit['commit']['author']['email'], 'author_date': commit['commit']['author']['date'], 'committer_login': commit['committer']['login'] if commit['committer'] else '', 'committer_name': commit['commit']['committer']['name'], 'committer_email': commit['commit']['committer']['email'], 'committer_date': commit['commit']['committer']['date'], 'comment_count': commit['commit']['comment_count'] } csv_writer.writerow(commit_info.values()) csv_file.flush() if len(data) < per_page or page == 10: break page += 1 if page == 10 and len(data) == 100: print('[This request has more than 1000 results]') return num_commits if __name__ == '__main__': last_stopped_repo = 'immu0001/Udacity-Data-Engineer-nanodegree' # Last one for all services input_path = f'../Data/all_DE_repositories.csv' commits_output_path = f'../Data/DE_commits_per_ci_files.csv' repos_ci_output_path = f'../Data/DE_ci_services.csv' ci_file_paths = { # Keep in sync with ci-services.tex (ICSME data paper Table). '.github/workflows': 'GitHub Actions', '.travis.yml': 'Travis CI', 'circle.yml': 'CircleCI', '.circleci/config.yml': 'CircleCI', '.gitlab-ci.yml': 'GitLab', '.appveyor.yml': 'AppVeyor', 'appveyor.yml': 'AppVeyor', 'azure-pipelines.yml': 'Azure Pipelines', 'bitbucket-pipelines.yml': 'Bitbucket', '.cirrus.yml': 'Cirrus', '.scrutinizer.yml': 'Scrutinizer CI', 'codeship-services.yml': 'Codeship', '.semaphore/semaphore.yml': 'Semaphore', 'wercker.yml': 'Wercker', 'Jenkinsfile': 'Jenkins', 'bitrise.yml': 'Bitrise', 'bamboo.yml': 'Bamboo', '.gocd.yaml': 'GoCD', 'codemagic.yaml': 'Codemagic', } first_commits_time_csv = True if not os.path.exists(commits_output_path) else False commits_csv_file = open(commits_output_path, 'a', newline='', encoding='utf-8') commits_csv_writer = csv.writer(commits_csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) if first_commits_time_csv: commits_csv_writer.writerow(['repo_name', 'language', 'configuration_file', 'commit_sha', 'parent_sha', 'commit_message', 'author_login', 'author_name', 'author_email', 'author_date', 'committer_login', 'committer_name', 'committer_email', 'committer_date', 'comment_count']) commits_csv_file.flush() first_time_repos_ci_mapping_csv = True if not os.path.exists(repos_ci_output_path) else False repos_ci_csv_file = open(repos_ci_output_path, 'a', newline='', encoding='utf-8') repos_ci_csv_writer = csv.writer(repos_ci_csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) if first_time_repos_ci_mapping_csv: repos_ci_csv_writer.writerow(['repo_name', 'language', 'ci_services_count', 'ci_services_list'] + list(ci_file_paths.keys())) repos_ci_csv_file.flush() chunksize = 1000 row_id = -1 search_started = False print('Waiting to reach the last repo we stopped at last run...') for repos_df in pd.read_csv(input_path, chunksize=chunksize): for _, repo in repos_df.iterrows(): row_id += 1 if last_stopped_repo == '' or repo['full_name'] == last_stopped_repo: # Last repo we stopped at last run search_started = True if not search_started: continue print(f'{row_id+1}: {repo['full_name']}') ci_services_commit_counts = [] ci_services_list = [] for ci_file_path, ci_service_name in ci_file_paths.items(): print(f' -> {ci_file_path} ', end='') num_commits = search_repo_commits_by_ci_file_path(repo['full_name'], ci_file_path, csv_file=commits_csv_file, csv_writer=commits_csv_writer) ci_services_commit_counts.append(num_commits if num_commits > 0 else '') ci_services_list += [ci_service_name] if num_commits > 0 and ci_service_name not in ci_services_list else [] print(f'[{num_commits}]' if num_commits > 0 else '') if len(ci_services_list) > 0: repos_ci_csv_writer.writerow([repo['full_name'], repo['language'], len(ci_services_list), ci_services_list] + ci_services_commit_counts) repos_ci_csv_file.flush()