-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
197 lines (159 loc) · 6.47 KB
/
main.py
File metadata and controls
197 lines (159 loc) · 6.47 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
import json
import uuid
import time
import os
import argparse
from datetime import datetime
from pathlib import Path
from git_manager import GitManager
from github_tool import GitHubTool
from token_manager import TokenManager
from proxy_manager import ProxyManager
from notifier import Notifier
from logger import setup_logger
def load_config():
"""Load configuration"""
with open("config.json") as f:
return json.load(f)
def load_state():
"""Load state"""
try:
with open("state.json") as f:
return json.load(f)
except:
return {"last_completed_pr": 0}
def save_state(state):
"""Save state"""
with open("state.json", "w") as f:
json.dump(state, f, indent=2)
def generate_content(index):
"""Generate README content"""
return f"""
---
## Automated Contribution #{index}
Timestamp: {datetime.now().isoformat()}
UUID: {uuid.uuid4()}
---
"""
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description="GitHub Automation Tool")
parser.add_argument("--count", type=int, help="Override PR count")
parser.add_argument("--delay", type=int, help="Override delay seconds")
parser.add_argument("--dry-run", action="store_true", help="Enable dry run mode")
parser.add_argument("--no-merge", action="store_true", help="Disable auto merge")
parser.add_argument("--reset", action="store_true", help="Reset state")
parser.add_argument("--use-proxies", action="store_true", help="Use proxies")
return parser.parse_args()
def main():
"""Main function"""
args = parse_args()
config = load_config()
state = load_state()
logger = setup_logger()
if args.reset:
state["last_completed_pr"] = 0
save_state(state)
print("🔄 State reset.")
return
# Apply overrides
if args.count:
config["pr_count"] = args.count
if args.delay:
config["delay_seconds"] = args.delay
if args.dry_run:
config["dry_run"] = True
if args.no_merge:
config["auto_merge"] = False
# Change to repo directory
os.chdir(config["repo_path"])
# Initialize managers
git = GitManager(config["base_branch"], config["max_retries"], logger)
gh = GitHubTool(config["base_branch"], config["max_retries"], logger)
token_manager = TokenManager()
proxy_manager = ProxyManager() if args.use_proxies else None
notifier = Notifier(config.get("slack_webhook"), config.get("discord_webhook"))
start = state["last_completed_pr"] + 1
end = config["pr_count"]
print(f"🚀 Starting from PR #{start}")
print(f"⏱️ Delay: {config['delay_seconds']} seconds")
consecutive_failures = 0
for i in range(start, end + 1):
try:
print(f"\n🔹 Processing PR #{i}")
branch = f"automation-{i}-{uuid.uuid4().hex[:8]}"
# Git operations
if not git.sync_base():
raise Exception("Failed to sync base branch")
if not git.create_branch(branch):
raise Exception(f"Failed to create branch {branch}")
# Update README
with open(config["readme_file"], "a", encoding="utf-8") as f:
f.write(generate_content(i))
if not git.commit(config["readme_file"], f"Automated update #{i}"):
print("⚠ No changes to commit")
continue
if not config["dry_run"]:
# Get token
token, _ = token_manager.get_best_token()
if not token:
raise Exception("No valid tokens available")
# Push and create PR
if not git.push(branch):
raise Exception("Failed to push branch")
pr_number = gh.create_pr(
f"Automated PR #{i}",
"Automated system update via GitHub Automation Tool.",
branch
)
if pr_number:
print(f"✅ PR #{i} created successfully (PR #{pr_number})")
# Send creation notification
notifier.send(
f"✅ PR #{i} created successfully\n"
f"Branch: {branch}\n"
f"PR Number: #{pr_number}",
"success"
)
# Auto-merge if enabled
if config["auto_merge"]:
merge_success = gh.merge_pr(branch)
if merge_success:
print(f"✅ PR #{pr_number} merged successfully")
notifier.send(
f"✅ PR #{i} merged successfully\n"
f"PR Number: #{pr_number}",
"success"
)
else:
print(f"⚠️ Failed to merge PR #{pr_number}")
notifier.send(
f"⚠️ PR #{i} created but merge failed\n"
f"PR Number: #{pr_number}",
"warning"
)
else:
print(f"✅ PR #{i} created successfully")
# Update state
state["last_completed_pr"] = i
save_state(state)
# Reset failure counter
consecutive_failures = 0
# Send notification every 10 PRs
if i % 10 == 0:
notifier.send(f"✅ Progress: {i}/{end} PRs completed")
# Delay
if i < end:
print(f"⏱️ Waiting {config['delay_seconds']} seconds...")
time.sleep(config["delay_seconds"])
except Exception as e:
consecutive_failures += 1
logger.error(f"PR #{i} failed: {str(e)}")
notifier.send(f"❌ Failed at PR #{i}: {str(e)[:100]}")
if consecutive_failures >= 5:
print("❌ Too many consecutive failures. Stopping.")
break
time.sleep(30)
print("\n🎉 Automation completed!")
if __name__ == "__main__":
main()