-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGitCommitAssistant.py
More file actions
1850 lines (1568 loc) · 79.9 KB
/
GitCommitAssistant.py
File metadata and controls
1850 lines (1568 loc) · 79.9 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 os
import subprocess
import datetime
import random
import shutil
import sys
import threading
import itertools
import time
import requests
from concurrent.futures import ThreadPoolExecutor
def run_command(command, cwd=None, env=None, suppress_output=True):
"""
Executes a shell command.
Args:
command (list): The command and its arguments to execute.
cwd (str, optional): The working directory to execute the command in.
env (dict, optional): Environment variables for the command.
suppress_output (bool, optional): If True, suppresses the command's output.
Raises:
SystemExit: Exits the program if the command fails.
"""
try:
if suppress_output:
subprocess.check_call(
command, cwd=cwd, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
else:
subprocess.check_call(command, cwd=cwd, env=env)
except subprocess.CalledProcessError:
print(f"\nError executing command: {' '.join(command)}")
print("Please execute the above command manually in the terminal.")
sys.exit(1)
def get_default_repo_names(file_path='repo_names.txt'):
"""
Loads repository names from a text file.
Args:
file_path (str): Path to the repository names file.
Returns:
list: A list of repository names.
Raises:
SystemExit: If the file does not exist or is empty.
"""
if not os.path.exists(file_path):
print(f"Repository names file '{file_path}' not found.")
sys.exit(1)
with open(file_path, 'r', encoding='utf-8') as f:
names = [line.strip() for line in f if line.strip()]
if not names:
print(f"No repository names found in '{file_path}'. Please add repository names.")
sys.exit(1)
return names
def create_repo(repo_name, token):
"""
Creates a GitHub repository using the GitHub API.
Args:
repo_name (str): The name of the repository to create.
token (str): GitHub Personal Access Token for authentication.
Returns:
str or None: The clone URL if creation is successful, "exists" if repository already exists, or None on failure.
"""
url = "https://api.github.com/user/repos"
headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json"
}
data = {
"name": repo_name,
"auto_init": True,
"private": True,
"description": "Automated repository creation"
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 201:
print(f"Repository '{repo_name}' created successfully.")
return response.json()["clone_url"]
elif response.status_code == 422:
print(f"Repository '{repo_name}' already exists.")
return "exists"
else:
print(f"Failed to create repository '{repo_name}'. Status Code: {response.status_code}")
print("Response:", response.json())
return None
def get_user_repos(repo_names):
"""
Gathers repository information from the user, either existing repositories or creating new ones.
Args:
repo_names (list): List of default repository names.
Returns:
dict: A dictionary with repository names as keys and their details as values.
"""
repos = {}
has_repos = input("Do you have existing repositories? (y/n): ").strip().lower()
if has_repos == 'y':
try:
num_repos = int(input("Enter the number of repositories: "))
except ValueError:
print("Invalid number. Please enter an integer.")
sys.exit(1)
for i in range(num_repos):
name = input(f"Enter name for repository {i+1}: ").strip()
url = input(f"Enter the GitHub URL for repository {i+1}: ").strip()
use_default = input("Do you want to use default commit messages? (y/n): ").strip().lower()
if use_default == 'y':
repos[name] = {"url": url, "messages": None}
else:
messages = []
print(f"Enter commit messages for '{name}' (type 'done' when finished):")
while True:
msg = input()
if msg.lower() == 'done':
break
if msg.strip():
messages.append(msg.strip())
if not messages:
print("No messages entered. Using default messages.")
repos[name] = {"url": url, "messages": None}
else:
repos[name] = {"url": url, "messages": messages}
else:
token = input("Enter your GitHub Personal Access Token: ").strip()
try:
num_repos = int(input("Enter the number of repositories to create: "))
except ValueError:
print("Invalid number. Please enter an integer.")
sys.exit(1)
for i in range(num_repos):
while True:
name = input(f"Enter name for new repository {i+1} (leave blank for default): ").strip()
if not name:
if repo_names:
name = random.choice(repo_names)
repo_names.remove(name)
print(f"Using default repository name: {name}")
else:
print("No more default names available. Please enter a unique repository name.")
name = input(f"Enter name for new repository {i+1}: ").strip()
clone_url = create_repo(name, token)
if clone_url == "exists":
choice = input(f"Repository '{name}' already exists. Do you want to choose another name? (y/n): ").strip().lower()
if choice == 'y':
continue
else:
break
elif clone_url:
repos[name] = {"url": clone_url, "messages": None}
break
else:
sys.exit(1)
if not repos:
print("No repositories to process.")
sys.exit(0)
return repos
def get_date_range():
"""
Prompts the user to input the start and end dates for commit generation.
Returns:
tuple: Start date and end date as datetime.date objects.
"""
print("\nChoose date range for commits:")
print("1. Last 30 days")
print("2. Last 3 months")
print("3. Last 6 months")
print("4. Last year")
print("5. Custom date range")
choice = input("Enter your choice (1-5): ").strip()
today = datetime.date.today()
if choice == '1':
start_date = today - datetime.timedelta(days=30)
end_date = today
print(f"Selected: Last 30 days ({start_date} to {end_date})")
elif choice == '2':
start_date = today - datetime.timedelta(days=90)
end_date = today
print(f"Selected: Last 3 months ({start_date} to {end_date})")
elif choice == '3':
start_date = today - datetime.timedelta(days=180)
end_date = today
print(f"Selected: Last 6 months ({start_date} to {end_date})")
elif choice == '4':
start_date = today - datetime.timedelta(days=365)
end_date = today
print(f"Selected: Last year ({start_date} to {end_date})")
elif choice == '5':
try:
start_date_str = input("Enter start date (YYYY-MM-DD): ").strip()
end_date_str = input("Enter end date (YYYY-MM-DD): ").strip()
start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d").date()
if start_date > end_date:
print("Start date must be before end date.")
sys.exit(1)
except ValueError:
print("Invalid date format. Please use YYYY-MM-DD.")
sys.exit(1)
else:
print("Invalid choice. Please enter a number between 1 and 5.")
sys.exit(1)
return start_date, end_date
def get_commit_range():
"""
Prompts the user to input the minimum and maximum number of commits per day.
Returns:
tuple: Minimum and maximum number of commits per day as integers.
"""
try:
min_commits = int(input("Enter minimum number of commits per day: "))
max_commits = int(input("Enter maximum number of commits per day: "))
if min_commits < 1 or max_commits < min_commits:
print("Invalid commit range.")
sys.exit(1)
return min_commits, max_commits
except ValueError:
print("Invalid input. Please enter integers.")
sys.exit(1)
def get_commit_frequency():
"""
Prompts the user to choose the frequency strategy for commits.
Returns:
dict: A dictionary containing the commit strategy and related parameters.
"""
print("\nHow often should it make commits?")
print("1. Every day")
print("2. Randomly")
print("3. Weekdays only")
print("4. Weekends only")
choice = input("Enter the number of your choice: ").strip()
if choice == '1':
print("\nYou have chosen to make commits every day.")
try:
commits_per_day = int(input("Enter the number of commits per day: "))
if commits_per_day < 1:
print("Number of commits must be at least 1.")
sys.exit(1)
return {
'strategy': 'fixed',
'min_commits': commits_per_day,
'max_commits': commits_per_day,
'days': 'all'
}
except ValueError:
print("Invalid input. Please enter an integer.")
sys.exit(1)
elif choice == '2':
print("\nYou have chosen to make commits randomly.")
min_commits, max_commits = get_commit_range()
return {
'strategy': 'random',
'min_commits': min_commits,
'max_commits': max_commits,
'days': 'all'
}
elif choice == '3':
print("\nYou have chosen to make commits on weekdays only.")
min_commits, max_commits = get_commit_range()
return {
'strategy': 'random',
'min_commits': min_commits,
'max_commits': max_commits,
'days': 'weekdays'
}
elif choice == '4':
print("\nYou have chosen to make commits on weekends only.")
min_commits, max_commits = get_commit_range()
return {
'strategy': 'random',
'min_commits': min_commits,
'max_commits': max_commits,
'days': 'weekends'
}
else:
print("Invalid choice. Please enter a number between 1 and 4.")
sys.exit(1)
def load_commit_messages(file_path='commit_messages.txt'):
"""
Loads commit messages from a text file.
Args:
file_path (str): Path to the commit messages file.
Returns:
list: A list of commit messages.
Raises:
SystemExit: If the file does not exist or is empty.
"""
if not os.path.exists(file_path):
print(f"Commit messages file '{file_path}' not found.")
sys.exit(1)
with open(file_path, 'r', encoding='utf-8') as f:
messages = [line.strip() for line in f if line.strip()]
if not messages:
print(f"No commit messages found in '{file_path}'. Please add commit messages.")
sys.exit(1)
return messages
def clone_repo(repo_name, repo_url, temp_dir):
"""
Clones the specified repository into a temporary directory.
Args:
repo_name (str): The name of the repository.
repo_url (str): The clone URL of the repository.
temp_dir (str): The path to the temporary directory.
Returns:
str: The path to the cloned repository.
"""
repo_path = os.path.join(temp_dir, repo_name)
if os.path.exists(repo_path):
shutil.rmtree(repo_path)
run_command(["git", "clone", repo_url, repo_path])
return repo_path
def make_commit(repo_path, commit_message, commit_date):
"""
Creates a commit with the given message and date.
Args:
repo_path (str): The path to the cloned repository.
commit_message (str): The commit message.
commit_date (datetime.date): The date for the commit.
"""
log_file = os.path.join(repo_path, "commit_log.txt")
# Append commit message to the log file
try:
with open(log_file, "a") as f:
f.write(f"{commit_date} - {commit_message}\n")
except Exception as e:
print(f"Error writing to commit_log.txt: {e}")
sys.exit(1)
# Stage the log file for commit
run_command(["git", "add", "commit_log.txt"], cwd=repo_path)
# Set commit date environment variables
env = os.environ.copy()
env["GIT_AUTHOR_DATE"] = commit_date.strftime("%Y-%m-%dT12:00:00")
env["GIT_COMMITTER_DATE"] = commit_date.strftime("%Y-%m-%dT12:00:00")
# Commit the changes
run_command(["git", "commit", "-m", commit_message], cwd=repo_path, env=env)
def make_pr_commit(repo_path, commit_message, commit_date, file_name):
"""
Creates a commit for a pull request with the given message and date.
Args:
repo_path (str): The path to the cloned repository.
commit_message (str): The commit message.
commit_date (datetime.date): The date for the commit.
file_name (str): The name of the file to add.
"""
# Stage the file for commit
run_command(["git", "add", file_name], cwd=repo_path)
# Set commit date environment variables
env = os.environ.copy()
env["GIT_AUTHOR_DATE"] = commit_date.strftime("%Y-%m-%dT12:00:00")
env["GIT_COMMITTER_DATE"] = commit_date.strftime("%Y-%m-%dT12:00:00")
# Commit the changes
run_command(["git", "commit", "-m", commit_message], cwd=repo_path, env=env)
def push_changes(repo_path):
"""
Pushes the committed changes to the remote repository.
Args:
repo_path (str): The path to the cloned repository.
Raises:
SystemExit: If the push operation fails.
"""
try:
run_command(["git", "push", "origin", "main"], cwd=repo_path)
except:
print(f"\nFailed to push changes for repository at {repo_path}.")
print("Please navigate to the repository directory and push the changes manually:")
print(f"cd {repo_path}")
print("git push origin main")
sys.exit(1)
def generate_commits(repos, start_date, end_date, commit_frequency, temp_dir):
"""
Generates commits for each repository within the specified date range based on commit frequency.
Args:
repos (dict): Dictionary containing repository details.
start_date (datetime.date): The start date for commit generation.
end_date (datetime.date): The end date for commit generation.
commit_frequency (dict): Commit frequency strategy and parameters.
temp_dir (str): Path to the temporary directory.
"""
commit_messages = load_commit_messages()
for repo_name, repo_info in repos.items():
print(f"\nProcessing repository: {repo_name}")
repo_path = clone_repo(repo_name, repo_info["url"], temp_dir)
messages = repo_info["messages"] if repo_info["messages"] else commit_messages
current_date = start_date
while current_date <= end_date:
# Determine if a commit should be made on this day based on the frequency strategy
make_commit_today = False
if commit_frequency['days'] == 'all':
make_commit_today = True
elif commit_frequency['days'] == 'weekdays' and current_date.weekday() < 5:
make_commit_today = True
elif commit_frequency['days'] == 'weekends' and current_date.weekday() >= 5:
make_commit_today = True
if make_commit_today:
if commit_frequency['strategy'] == 'fixed':
num_commits = commit_frequency['min_commits']
else:
num_commits = random.randint(commit_frequency['min_commits'], commit_frequency['max_commits'])
for _ in range(num_commits):
message = random.choice(messages)
make_commit(repo_path, message, current_date)
current_date += datetime.timedelta(days=1)
push_changes(repo_path)
print(f"Completed processing for repository: {repo_name}")
def get_pull_request_count():
"""
Prompts the user to input the number of pull requests to create.
Returns:
int: Number of pull requests to create.
"""
try:
num_prs = int(input("Enter the number of pull requests to create: "))
if num_prs < 1:
print("Number of pull requests must be at least 1.")
sys.exit(1)
return num_prs
except ValueError:
print("Invalid input. Please enter an integer.")
sys.exit(1)
def get_pr_date_range():
"""
Prompts the user to input the start and end dates for pull request creation.
Returns:
tuple: Start date and end date as datetime.date objects.
"""
print("\nChoose date range for pull requests:")
print("1. Last 30 days")
print("2. Last 3 months")
print("3. Last 6 months")
print("4. Last year")
print("5. Custom date range")
choice = input("Enter your choice (1-5): ").strip()
today = datetime.date.today()
if choice == '1':
start_date = today - datetime.timedelta(days=30)
end_date = today
print(f"Selected: Last 30 days ({start_date} to {end_date})")
elif choice == '2':
start_date = today - datetime.timedelta(days=90)
end_date = today
print(f"Selected: Last 3 months ({start_date} to {end_date})")
elif choice == '3':
start_date = today - datetime.timedelta(days=180)
end_date = today
print(f"Selected: Last 6 months ({start_date} to {end_date})")
elif choice == '4':
start_date = today - datetime.timedelta(days=365)
end_date = today
print(f"Selected: Last year ({start_date} to {end_date})")
elif choice == '5':
try:
start_date_str = input("Enter start date for PRs (YYYY-MM-DD): ").strip()
end_date_str = input("Enter end date for PRs (YYYY-MM-DD): ").strip()
start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d").date()
if start_date > end_date:
print("Start date must be before end date.")
sys.exit(1)
except ValueError:
print("Invalid date format. Please use YYYY-MM-DD.")
sys.exit(1)
else:
print("Invalid choice. Please enter a number between 1 and 5.")
sys.exit(1)
return start_date, end_date
def create_branch(repo_path, branch_name):
"""
Creates a new branch in the repository.
Args:
repo_path (str): The path to the cloned repository.
branch_name (str): The name of the branch to create.
"""
run_command(["git", "checkout", "-b", branch_name], cwd=repo_path)
def create_pull_request(repo_name, token, branch_name, title, body):
"""
Creates a pull request using the GitHub API.
Args:
repo_name (str): The name of the repository.
token (str): GitHub Personal Access Token for authentication.
branch_name (str): The name of the branch to create the pull request from.
title (str): The title of the pull request.
body (str): The description of the pull request.
Returns:
int or None: The pull request number if created successfully, None otherwise.
"""
# Get the username from the GitHub API
user_url = "https://api.github.com/user"
headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json"
}
user_response = requests.get(user_url, headers=headers)
if user_response.status_code != 200:
print(f"Failed to get user information. Status Code: {user_response.status_code}")
return None
username = user_response.json()["login"]
# Create the pull request
pr_url = f"https://api.github.com/repos/{username}/{repo_name}/pulls"
pr_data = {
"title": title,
"body": body,
"head": branch_name,
"base": "main"
}
pr_response = requests.post(pr_url, headers=headers, json=pr_data)
if pr_response.status_code == 201:
pr_number = pr_response.json()['number']
print(f"Pull request #{pr_number} created successfully: {pr_response.json()['html_url']}")
return pr_number
else:
print(f"Failed to create pull request. Status Code: {pr_response.status_code}")
print("Response:", pr_response.json())
return None
def merge_pull_request(repo_name, token, pr_number):
"""
Merges a pull request using the GitHub API.
Args:
repo_name (str): The name of the repository.
token (str): GitHub Personal Access Token for authentication.
pr_number (int): The pull request number to merge.
Returns:
bool: True if the pull request was merged successfully, False otherwise.
"""
# Get the username from the GitHub API
user_url = "https://api.github.com/user"
headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json"
}
user_response = requests.get(user_url, headers=headers)
if user_response.status_code != 200:
return False
username = user_response.json()["login"]
# Merge the pull request
merge_url = f"https://api.github.com/repos/{username}/{repo_name}/pulls/{pr_number}/merge"
merge_data = {
"commit_title": "Automated merge",
"commit_message": "Merged by GitCommitAssistant",
"merge_method": "merge"
}
merge_response = requests.put(merge_url, headers=headers, json=merge_data)
if merge_response.status_code == 200:
print(f"Pull request #{pr_number} merged successfully")
return True
else:
print(f"Failed to merge pull request #{pr_number}")
return False
def merge_pull_request_with_date(repo_name, token, pr_number, merge_date):
"""
Attempts to merge a pull request and then update the merge commit date locally.
Args:
repo_name (str): The name of the repository.
token (str): GitHub Personal Access Token for authentication.
pr_number (int): The pull request number to merge.
merge_date (datetime.date): The desired merge date.
Returns:
bool: True if successful, False otherwise.
"""
# First, try regular merge
success = merge_pull_request(repo_name, token, pr_number)
if not success:
return False
# Note: GitHub API doesn't allow setting merge commit dates directly
# The commits within the PR will have the correct dates, which is what matters for activity
return True
def create_and_merge_pr(repo_name, repo_path, token, commit_messages, pr_index, pr_date):
"""
Creates a single pull request and merges it with proper backdating.
Args:
repo_name (str): The name of the repository.
repo_path (str): The path to the cloned repository.
token (str): GitHub Personal Access Token for authentication.
commit_messages (list): List of commit messages to use.
pr_index (int): The index of the PR being created.
pr_date (datetime.date): The date for the PR.
Returns:
bool: True if successful, False otherwise.
"""
try:
# Create a new branch
branch_name = f"feature/automated-pr-{pr_index}-{random.randint(1000, 9999)}"
create_branch(repo_path, branch_name)
# Make multiple commits on the branch to simulate development over time
# This helps with GitHub's activity tracking
for i in range(random.randint(1, 3)): # 1-3 commits per PR
file_suffix = random.randint(100, 999)
file_name = f"pr_feature_{pr_index}_{i+1}_{file_suffix}.txt"
pr_file = os.path.join(repo_path, file_name)
with open(pr_file, "w") as f:
f.write(f"This is commit #{i+1} for automated pull request #{pr_index}.\n")
f.write(f"Created at: {pr_date.isoformat()}\n")
f.write(f"Feature description: {random.choice(commit_messages)}\n")
# Commit with the specified date (slightly offset for multiple commits)
commit_date = pr_date + datetime.timedelta(hours=i*2) # Spread commits across the day
commit_message = random.choice(commit_messages)
make_pr_commit(repo_path, f"Add feature {pr_index} part {i+1}: {commit_message}", commit_date, file_name)
# Push the branch
run_command(["git", "push", "-u", "origin", branch_name], cwd=repo_path)
# Create the pull request
pr_title = f"Feature {pr_index}: {random.choice(commit_messages)}"
pr_body = f"This pull request adds feature {pr_index}.\n\nImplemented on {pr_date.strftime('%Y-%m-%d')}\n\n{random.choice(commit_messages)}"
pr_number = create_pull_request(repo_name, token, branch_name, pr_title, pr_body)
# If PR was created successfully, merge it immediately
if pr_number:
# Create a merge commit with the correct date
merge_success = merge_pull_request_with_date(repo_name, token, pr_number, pr_date)
if not merge_success:
# Fallback to regular merge if date-specific merge fails
merge_pull_request(repo_name, token, pr_number)
# Switch back to main branch for the next PR
run_command(["git", "checkout", "main"], cwd=repo_path)
return True
except Exception as e:
print(f"Error creating PR {pr_index}: {e}")
return False
def generate_pull_requests(repos, num_prs, start_date, end_date, temp_dir, token):
"""
Generates pull requests for each repository across the specified date range.
This approach creates commits on historical dates and pushes them individually.
Args:
repos (dict): Dictionary containing repository details.
num_prs (int): Number of pull requests to create per repository.
start_date (datetime.date): The start date for PR creation.
end_date (datetime.date): The end date for PR creation.
temp_dir (str): Path to the temporary directory.
token (str): GitHub Personal Access Token for authentication.
"""
print(f"\n🚀 Creating {num_prs} pull requests from {start_date} to {end_date}")
print("⚠️ Note: This will create commits on historical dates for proper GitHub activity tracking")
# Load commit messages to use as PR titles and descriptions
commit_messages = load_commit_messages()
# Calculate date distribution for PRs
total_days = (end_date - start_date).days + 1
for repo_name, repo_info in repos.items():
print(f"\nProcessing repository: {repo_name}")
repo_path = clone_repo(repo_name, repo_info["url"], temp_dir)
# Group PRs by date for better GitHub activity distribution
date_groups = {}
for i in range(num_prs):
if total_days >= num_prs:
day_offset = (i * total_days) // num_prs
else:
day_offset = random.randint(0, total_days - 1)
pr_date = start_date + datetime.timedelta(days=day_offset)
if pr_date not in date_groups:
date_groups[pr_date] = []
date_groups[pr_date].append(i + 1)
# Process PRs grouped by date
for pr_date, pr_indices in sorted(date_groups.items()):
print(f"Creating {len(pr_indices)} PRs for {pr_date}")
for pr_index in pr_indices:
success = create_historical_pr(repo_name, repo_path, token, commit_messages, pr_index, pr_date)
if not success:
print(f"Failed to create PR {pr_index} for {repo_name}")
print(f"Completed processing pull requests for repository: {repo_name}")
def create_historical_pr(repo_name, repo_path, token, commit_messages, pr_index, pr_date):
"""
Creates a pull request with commits that have historical dates.
Uses a different approach to ensure GitHub recognizes the historical activity.
Args:
repo_name (str): The name of the repository.
repo_path (str): The path to the cloned repository.
token (str): GitHub Personal Access Token for authentication.
commit_messages (list): List of commit messages to use.
pr_index (int): The index of the PR being created.
pr_date (datetime.date): The date for the PR.
Returns:
bool: True if successful, False otherwise.
"""
try:
# Create a new branch
branch_name = f"feature/historical-pr-{pr_index}-{pr_date.strftime('%Y%m%d')}"
create_branch(repo_path, branch_name)
# Create multiple commits with the historical date
num_commits = random.randint(1, 3)
for i in range(num_commits):
file_suffix = random.randint(100, 999)
file_name = f"historical_feature_{pr_index}_{i+1}_{file_suffix}.txt"
pr_file = os.path.join(repo_path, file_name)
# Create file content
with open(pr_file, "w") as f:
f.write(f"Historical PR #{pr_index} - Commit {i+1}\n")
f.write(f"Date: {pr_date.isoformat()}\n")
f.write(f"Feature: {random.choice(commit_messages)}\n")
f.write(f"Timestamp: {pr_date.strftime('%Y-%m-%d %H:%M:%S')}\n")
# Create commit with historical date
commit_time = pr_date + datetime.timedelta(hours=i*3, minutes=random.randint(0, 59))
commit_message = f"Add historical feature {pr_index}.{i+1}: {random.choice(commit_messages)}"
# Stage the file
run_command(["git", "add", file_name], cwd=repo_path)
# Create commit with historical date
env = os.environ.copy()
env["GIT_AUTHOR_DATE"] = commit_time.strftime("%Y-%m-%dT%H:%M:%S")
env["GIT_COMMITTER_DATE"] = commit_time.strftime("%Y-%m-%dT%H:%M:%S")
run_command(["git", "commit", "-m", commit_message], cwd=repo_path, env=env)
# Push the branch with historical commits
run_command(["git", "push", "-u", "origin", branch_name], cwd=repo_path)
# Create the pull request
pr_title = f"Historical Feature {pr_index}: {random.choice(commit_messages)}"
pr_body = f"This pull request implements feature {pr_index}.\n\nDeveloped on: {pr_date.strftime('%Y-%m-%d')}\n\n{random.choice(commit_messages)}"
pr_number = create_pull_request(repo_name, token, branch_name, pr_title, pr_body)
# Merge the PR immediately
if pr_number:
merge_pull_request(repo_name, token, pr_number)
# Switch back to main branch
run_command(["git", "checkout", "main"], cwd=repo_path)
return True
except Exception as e:
print(f"Error creating historical PR {pr_index}: {e}")
return False
def prepare_commit_data(commit_date, commit_index, commit_messages):
"""
Prepares commit data without touching the git repository (thread-safe).
Args:
commit_date (datetime.date): The date for the commit.
commit_index (int): The index of this commit.
commit_messages (list): List of commit messages to choose from.
Returns:
dict: Commit data including file info, timestamp, and message.
"""
# Create unique file for this commit
timestamp = datetime.datetime.combine(commit_date, datetime.time(
hour=random.randint(9, 17),
minute=random.randint(0, 59),
second=random.randint(0, 59)
))
file_name = f"pr_commit_{commit_date.strftime('%Y%m%d')}_{commit_index}_{random.randint(1000, 9999)}.txt"
# Prepare file content
file_content = f"Historical commit #{commit_index} for PR simulation\n"
file_content += f"Date: {commit_date.isoformat()}\n"
file_content += f"Timestamp: {timestamp.strftime('%Y-%m-%d %H:%M:%S')}\n"
file_content += f"Feature: {random.choice(commit_messages)}\n"
commit_message = f"Historical commit {commit_index}: {random.choice(commit_messages)}"
return {
'file_name': file_name,
'file_content': file_content,
'timestamp': timestamp,
'commit_message': commit_message,
'commit_date': commit_date,
'commit_index': commit_index
}
def create_historical_commit_from_data(repo_path, commit_data):
"""
Creates a commit from prepared data (not thread-safe, must be called sequentially).
Args:
repo_path (str): The path to the repository.
commit_data (dict): Prepared commit data.
Returns:
bool: True if successful, False otherwise.
"""
try:
file_path = os.path.join(repo_path, commit_data['file_name'])
# Create file
with open(file_path, "w") as f:
f.write(commit_data['file_content'])
# Stage the file
run_command(["git", "add", commit_data['file_name']], cwd=repo_path)
# Create commit with historical timestamp
env = os.environ.copy()
env["GIT_AUTHOR_DATE"] = commit_data['timestamp'].strftime("%Y-%m-%dT%H:%M:%S")
env["GIT_COMMITTER_DATE"] = commit_data['timestamp'].strftime("%Y-%m-%dT%H:%M:%S")
run_command(["git", "commit", "-m", commit_data['commit_message']], cwd=repo_path, env=env)
return True
except Exception as e:
print(f"Error creating commit {commit_data['commit_index']}: {e}")
return False
def generate_historical_commits_for_prs(repos, num_prs, start_date, end_date, temp_dir):
"""
Generates commits with historical dates using parallel processing for maximum speed.
This is the correct approach for backdating GitHub activity.
Args:
repos (dict): Dictionary containing repository details.
num_prs (int): Number of pull requests worth of commits to create.
start_date (datetime.date): The start date for PR creation.
end_date (datetime.date): The end date for PR creation.
temp_dir (str): Path to the temporary directory.
"""
print(f"\n🚀 Creating historical commits for {num_prs} PRs from {start_date} to {end_date}")
print("⚡ Using parallel processing for maximum speed (10 concurrent operations)")
print("✅ This approach creates commits with historical dates that GitHub will recognize")
# Load commit messages
commit_messages = load_commit_messages()
# Calculate date distribution
total_days = (end_date - start_date).days + 1
for repo_name, repo_info in repos.items():
print(f"\nProcessing repository: {repo_name}")
repo_path = clone_repo(repo_name, repo_info["url"], temp_dir)
# Create a list of all commits to be made
all_commits = []
for i in range(num_prs):
if total_days >= num_prs:
day_offset = (i * total_days) // num_prs
else:
day_offset = random.randint(0, total_days - 1)
commit_date = start_date + datetime.timedelta(days=day_offset)
# Each PR gets 1-3 commits
commits_per_pr = random.randint(1, 3)
for j in range(commits_per_pr):
all_commits.append((commit_date, len(all_commits) + 1))
print(f"Creating {len(all_commits)} total commits with optimized parallel processing...")
# Step 1: Prepare all commit data in parallel (thread-safe)
print("📋 Preparing commit data in parallel...")
all_commit_data = []
batch_size = 50 # Larger batches for data preparation
total_batches = (len(all_commits) + batch_size - 1) // batch_size
for batch_num in range(total_batches):
start_idx = batch_num * batch_size
end_idx = min(start_idx + batch_size, len(all_commits))
batch_commits = all_commits[start_idx:end_idx]
# Prepare commit data in parallel
with ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for commit_date, commit_index in batch_commits:
future = executor.submit(prepare_commit_data, commit_date, commit_index, commit_messages)
futures.append(future)
# Collect all prepared data
for future in futures:
commit_data = future.result()
if commit_data:
all_commit_data.append(commit_data)
print(f"✅ Prepared batch {batch_num + 1}/{total_batches}")
# Step 2: Create commits sequentially (git operations must be sequential)
print(f"🚀 Creating {len(all_commit_data)} commits sequentially...")
successful_commits = 0
for i, commit_data in enumerate(all_commit_data, 1):
if create_historical_commit_from_data(repo_path, commit_data):
successful_commits += 1
# Progress update every 100 commits
if i % 100 == 0 or i == len(all_commit_data):
print(f"Progress: {i}/{len(all_commit_data)} commits created ({successful_commits} successful)")
print(f"✅ All commits completed: {successful_commits}/{len(all_commit_data)} successful")
# Push all historical commits at once
print(f"Pushing all {len(all_commits)} historical commits for {repo_name}...")
push_changes(repo_path)
print(f"✅ Completed historical commits for repository: {repo_name}")
print(f"🎯 Total commits created: {len(all_commits)}")
def spinner(spinner_event):
"""
Displays a spinning loader in green while processing.
Args:
spinner_event (threading.Event): Event to signal the spinner to stop.
"""
spinner_chars = itertools.cycle(['|', '/', '-', '\\'])
while not spinner_event.is_set():
sys.stdout.write('\r\033[92m' + next(spinner_chars) + ' Processing...\033[0m')
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\r\033[92mDone! \033[0m\n')
def main():
"""
Main function to execute the script.
"""
print("\nWelcome to GitCommitAssistant!")
print("What would you like to do?")
print("1. Generate commits")