-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_status.py
More file actions
100 lines (81 loc) · 2.43 KB
/
github_status.py
File metadata and controls
100 lines (81 loc) · 2.43 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
#!/usr/bin/env python3
"""GitHub Commit Status API wrapper using urllib (zero external dependencies)."""
import json
import os
import re
import sys
import urllib.error
import urllib.request
def parse_repo_url(url):
"""Extract (owner, repo) from a GitHub URL.
Handles:
- https://github.com/Owner/Repo.git
- git@github.com:Owner/Repo.git
"""
# HTTPS format
m = re.match(r"https?://[^/]+/([^/]+)/([^/]+?)(?:\.git)?$", url)
if m:
return m.group(1), m.group(2)
# SSH format
m = re.match(r"git@[^:]+:([^/]+)/([^/]+?)(?:\.git)?$", url)
if m:
return m.group(1), m.group(2)
return "", ""
def build_status_context(prefix, job_name):
"""Build status context string, e.g. 'ci/infiniops/nvidia_gpu'."""
return f"{prefix}/{job_name}"
def post_commit_status(
owner,
repo,
sha,
state,
context,
description,
target_url=None,
token=None,
):
"""Post a commit status to GitHub.
Args:
state: One of 'pending', 'success', 'failure', 'error'.
Returns True on success, False on failure.
"""
token = token or os.environ.get("GITHUB_TOKEN", "")
if not token:
print("warning: GITHUB_TOKEN not set, skipping status update", file=sys.stderr)
return False
if not owner or not repo or not sha:
print(
"warning: missing owner/repo/sha, skipping status update", file=sys.stderr
)
return False
url = f"https://api.github.com/repos/{owner}/{repo}/statuses/{sha}"
body = {
"state": state,
"context": context,
"description": description[:140],
}
if target_url:
body["target_url"] = target_url
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
headers={
"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json",
"Content-Type": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return 200 <= resp.status < 300
except urllib.error.HTTPError as e:
print(
f"warning: GitHub status API returned {e.code}: {e.reason}",
file=sys.stderr,
)
return False
except urllib.error.URLError as e:
print(f"warning: GitHub status API error: {e.reason}", file=sys.stderr)
return False