forked from codedog-ai/codedog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_codedog.py
More file actions
executable file
·2226 lines (1874 loc) · 116 KB
/
run_codedog.py
File metadata and controls
executable file
·2226 lines (1874 loc) · 116 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import asyncio
import time
import traceback
import logging
from dotenv import load_dotenv
from typing import Any, Dict, List, Optional, Tuple
import os
import re
import sys
from datetime import datetime, timedelta
# Load environment variables from .env file
load_dotenv()
# Configure logger
logger = logging.getLogger(__name__)
from github import Github
from gitlab import Gitlab
from langchain_community.callbacks.manager import get_openai_callback
from codedog.actors.reporters.pull_request import PullRequestReporter
from codedog.chains import CodeReviewChain, PRSummaryChain, CodeReviewChainFactory
from codedog.retrievers import GithubRetriever, GitlabRetriever
from codedog.utils.langchain_utils import load_model_by_name
from codedog.utils.email_utils import send_report_email
from codedog.utils.git_hooks import install_git_hooks
from codedog.utils.git_log_analyzer import get_file_diffs_by_timeframe, get_commit_diff, CommitInfo
from codedog.utils.code_evaluator import DiffEvaluator, generate_evaluation_markdown, FileEvaluationResult, CodeEvaluation
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="CodeDog - AI-powered code review tool")
# Main operation subparsers
subparsers = parser.add_subparsers(dest="command", help="Command to run")
# Repository evaluation command (only command available)
repo_eval_parser = subparsers.add_parser("repo-eval", help="Evaluate all commits in a repository within a time period for all committers")
repo_eval_parser.add_argument("repo", help="Git repository path or name (e.g. owner/repo for remote repositories)")
repo_eval_parser.add_argument("--start-date", help="Start date (YYYY-MM-DD), defaults to 7 days ago")
repo_eval_parser.add_argument("--end-date", help="End date (YYYY-MM-DD), defaults to today")
repo_eval_parser.add_argument("--include", help="Included file extensions, comma separated, e.g. .py,.js")
repo_eval_parser.add_argument("--exclude", help="Excluded file extensions, comma separated, e.g. .md,.txt")
repo_eval_parser.add_argument("--model", help="Evaluation model, defaults to CODE_REVIEW_MODEL env var or gpt-3.5")
repo_eval_parser.add_argument("--email", help="Email addresses to send the report to (comma-separated)")
repo_eval_parser.add_argument("--output-dir", help="Directory to save reports, defaults to codedog_repo_eval_<date>")
repo_eval_parser.add_argument("--platform", choices=["github", "gitlab"], default="github",
help="Platform to use (github or gitlab, defaults to github)")
repo_eval_parser.add_argument("--gitlab-url", help="GitLab URL (defaults to https://gitlab.com or GITLAB_URL env var)")
repo_eval_parser.add_argument("--model-token-limit", type=int, default=45000, help="Model token limit for evaluation (default: 45000)")
return parser.parse_args()
def parse_emails(emails_str: Optional[str]) -> List[str]:
"""Parse comma-separated email addresses."""
if not emails_str:
return []
return [email.strip() for email in emails_str.split(",") if email.strip()]
def parse_extensions(extensions_str: Optional[str]) -> Optional[List[str]]:
"""Parse comma-separated file extensions."""
if not extensions_str:
return None
return [ext.strip() for ext in extensions_str.split(",") if ext.strip()]
def get_author_slug(author: str) -> str:
"""从作者名称中提取邮箱,用于文件名"""
# 从作者名称中提取邮箱,用于文件名
email_match = re.search(r'<([^>]+)>', author)
if email_match:
# 如果有邮箱,使用邮箱作为文件名的一部分
email = email_match.group(1)
# 提取邮箱用户名部分(去掉@及后面的域名)
email_username = email.split('@')[0] if '@' in email else email
author_slug = email_username.replace(".", "_").replace("-", "_")
else:
# 如果没有邮箱,使用作者名称
author_slug = author.replace("@", "_at_").replace(" ", "_").replace("/", "_").replace("<", "").replace(">", "")
return author_slug
def split_commits_into_batches(
commits: List[CommitInfo],
commit_file_diffs: Dict[str, Dict[str, str]],
model_token_limit: int,
safety_margin: float = 0.75 # 增加安全边际系数,更有效地利用模型token限制
) -> List[List[CommitInfo]]:
"""
将提交智能分割为多个批次,确保每个批次不超过模型的处理能力
Args:
commits: 提交列表
commit_file_diffs: 提交文件差异字典
model_token_limit: 模型的token限制
safety_margin: 安全边际系数(0-1)
Returns:
批次列表,每个批次包含多个提交
"""
safe_token_limit = int(model_token_limit * safety_margin)
batches = []
current_batch = []
current_tokens = 0
# 按时间顺序排序提交
sorted_commits = sorted(commits, key=lambda x: x.date)
# 提示模板的基本token数量(包括指令、格式说明等)
# 根据实际使用情况调整
base_prompt_tokens = 800
# 每个提交的元数据(提交哈希、消息等)的估计token数量
commit_metadata_tokens = 100
# 初始token计数包含基本提示
current_tokens = base_prompt_tokens
for commit in sorted_commits:
# 估算当前提交的token数量
commit_tokens = commit_metadata_tokens # 基本元数据
if commit.hash in commit_file_diffs:
for file_path, file_diff in commit_file_diffs[commit.hash].items():
# 更精确的token估算:
# 1. 代码比普通文本需要更多token(特殊字符、缩进等)
# 2. 使用字符数而不是单词数作为基础
# 3. 对不同类型的内容使用不同的系数
# 文件路径也消耗token
commit_tokens += len(file_path) * 0.5
# 估算diff内容的token
# 使用更高的系数 (1.5 而不是 1.3),因为代码通常有更多的特殊字符和结构
char_count = len(file_diff)
# 平均每个字符约0.33个token(更准确的估计)
diff_tokens = char_count * 0.33
# 添加一些额外的token用于diff格式和结构
diff_tokens += 50 # 每个文件的diff头部等
commit_tokens += diff_tokens
# 如果添加当前提交会超出限制,创建新批次
if current_tokens + commit_tokens > safe_token_limit and current_batch:
logger.info(f"Creating new batch at estimated {current_tokens} tokens (limit: {safe_token_limit})")
batches.append(current_batch)
current_batch = []
current_tokens = base_prompt_tokens # 重置为基本提示的token数
# 如果单个提交就超出限制,需要单独处理
if commit_tokens > safe_token_limit:
logger.warning(f"Large commit {commit.hash} with estimated {commit_tokens} tokens exceeds safe limit")
# 这种情况下,我们可以选择:
# 1. 单独评估这个提交
# 2. 将这个提交拆分为更小的部分
# 这里我们选择方案1,单独评估
if not current_batch: # 如果当前批次为空
batches.append([commit])
logger.info(f"Added large commit {commit.hash} as a separate batch")
else:
# 先保存当前批次
batches.append(current_batch)
logger.info(f"Saved current batch before processing large commit")
# 然后单独处理这个大提交
batches.append([commit])
logger.info(f"Added large commit {commit.hash} as a separate batch")
current_batch = []
current_tokens = base_prompt_tokens
else:
# 正常情况:添加到当前批次
current_batch.append(commit)
current_tokens += commit_tokens
logger.info(f"Added commit {commit.hash} to batch, new token estimate: {current_tokens}")
# 添加最后一个批次(如果有)
if current_batch:
batches.append(current_batch)
logger.info(f"Added final batch with {len(current_batch)} commits, estimated {current_tokens} tokens")
# 记录批次信息
for i, batch in enumerate(batches):
logger.info(f"Batch {i+1}: {len(batch)} commits, commit hashes: {[c.hash for c in batch]}")
return batches
async def pr_summary(retriever, summary_chain):
"""Generate PR summary asynchronously."""
result = await summary_chain.ainvoke(
{"pull_request": retriever.pull_request}, include_run_info=True
)
return result
async def code_review(retriever, review_chain):
"""Generate code review asynchronously."""
result = await review_chain.ainvoke(
{"pull_request": retriever.pull_request}, include_run_info=True
)
return result
def get_remote_commit_diff(
platform: str,
repository_name: str,
commit_hash: str,
include_extensions: Optional[List[str]] = None,
exclude_extensions: Optional[List[str]] = None,
gitlab_url: Optional[str] = None,
) -> Dict[str, Dict[str, Any]]:
"""
Get commit diff from remote repositories (GitHub or GitLab).
Args:
platform (str): Platform to use (github or gitlab)
repository_name (str): Repository name (e.g. owner/repo)
commit_hash (str): Commit hash to review
include_extensions (Optional[List[str]], optional): File extensions to include. Defaults to None.
exclude_extensions (Optional[List[str]], optional): File extensions to exclude. Defaults to None.
gitlab_url (Optional[str], optional): GitLab URL. Defaults to None.
Returns:
Dict[str, Dict[str, Any]]: Dictionary mapping file paths to their diffs and statistics
"""
logger.info(f"Getting commit diff from {platform} for repository {repository_name}, commit {commit_hash}")
logger.info(f"Include extensions: {include_extensions}, Exclude extensions: {exclude_extensions}")
if platform.lower() == "github":
# Initialize GitHub client
github_token = os.environ.get("GITHUB_TOKEN", "")
if not github_token:
error_msg = "GITHUB_TOKEN environment variable is not set"
logger.error(error_msg)
print(error_msg)
return {}
github_client = Github(github_token)
print(f"Analyzing GitHub repository {repository_name} for commit {commit_hash}")
logger.info(f"Initialized GitHub client for repository {repository_name}")
try:
# Get repository
logger.info(f"Fetching repository {repository_name}")
repo = github_client.get_repo(repository_name)
# Get commit
logger.info(f"Fetching commit {commit_hash}")
commit = repo.get_commit(commit_hash)
logger.info(f"Commit found: {commit.sha}, author: {commit.commit.author.name}, date: {commit.commit.author.date}")
# Extract file diffs
file_diffs = {}
logger.info(f"Processing {len(commit.files)} files in commit")
for i, file in enumerate(commit.files):
logger.info(f"Processing file {i+1}/{len(commit.files)}: {file.filename}")
# Filter by file extensions
_, ext = os.path.splitext(file.filename)
logger.debug(f"File extension: {ext}")
if include_extensions and ext not in include_extensions:
logger.info(f"Skipping file {file.filename} - extension {ext} not in include list")
continue
if exclude_extensions and ext in exclude_extensions:
logger.info(f"Skipping file {file.filename} - extension {ext} in exclude list")
continue
if file.patch:
logger.info(f"Adding file {file.filename} to diff (status: {file.status}, additions: {file.additions}, deletions: {file.deletions})")
file_diffs[file.filename] = {
"diff": f"diff --git a/{file.filename} b/{file.filename}\n{file.patch}",
"status": file.status,
"additions": file.additions,
"deletions": file.deletions,
}
else:
logger.warning(f"No patch content for file {file.filename}")
logger.info(f"Processed {len(file_diffs)} files after filtering")
return file_diffs
except Exception as e:
error_msg = f"Failed to retrieve GitHub commit: {str(e)}"
logger.error(error_msg, exc_info=True)
print(error_msg)
return {}
elif platform.lower() == "gitlab":
# Initialize GitLab client
gitlab_token = os.environ.get("GITLAB_TOKEN", "")
if not gitlab_token:
error_msg = "GITLAB_TOKEN environment variable is not set"
logger.error(error_msg)
print(error_msg)
return {}
# Use provided GitLab URL or fall back to environment variable or default
gitlab_url = gitlab_url or os.environ.get("GITLAB_URL", "https://gitlab.com")
logger.info(f"Using GitLab URL: {gitlab_url}")
gitlab_client = Gitlab(url=gitlab_url, private_token=gitlab_token)
print(f"Analyzing GitLab repository {repository_name} for commit {commit_hash}")
logger.info(f"Initialized GitLab client for repository {repository_name}")
try:
# Get repository
logger.info(f"Fetching project {repository_name}")
project = gitlab_client.projects.get(repository_name)
logger.info(f"Project found: {project.name}, ID: {project.id}")
# Get commit
logger.info(f"Fetching commit {commit_hash}")
commit = project.commits.get(commit_hash)
logger.info(f"Commit found: {commit.id}, author: {commit.author_name}, date: {commit.created_at}")
# Get commit diff
logger.info("Fetching commit diff")
diff = commit.diff()
logger.info(f"Processing {len(diff)} files in commit diff")
# Extract file diffs
file_diffs = {}
for i, file_diff in enumerate(diff):
file_path = file_diff.get('new_path', '')
old_path = file_diff.get('old_path', '')
diff_content = file_diff.get('diff', '')
logger.info(f"Processing file {i+1}/{len(diff)}: {file_path}")
logger.debug(f"Old path: {old_path}, New path: {file_path}")
# Skip if no diff content
if not diff_content:
logger.warning(f"No diff content for file {file_path}, skipping")
continue
# Filter by file extensions
_, ext = os.path.splitext(file_path)
logger.debug(f"File extension: {ext}")
if include_extensions and ext not in include_extensions:
logger.info(f"Skipping file {file_path} - extension {ext} not in include list")
continue
if exclude_extensions and ext in exclude_extensions:
logger.info(f"Skipping file {file_path} - extension {ext} in exclude list")
continue
# Determine file status
if file_diff.get('new_file', False):
status = 'A' # Added
elif file_diff.get('deleted_file', False):
status = 'D' # Deleted
else:
status = 'M' # Modified
logger.debug(f"File status: {status}")
# Format diff content
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n{diff_content}"
# Count additions and deletions
additions = diff_content.count('\n+')
deletions = diff_content.count('\n-')
logger.debug(f"Additions: {additions}, Deletions: {deletions}")
logger.info(f"Adding file {file_path} to diff (status: {status}, additions: {additions}, deletions: {deletions})")
file_diffs[file_path] = {
"diff": formatted_diff,
"status": status,
"additions": additions,
"deletions": deletions,
}
logger.info(f"Processed {len(file_diffs)} files after filtering")
return file_diffs
except Exception as e:
error_msg = f"Failed to retrieve GitLab commit: {str(e)}"
logger.error(error_msg, exc_info=True)
print(error_msg)
return {}
else:
error_msg = f"Unsupported platform: {platform}. Use 'github' or 'gitlab'."
logger.error(error_msg)
print(error_msg)
return {}
def get_all_remote_commits(
platform: str,
repository_name: str,
start_date: str,
end_date: str,
include_extensions: Optional[List[str]] = None,
exclude_extensions: Optional[List[str]] = None,
gitlab_url: Optional[str] = None,
) -> Dict[str, Tuple[List[Any], Dict[str, Dict[str, str]], Dict[str, int]]]:
"""
Get all commits from remote repositories (GitHub or GitLab) grouped by author.
Args:
platform (str): Platform to use (github or gitlab)
repository_name (str): Repository name (e.g. owner/repo)
start_date (str): Start date (YYYY-MM-DD)
end_date (str): End date (YYYY-MM-DD)
include_extensions (Optional[List[str]], optional): File extensions to include. Defaults to None.
exclude_extensions (Optional[List[str]], optional): File extensions to exclude. Defaults to None.
gitlab_url (Optional[str], optional): GitLab URL. Defaults to None.
Returns:
Dict[str, Tuple[List[Any], Dict[str, Dict[str, str]], Dict[str, int]]]: Dictionary mapping author names to their commits, file diffs, and code stats
"""
if platform.lower() == "github":
# Initialize GitHub client
github_token = os.environ.get("GITHUB_TOKEN", "")
if not github_token:
error_msg = "GITHUB_TOKEN environment variable is not set"
logger.error(error_msg)
print(error_msg)
return {}
github_client = Github(github_token)
print(f"Analyzing GitHub repository {repository_name} for all commits")
logger.info(f"Initialized GitHub client for repository {repository_name}")
try:
# Get repository
repo = github_client.get_repo(repository_name)
# Convert dates to datetime objects
start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
end_datetime = datetime.strptime(end_date, "%Y-%m-%d") + timedelta(days=1) # Include the end date
# Get all commits in the repository within the date range
all_commits = repo.get_commits(since=start_datetime, until=end_datetime)
# Group commits by author
author_commits = {}
for commit in all_commits:
author_name = commit.commit.author.name
author_email = commit.commit.author.email
# Use email as part of the key to distinguish between authors with the same name
author_key = f"{author_name} <{author_email}>" if author_email else author_name
if author_key not in author_commits:
author_commits[author_key] = {
"commits": [],
"file_diffs": {},
"stats": {
"total_added_lines": 0,
"total_deleted_lines": 0,
"total_effective_lines": 0,
"total_files": set()
}
}
# Create CommitInfo object
commit_info = CommitInfo(
hash=commit.sha,
author=author_name,
date=commit.commit.author.date,
message=commit.commit.message,
files=[file.filename for file in commit.files],
diff="\n".join([f"diff --git a/{file.filename} b/{file.filename}\n{file.patch}" for file in commit.files if file.patch]),
added_lines=sum(file.additions for file in commit.files),
deleted_lines=sum(file.deletions for file in commit.files),
effective_lines=sum(file.additions - file.deletions for file in commit.files)
)
author_commits[author_key]["commits"].append(commit_info)
# Extract file diffs
file_diffs = {}
for file in commit.files:
if file.patch:
# Filter by file extensions
_, ext = os.path.splitext(file.filename)
if include_extensions and ext not in include_extensions:
continue
if exclude_extensions and ext in exclude_extensions:
continue
file_diffs[file.filename] = file.patch
author_commits[author_key]["stats"]["total_files"].add(file.filename)
author_commits[author_key]["file_diffs"][commit.sha] = file_diffs
# Update stats
author_commits[author_key]["stats"]["total_added_lines"] += commit_info.added_lines
author_commits[author_key]["stats"]["total_deleted_lines"] += commit_info.deleted_lines
author_commits[author_key]["stats"]["total_effective_lines"] += commit_info.effective_lines
# Convert the set of files to count
for author_key in author_commits:
author_commits[author_key]["stats"]["total_files"] = len(author_commits[author_key]["stats"]["total_files"])
# Convert to the expected return format
result = {}
for author_key, data in author_commits.items():
result[author_key] = (data["commits"], data["file_diffs"], data["stats"])
return result
except Exception as e:
error_msg = f"Failed to retrieve GitHub commits: {str(e)}"
logger.error(error_msg, exc_info=True)
print(error_msg)
return {}
elif platform.lower() == "gitlab":
# Initialize GitLab client
gitlab_token = os.environ.get("GITLAB_TOKEN", "")
if not gitlab_token:
error_msg = "GITLAB_TOKEN environment variable is not set"
logger.error(error_msg)
print(error_msg)
return {}
# Use provided GitLab URL or fall back to environment variable or default
gitlab_url = gitlab_url or os.environ.get("GITLAB_URL", "https://gitlab.com")
logger.info(f"Using GitLab URL: {gitlab_url}")
gitlab_client = Gitlab(url=gitlab_url, private_token=gitlab_token)
print(f"Analyzing GitLab repository {repository_name} for all commits")
logger.info(f"Initialized GitLab client for repository {repository_name}")
try:
# Get repository
project = gitlab_client.projects.get(repository_name)
logger.info(f"Project found: {project.name}, ID: {project.id}")
# Convert dates to ISO format
start_iso = f"{start_date}T00:00:00Z"
end_iso = f"{end_date}T23:59:59Z"
# Get all commits in the repository within the date range
all_commits = project.commits.list(all=True, get_all=True, since=start_iso, until=end_iso)
logger.info(f"Found {len(all_commits)} commits in the date range")
# Group commits by author
author_commits = {}
for commit in all_commits:
author_name = commit.author_name
author_email = commit.author_email
# Use email as part of the key to distinguish between authors with the same name
author_key = f"{author_name} <{author_email}>" if author_email else author_name
if author_key not in author_commits:
author_commits[author_key] = {
"commits": [],
"file_diffs": {},
"stats": {
"total_added_lines": 0,
"total_deleted_lines": 0,
"total_effective_lines": 0,
"total_files": set()
}
}
# Get commit details
commit_detail = project.commits.get(commit.id)
# Get commit diff
diff = commit_detail.diff(get_all=True)
# Filter files by extension
filtered_diff = []
for file_diff in diff:
file_path = file_diff.get('new_path', '')
_, ext = os.path.splitext(file_path)
if include_extensions and ext not in include_extensions:
continue
if exclude_extensions and ext in exclude_extensions:
continue
filtered_diff.append(file_diff)
# Skip if no files match the filter
if not filtered_diff:
continue
# Get file content for each modified file
file_diffs = {}
for file_diff in filtered_diff:
file_path = file_diff.get('new_path', '')
old_path = file_diff.get('old_path', '')
diff_content = file_diff.get('diff', '')
# Skip if no diff content
if not diff_content:
continue
# Format diff content
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n{diff_content}"
file_diffs[file_path] = formatted_diff
author_commits[author_key]["stats"]["total_files"].add(file_path)
# Skip if no valid diffs
if not file_diffs:
continue
# Count additions and deletions
added_lines = sum(diff_content.count('\n+') for diff_content in file_diffs.values())
deleted_lines = sum(diff_content.count('\n-') for diff_content in file_diffs.values())
effective_lines = added_lines - deleted_lines
# Create CommitInfo object
commit_info = CommitInfo(
hash=commit.id,
author=author_name,
date=datetime.strptime(commit.created_at, "%Y-%m-%dT%H:%M:%S.%f%z") if '.' in commit.created_at else datetime.strptime(commit.created_at, "%Y-%m-%dT%H:%M:%SZ"),
message=commit.message,
files=list(file_diffs.keys()),
diff="\n\n".join(file_diffs.values()),
added_lines=added_lines,
deleted_lines=deleted_lines,
effective_lines=effective_lines
)
author_commits[author_key]["commits"].append(commit_info)
author_commits[author_key]["file_diffs"][commit.id] = file_diffs
# Update stats
author_commits[author_key]["stats"]["total_added_lines"] += added_lines
author_commits[author_key]["stats"]["total_deleted_lines"] += deleted_lines
author_commits[author_key]["stats"]["total_effective_lines"] += effective_lines
# Convert the set of files to count
for author_key in author_commits:
author_commits[author_key]["stats"]["total_files"] = len(author_commits[author_key]["stats"]["total_files"])
# Convert to the expected return format
result = {}
for author_key, data in author_commits.items():
result[author_key] = (data["commits"], data["file_diffs"], data["stats"])
return result
except Exception as e:
error_msg = f"Failed to retrieve GitLab commits: {str(e)}"
logger.error(error_msg, exc_info=True)
print(error_msg)
return {}
else:
error_msg = f"Unsupported platform: {platform}. Use 'github' or 'gitlab'."
logger.error(error_msg)
print(error_msg)
return {}
def get_remote_commits(
platform: str,
repository_name: str,
author: str,
start_date: str,
end_date: str,
include_extensions: Optional[List[str]] = None,
exclude_extensions: Optional[List[str]] = None,
gitlab_url: Optional[str] = None,
) -> Tuple[List[Any], Dict[str, Dict[str, str]], Dict[str, int]]:
"""
Get commits from remote repositories (GitHub or GitLab).
Args:
platform (str): Platform to use (github or gitlab)
repository_name (str): Repository name (e.g. owner/repo)
author (str): Author name or email
start_date (str): Start date (YYYY-MM-DD)
end_date (str): End date (YYYY-MM-DD)
include_extensions (Optional[List[str]], optional): File extensions to include. Defaults to None.
exclude_extensions (Optional[List[str]], optional): File extensions to exclude. Defaults to None.
gitlab_url (Optional[str], optional): GitLab URL. Defaults to None.
Returns:
Tuple[List[Any], Dict[str, Dict[str, str]], Dict[str, int]]: Commits, file diffs, and code stats
"""
if platform.lower() == "github":
# Initialize GitHub client
github_client = Github() # Will automatically load GITHUB_TOKEN from environment
print(f"Analyzing GitHub repository {repository_name} for commits by {author}")
try:
# Get repository
repo = github_client.get_repo(repository_name)
# Convert dates to datetime objects
start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
end_datetime = datetime.strptime(end_date, "%Y-%m-%d") + timedelta(days=1) # Include the end date
# Get commits
commits = []
commit_file_diffs = {}
# Get all commits in the repository within the date range
all_commits = repo.get_commits(since=start_datetime, until=end_datetime)
# Filter by author
for commit in all_commits:
if author.lower() in commit.commit.author.name.lower() or (
commit.commit.author.email and author.lower() in commit.commit.author.email.lower()
):
# Create CommitInfo object
commit_info = CommitInfo(
hash=commit.sha,
author=commit.commit.author.name,
date=commit.commit.author.date,
message=commit.commit.message,
files=[file.filename for file in commit.files],
diff="\n".join([f"diff --git a/{file.filename} b/{file.filename}\n{file.patch}" for file in commit.files if file.patch]),
added_lines=sum(file.additions for file in commit.files),
deleted_lines=sum(file.deletions for file in commit.files),
effective_lines=sum(file.additions - file.deletions for file in commit.files)
)
commits.append(commit_info)
# Extract file diffs
file_diffs = {}
for file in commit.files:
if file.patch:
# Filter by file extensions
_, ext = os.path.splitext(file.filename)
if include_extensions and ext not in include_extensions:
continue
if exclude_extensions and ext in exclude_extensions:
continue
file_diffs[file.filename] = file.patch
commit_file_diffs[commit.sha] = file_diffs
# Calculate code stats
code_stats = {
"total_added_lines": sum(commit.added_lines for commit in commits),
"total_deleted_lines": sum(commit.deleted_lines for commit in commits),
"total_effective_lines": sum(commit.effective_lines for commit in commits),
"total_files": len(set(file for commit in commits for file in commit.files))
}
return commits, commit_file_diffs, code_stats
except Exception as e:
error_msg = f"Failed to retrieve GitHub commits: {str(e)}"
print(error_msg)
return [], {}, {}
elif platform.lower() == "gitlab":
# Initialize GitLab client
gitlab_token = os.environ.get("GITLAB_TOKEN", "")
if not gitlab_token:
error_msg = "GITLAB_TOKEN environment variable is not set"
print(error_msg)
return [], {}, {}
# Use provided GitLab URL or fall back to environment variable or default
gitlab_url = gitlab_url or os.environ.get("GITLAB_URL", "https://gitlab.com")
gitlab_client = Gitlab(url=gitlab_url, private_token=gitlab_token)
print(f"Analyzing GitLab repository {repository_name} for commits by {author}")
try:
# Get repository
project = gitlab_client.projects.get(repository_name)
# Get commits
commits = []
commit_file_diffs = {}
# Convert dates to ISO format
start_iso = f"{start_date}T00:00:00Z"
end_iso = f"{end_date}T23:59:59Z"
# Get all commits in the repository within the date range
all_commits = project.commits.list(all=True, get_all=True, since=start_iso, until=end_iso)
# Filter by author
for commit in all_commits:
if author.lower() in commit.author_name.lower() or (
commit.author_email and author.lower() in commit.author_email.lower()
):
# Get commit details
commit_detail = project.commits.get(commit.id)
# Get commit diff
diff = commit_detail.diff(get_all=True)
# Filter files by extension
filtered_diff = []
for file_diff in diff:
file_path = file_diff.get('new_path', '')
_, ext = os.path.splitext(file_path)
if include_extensions and ext not in include_extensions:
continue
if exclude_extensions and ext in exclude_extensions:
continue
filtered_diff.append(file_diff)
# Skip if no files match the filter
if not filtered_diff:
continue
# Get file content for each modified file
file_diffs = {}
for file_diff in filtered_diff:
file_path = file_diff.get('new_path', '')
old_path = file_diff.get('old_path', '')
diff_content = file_diff.get('diff', '')
# Skip if no diff content
if not diff_content:
continue
# Try to get the file content
try:
# For new files, get the content from the current commit
if file_diff.get('new_file', False):
try:
# Get the file content and handle both string and bytes
file_obj = project.files.get(file_path=file_path, ref=commit.id)
if hasattr(file_obj, 'content'):
# Raw content from API
file_content = file_obj.content
elif hasattr(file_obj, 'decode'):
# Decode if it's bytes
try:
file_content = file_obj.decode()
except TypeError:
# If decode fails, try to get content directly
file_content = file_obj.content if hasattr(file_obj, 'content') else str(file_obj)
else:
# Fallback to string representation
file_content = str(file_obj)
# Format as a proper diff with the entire file as added
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- /dev/null\n+++ b/{file_path}\n"
formatted_diff += "\n".join([f"+{line}" for line in file_content.split('\n')])
file_diffs[file_path] = formatted_diff
except Exception as e:
print(f"Warning: Could not get content for new file {file_path}: {str(e)}")
# Try to get the raw file content directly from the API
try:
import base64
raw_file = project.repository_files.get(file_path=file_path, ref=commit.id)
if raw_file and hasattr(raw_file, 'content'):
# Decode base64 content if available
try:
decoded_content = base64.b64decode(raw_file.content).decode('utf-8', errors='replace')
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- /dev/null\n+++ b/{file_path}\n"
formatted_diff += "\n".join([f"+{line}" for line in decoded_content.split('\n')])
file_diffs[file_path] = formatted_diff
continue
except Exception as decode_err:
print(f"Warning: Could not decode content for {file_path}: {str(decode_err)}")
except Exception as api_err:
print(f"Warning: Could not get raw file content for {file_path}: {str(api_err)}")
# Use diff content as fallback
file_diffs[file_path] = diff_content
# For deleted files, get the content from the parent commit
elif file_diff.get('deleted_file', False):
try:
# Get parent commit
parent_commits = project.commits.get(commit.id).parent_ids
if parent_commits:
# Get the file content and handle both string and bytes
try:
file_obj = project.files.get(file_path=old_path, ref=parent_commits[0])
if hasattr(file_obj, 'content'):
# Raw content from API
file_content = file_obj.content
elif hasattr(file_obj, 'decode'):
# Decode if it's bytes
try:
file_content = file_obj.decode()
except TypeError:
# If decode fails, try to get content directly
file_content = file_obj.content if hasattr(file_obj, 'content') else str(file_obj)
else:
# Fallback to string representation
file_content = str(file_obj)
# Format as a proper diff with the entire file as deleted
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- a/{old_path}\n+++ /dev/null\n"
formatted_diff += "\n".join([f"-{line}" for line in file_content.split('\n')])
file_diffs[file_path] = formatted_diff
except Exception as file_err:
# Try to get the raw file content directly from the API
try:
import base64
raw_file = project.repository_files.get(file_path=old_path, ref=parent_commits[0])
if raw_file and hasattr(raw_file, 'content'):
# Decode base64 content if available
try:
decoded_content = base64.b64decode(raw_file.content).decode('utf-8', errors='replace')
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- a/{old_path}\n+++ /dev/null\n"
formatted_diff += "\n".join([f"-{line}" for line in decoded_content.split('\n')])
file_diffs[file_path] = formatted_diff
except Exception as decode_err:
print(f"Warning: Could not decode content for deleted file {old_path}: {str(decode_err)}")
file_diffs[file_path] = diff_content
else:
file_diffs[file_path] = diff_content
except Exception as api_err:
print(f"Warning: Could not get raw file content for deleted file {old_path}: {str(api_err)}")
file_diffs[file_path] = diff_content
else:
file_diffs[file_path] = diff_content
except Exception as e:
print(f"Warning: Could not get content for deleted file {old_path}: {str(e)}")
file_diffs[file_path] = diff_content
# For modified files, use the diff content
else:
# Check if diff_content is empty or minimal
if not diff_content or len(diff_content.strip()) < 10:
# Try to get the full file content for better context
try:
# Get the file content and handle both string and bytes
file_obj = project.files.get(file_path=file_path, ref=commit.id)
if hasattr(file_obj, 'content'):
# Raw content from API
file_content = file_obj.content
elif hasattr(file_obj, 'decode'):
# Decode if it's bytes
try:
file_content = file_obj.decode()
except TypeError:
# If decode fails, try to get content directly
file_content = file_obj.content if hasattr(file_obj, 'content') else str(file_obj)
else:
# Fallback to string representation
file_content = str(file_obj)
# Format as a proper diff with the entire file
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- a/{old_path}\n+++ b/{file_path}\n"
formatted_diff += "\n".join([f"+{line}" for line in file_content.split('\n')])
file_diffs[file_path] = formatted_diff
except Exception as e:
print(f"Warning: Could not get content for modified file {file_path}: {str(e)}")
# Try to get the raw file content directly from the API
try:
import base64
raw_file = project.repository_files.get(file_path=file_path, ref=commit.id)
if raw_file and hasattr(raw_file, 'content'):
# Decode base64 content if available
try:
decoded_content = base64.b64decode(raw_file.content).decode('utf-8', errors='replace')
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- a/{old_path}\n+++ b/{file_path}\n"
formatted_diff += "\n".join([f"+{line}" for line in decoded_content.split('\n')])
file_diffs[file_path] = formatted_diff
except Exception as decode_err:
print(f"Warning: Could not decode content for {file_path}: {str(decode_err)}")
# Enhance the diff format with what we have
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- a/{old_path}\n+++ b/{file_path}\n{diff_content}"
file_diffs[file_path] = formatted_diff
else:
# Enhance the diff format with what we have
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- a/{old_path}\n+++ b/{file_path}\n{diff_content}"
file_diffs[file_path] = formatted_diff
except Exception as api_err:
print(f"Warning: Could not get raw file content for {file_path}: {str(api_err)}")
# Enhance the diff format with what we have
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- a/{old_path}\n+++ b/{file_path}\n{diff_content}"
file_diffs[file_path] = formatted_diff
else:
# Enhance the diff format
formatted_diff = f"diff --git a/{old_path} b/{file_path}\n--- a/{old_path}\n+++ b/{file_path}\n{diff_content}"
file_diffs[file_path] = formatted_diff
except Exception as e:
print(f"Warning: Error processing diff for {file_path}: {str(e)}")
file_diffs[file_path] = diff_content
# Skip if no valid diffs
if not file_diffs:
continue
# Create CommitInfo object with enhanced diff content
commit_info = CommitInfo(
hash=commit.id,
author=commit.author_name,
date=datetime.strptime(commit.created_at, "%Y-%m-%dT%H:%M:%S.%f%z"),
message=commit.message,
files=list(file_diffs.keys()),
diff="\n\n".join(file_diffs.values()),
added_lines=sum(diff.count('\n+') for diff in file_diffs.values()),