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