-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkflow_manager.py
More file actions
316 lines (268 loc) · 11 KB
/
workflow_manager.py
File metadata and controls
316 lines (268 loc) · 11 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
#!/usr/bin/env python3
"""
Workflow Manager - Handles GitHub Actions workflow operations.
"""
from typing import Dict, List, Optional, Tuple
from github import Github
from github.GithubException import GithubException
class WorkflowManager:
"""Manages GitHub Actions workflows."""
def __init__(self, github: Github, repo_name: str, retryable_workflows: List[str] = None):
"""
Initialize workflow manager.
Args:
github: GitHub API client
repo_name: Repository name in format 'owner/repo'
retryable_workflows: List of workflow names that can be retried
"""
self.github = github
self.repo = github.get_repo(repo_name)
self.retryable_workflows = retryable_workflows or []
def get_workflow_runs(self, sha: str) -> List[Dict]:
"""
Get all workflow runs for a specific commit.
Args:
sha: Commit SHA
Returns:
List of workflow run information
"""
runs = self.repo.get_workflow_runs(head_sha=sha)
workflow_runs = []
for run in runs:
workflow_runs.append({
"id": run.id,
"name": run.name,
"status": run.status,
"conclusion": run.conclusion,
"workflow_id": run.workflow_id,
"created_at": run.created_at.isoformat() if run.created_at else None,
"url": run.html_url,
})
return workflow_runs
def get_workflow_status(self, sha: str, branch: str = None) -> Dict:
"""
Get status summary of all workflows for a commit and optionally branch.
Args:
sha: Commit SHA
branch: Optional branch name to also check workflows for the branch
Returns:
Dictionary with workflow status information
"""
# Get runs for the specific SHA
runs = self.get_workflow_runs(sha)
# Also get runs for the branch if provided
# This is important because auto-fix commits might not trigger all workflows,
# but workflows from earlier commits in the PR might still be running
if branch:
try:
branch_runs = self.repo.get_workflow_runs(branch=branch)
branch_workflow_runs = []
for run in branch_runs:
branch_workflow_runs.append({
"id": run.id,
"name": run.name,
"status": run.status,
"conclusion": run.conclusion,
"workflow_id": run.workflow_id,
"created_at": run.created_at.isoformat() if run.created_at else None,
"url": run.html_url,
})
# Combine and deduplicate by run ID
all_runs = {run["id"]: run for run in runs}
for run in branch_workflow_runs:
if run["id"] not in all_runs:
all_runs[run["id"]] = run
runs = list(all_runs.values())
except Exception as e:
print(f"Warning: Could not get branch workflows: {e}")
# Group by workflow name
workflows = {}
for run in runs:
name = run["name"]
if name not in workflows:
workflows[name] = {
"name": name,
"status": run["status"],
"conclusion": run.get("conclusion"),
"url": run["url"],
"latest_run_id": run["id"],
}
else:
# Keep the latest run
if run["id"] > workflows[name]["latest_run_id"]:
workflows[name].update({
"status": run["status"],
"conclusion": run.get("conclusion"),
"url": run["url"],
"latest_run_id": run["id"],
})
return {
"sha": sha,
"workflows": list(workflows.values()),
}
def are_all_checks_passed(self, sha: str, branch: str = None, exclude_workflows: List[str] = None) -> Tuple[bool, Dict]:
"""
Check if all checks and workflows have passed for a commit and branch.
This method checks:
1. All checks for the HEAD SHA
2. All workflow runs for the HEAD SHA
3. All workflow runs for the branch (if provided)
Args:
sha: Commit SHA
branch: Optional branch name to also check workflows for the branch
exclude_workflows: List of workflow names to exclude from the check
Returns:
Tuple of (all_passed: bool, details: Dict)
"""
if exclude_workflows is None:
exclude_workflows = []
import requests
# Get checks for the SHA
try:
checks_url = f"https://api.github.com/repos/{self.repo.full_name}/commits/{sha}/check-runs"
headers = {"Accept": "application/vnd.github.v3+json"}
auth = self.github._Github__requester._Requester__authorizationHeader
if auth:
headers["Authorization"] = auth
response = requests.get(checks_url, headers=headers, params={"per_page": 100})
checks_data = response.json() if response.status_code == 200 else {}
check_runs = checks_data.get("check_runs", [])
except Exception as e:
print(f"Warning: Could not get checks: {e}")
check_runs = []
# Get status for the SHA
try:
status_url = f"https://api.github.com/repos/{self.repo.full_name}/commits/{sha}/status"
response = requests.get(status_url, headers=headers)
status_data = response.json() if response.status_code == 200 else {}
combined_status = status_data.get("state", "unknown")
except Exception as e:
print(f"Warning: Could not get status: {e}")
combined_status = "unknown"
# Get workflow status (includes branch workflows if branch is provided)
workflow_status = self.get_workflow_status(sha, branch)
# Check if all checks passed
all_checks_passed = (
len(check_runs) > 0 and
all(check["status"] == "completed" and check["conclusion"] == "success"
for check in check_runs if check.get("conclusion") != "skipped") and
combined_status == "success"
)
# Check if all workflows passed (excluding specified workflows)
workflows = workflow_status.get("workflows", [])
# Filter out excluded workflows
relevant_workflows = [
w for w in workflows
if w.get("name") not in exclude_workflows
]
all_workflows_passed = (
len(relevant_workflows) > 0 and
all(w.get("status") == "completed" and w.get("conclusion") == "success"
for w in relevant_workflows)
)
# Check for running workflows (excluding excluded ones)
running_workflows = [
w for w in workflows
if w.get("name") not in exclude_workflows
and w.get("status") in ["in_progress", "queued", "waiting"]
]
# Check for failed workflows (excluding excluded ones)
failed_workflows = [
w for w in workflows
if w.get("name") not in exclude_workflows
and w.get("status") == "completed" and w.get("conclusion") == "failure"
]
# Check for pending checks
pending_checks = [
check for check in check_runs
if check.get("status") != "completed"
]
# Check for failed checks
failed_checks = [
check for check in check_runs
if check.get("status") == "completed" and
check.get("conclusion") not in ["success", "skipped"]
]
truly_all_passed = (
all_checks_passed and
all_workflows_passed and
len(running_workflows) == 0 and
len(failed_workflows) == 0 and
len(pending_checks) == 0 and
len(failed_checks) == 0
)
details = {
"all_checks_passed": all_checks_passed,
"all_workflows_passed": all_workflows_passed,
"truly_all_passed": truly_all_passed,
"running_workflows": running_workflows,
"failed_workflows": failed_workflows,
"pending_checks": pending_checks,
"failed_checks": failed_checks,
"total_checks": len(check_runs),
"total_workflows": len(relevant_workflows),
"combined_status": combined_status,
"excluded_workflows": exclude_workflows,
}
return (truly_all_passed, details)
def retry_workflow(self, sha: str, workflow_name: str) -> bool:
"""
Retry a specific workflow.
Args:
sha: Commit SHA
workflow_name: Name of the workflow to retry
Returns:
True if workflow was found and retry was triggered
"""
# Check if workflow is retryable
if self.retryable_workflows and workflow_name not in self.retryable_workflows:
return False
try:
# Get workflow runs for this commit
runs = self.repo.get_workflow_runs(head_sha=sha)
# Find the workflow by name
for run in runs:
if run.name == workflow_name:
# Re-run the workflow
run.rerun()
return True
return False
except GithubException as e:
print(f"Error retrying workflow: {e}")
return False
def retry_failed_workflows(self, sha: str) -> List[str]:
"""
Retry all failed workflows for a commit.
Args:
sha: Commit SHA
Returns:
List of workflow names that were retried
"""
runs = self.repo.get_workflow_runs(head_sha=sha)
retried = []
for run in runs:
# Only retry failed workflows that are not currently running
# and are in the retryable list (if list is provided)
if run.conclusion == "failure" and run.status != "in_progress":
# Check if workflow is retryable
if self.retryable_workflows and run.name not in self.retryable_workflows:
continue
try:
run.rerun()
retried.append(run.name)
except GithubException as e:
print(f"Error retrying {run.name}: {e}")
return retried
def get_failed_workflows(self, sha: str) -> List[Dict]:
"""
Get list of failed workflows.
Args:
sha: Commit SHA
Returns:
List of failed workflow information
"""
runs = self.get_workflow_runs(sha)
return [
run for run in runs
if run.get("conclusion") == "failure"
]