File size: 11,185 Bytes
590e1e5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
import os
import subprocess
from openpyxl import Workbook
from git import Repo
import os
import shutil
import tempfile
import uuid
import re
def remove_cpp_comments(code):
# Remove multi-line comments
code = re.sub(r'/\*[\s\S]*?\*/', '', code)
# Remove single-line comments
code = re.sub(r'//.*', '', code)
# Remove empty lines
code = '\n'.join(line for line in code.splitlines() if line.strip())
return code
def process_dataframe(df):
# Apply comment removal to both 'Code' and 'Unit Test - (Ground Truth)' columns
df['Code'] = df['Code'].apply(remove_cpp_comments)
df['Unit Test - (Ground Truth)'] = df['Unit Test - (Ground Truth)'].apply(remove_cpp_comments)
return df
# Initialize global ID counter
id_counter = 0
def get_remote_default_branch(repo_url):
try:
# Create a temporary directory
temp_dir = tempfile.mkdtemp()
repo = Repo.clone_from(repo_url, temp_dir, depth=1)
# Get the default branch name
default_branch = repo.active_branch.name
return default_branch
except Exception as e:
print(f"Error: {e}")
return None
finally:
# Clean up the temporary directory
shutil.rmtree(temp_dir)
def clone_repo(repo_url: str, local_path: str) -> str:
"""
Clone a Git repository to a local path if it doesn't exist.
Determine the default branch (either 'main', 'master', or another default) of the repository.
Args:
repo_url (str): The URL of the Git repository.
local_path (str): The local path where the repository should be cloned.
Returns:
str: The name of the default branch of the repository.
"""
if not os.path.exists(local_path):
subprocess.run(['git', 'clone', repo_url, local_path], check=True)
def get_commit_hash(repo_path: str) -> str:
"""
Get the latest commit hash of a repository.
Args:
repo_path (str): The local path of the repository.
Returns:
str: The latest commit hash.
"""
result = subprocess.run(['git', '-C', repo_path, 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, check=True)
return result.stdout.decode('utf-8').strip()
def find_files(directory: str, extensions: list) -> dict:
"""
Find files with specific extensions within a directory.
Args:
directory (str): The directory to search within.
extensions (list): A list of file extensions to search for.
Returns:
dict: A dictionary where keys are file extensions and values are lists of file paths.
"""
found_files = {ext: [] for ext in extensions}
for root, _, files in os.walk(directory):
for file in files:
for ext in extensions:
if file.endswith(ext):
found_files[ext].append(os.path.join(root, file))
return found_files
def group_files_by_basename(files_dict: dict) -> dict:
"""
Group files by their base name, associating code files with their corresponding test files.
Args:
files_dict (dict): A dictionary of lists of file paths, categorized by extensions.
Returns:
dict: A dictionary where keys are base names of files and values are dictionaries of file paths.
"""
grouped_files = {}
for ext in ['.cc', '.h']:
for file_path in files_dict.get(ext, []):
base_name = os.path.basename(file_path).replace(ext, '')
if base_name not in grouped_files:
grouped_files[base_name] = {}
grouped_files[base_name][ext] = file_path
for ext in ['_test.cc', '_unittest.cc']:
for file_path in files_dict.get(ext, []):
base_name = os.path.basename(file_path).replace(ext, '')
if base_name not in grouped_files:
grouped_files[base_name] = {}
grouped_files[base_name][ext] = file_path
# Filter out entries without test files
grouped_files_with_tests = {
k: v for k, v in grouped_files.items() if '_test.cc' in v or '_unittest.cc' in v
}
return grouped_files_with_tests
def read_file_content(file_path: str) -> str:
"""
Read the content of a file.
Args:
file_path (str): The path to the file.
Returns:
str: The content of the file.
"""
with open(file_path, 'r') as file:
return file.read()
def process_repo(repo_url: str, local_path: str, default_branch: str) -> list:
"""
Process a repository by finding files, reading content, and generating data for each file.
Args:
repo_url (str): The URL of the Git repository.
local_path (str): The local path of the repository.
default_branch (str): The default branch of the repository.
Returns:
list: A list of file data dictionaries.
"""
codebases_path = 'codebases'
os.makedirs(codebases_path, exist_ok=True)
repo_local_path = os.path.join(codebases_path, local_path)
clone_repo(repo_url, repo_local_path)
# Get the latest commit hash
commit_hash = get_commit_hash(repo_local_path)
repo_directory = repo_local_path
extensions = ['.cc', '.h', '_test.cc', '_unittest.cc']
files_dict = find_files(repo_directory, extensions)
grouped_files = group_files_by_basename(files_dict)
file_data_list = []
for base_name, file_group in grouped_files.items():
code_content = ""
file_path = ""
unit_test_content = ""
unit_test_path = ""
if '.cc' in file_group or '.h' in file_group:
if '.cc' in file_group:
code_content += read_file_content(file_group['.cc']) + "\n"
file_path = file_group['.cc']
elif '.h' in file_group:
code_content += read_file_content(file_group['.h']) + "\n"
file_path = file_group['.h']
if '_test.cc' in file_group:
unit_test_content = read_file_content(file_group['_test.cc'])
unit_test_path = file_group['_test.cc']
elif '_unittest.cc' in file_group:
unit_test_content = read_file_content(file_group['_unittest.cc'])
unit_test_path = file_group['_unittest.cc']
relative_file_path = os.path.relpath(file_path, repo_directory)
relative_unit_test_path = os.path.relpath(unit_test_path, repo_directory)
# Generate a unique identifier (UID)
unique_id = str(uuid.uuid4())
file_data_list.append({
'id': unique_id, # Use UID instead of sequential ID
'language': 'cpp',
'repository_name': f'{repo_url.split("/")[-2]}/{repo_url.split("/")[-1].replace(".git", "")}',
'file_name': base_name,
'file_path_in_repository': relative_file_path,
'file_path_for_unit_test': relative_unit_test_path,
'Code': code_content.strip(),
'Unit Test': unit_test_content.strip(),
'Code Url': f'https://github.com/{repo_url.split("/")[-2]}/{repo_url.split("/")[-1].replace(".git", "")}/blob/{default_branch}/{relative_file_path}',
'Test Code Url': f'https://github.com/{repo_url.split("/")[-2]}/{repo_url.split("/")[-1].replace(".git", "")}/blob/{default_branch}/{relative_unit_test_path}',
'Commit Hash': commit_hash
})
return file_data_list
def save_dict_to_excel(data_dict: dict, output_file: str):
"""
Save a dictionary to an Excel file.
Args:
data_dict (dict): The dictionary to save, with keys as the first column and values as the second.
output_file (str): The path to the output Excel file.
"""
wb = Workbook()
ws = wb.active
ws.title = "Dictionary Data"
# Add headers
ws.append(['Key', 'Value'])
# Append dictionary data
for key, value in data_dict.items():
ws.append([key, value])
# Save the workbook
wb.save(output_file)
print(f"Dictionary has been written to {output_file}")
def save_to_excel(file_data_list: list, output_file: str):
"""
Save the collected file data to an Excel file.
Args:
file_data_list (list): A list of dictionaries containing file data.
output_file (str): The path to the output Excel file.
"""
wb = Workbook()
ws = wb.active
ws.title = "Unit Test Data"
header = [
'ID', 'Language', 'Repository Name', 'File Name',
'File Path in Repository', 'File Path for Unit Test',
'Code', 'Unit Test - (Ground Truth)', 'Code Url', 'Test Code Url', 'Commit Hash'
]
ws.append(header)
for file_data in file_data_list:
ws.append([
file_data['id'],
file_data['language'],
file_data['repository_name'],
file_data['file_name'],
file_data['file_path_in_repository'],
file_data['file_path_for_unit_test'],
file_data['Code'],
file_data['Unit Test'],
file_data['Code Url'],
file_data['Test Code Url'],
file_data['Commit Hash']
])
wb.save(output_file)
print(f"File data has been written to {output_file}")
def combine_repo_data(repo_urls: list):
"""
Combine data from multiple repositories and save it to an Excel file.
Args:
repo_urls (list): A list of Git repository URLs.
"""
all_file_data = []
global_id_counter = 0
# Map for storing repo names and commit hashes
repo_commit_map = {}
for repo_url in repo_urls:
repo_name = repo_url.split("/")[-1].replace(".git", "")
default_branch = get_remote_default_branch(repo_url)
print(repo_url)
print(default_branch)
file_data = process_repo(repo_url, repo_name, default_branch)
all_file_data.extend(file_data)
# Store the commit hash for this repo
repo_commit_map[repo_name] = get_commit_hash(os.path.join('codebases', repo_name))
# Save data to Excel
output_file = 'combined_repo_data.xlsx'
save_to_excel(all_file_data, output_file)
# Print or save the repo-commit hash map for reproducibility
print("Repository and Commit Hash Map:")
for repo, commit_hash in repo_commit_map.items():
print(f"{repo}: {commit_hash}")
save_dict_to_excel(repo_commit_map, 'repo_commit_map.xlsx')
repo_urls = [
'https://github.com/google/googletest.git',
'https://github.com/google/libaddressinput.git',
'https://github.com/abseil/abseil-cpp.git',
'https://github.com/google/libphonenumber.git',
'https://github.com/google/langsvr.git',
'https://github.com/google/tensorstore.git',
'https://github.com/google/arolla.git',
# 'https://github.com/pytorch/pytorch.git',
'https://github.com/tensorflow/tensorflow.git',
'https://github.com/google/glog.git',
'https://github.com/google/leveldb.git',
'https://github.com/google/tsl.git',
'https://github.com/google/quiche.git',
'https://github.com/google/cel-cpp.git'
]
combine_repo_data(repo_urls)
|