Repository navigation
Expand file tree
/
Copy pathgithub.py
More file actions
145 lines (123 loc) · 4.88 KB
/
Copy pathgithub.py
File metadata and controls
145 lines (123 loc) · 4.88 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
"""GitHub side of open_pr. Runs only on the workflow host, which holds GITHUB_TOKEN.
The token reaches git through an http.extraheader set in the environment, so
it never appears in a command line, a remote URL, or the .git/config of a
clone that could later be copied into a sandbox.
"""
from __future__ import annotations
import base64
import os
import re
import subprocess
from pathlib import Path
import httpx
API = "https://api.github.com"
DIFF_PATH = re.compile(r"^diff --git a/(.+?) b/(.+)$", re.MULTILINE)
# Changes here can run code with repository secrets once merged or, for some
# triggers, as soon as the PR opens. Off by default; see README "Security".
PROTECTED_PREFIXES = (".github/workflows/", ".github/actions/")
def token() -> str:
value = os.environ.get("GITHUB_TOKEN", "")
if not value:
raise RuntimeError("GITHUB_TOKEN is not set on the workflow service")
return value
def git_env(github_token: str) -> dict[str, str]:
"""Environment that authenticates git to github.com without exposing the token."""
basic = base64.b64encode(f"x-access-token:{github_token}".encode()).decode()
return {
**os.environ,
"GIT_TERMINAL_PROMPT": "0",
"GIT_CONFIG_COUNT": "1",
"GIT_CONFIG_KEY_0": "http.https://github.com/.extraheader",
"GIT_CONFIG_VALUE_0": f"AUTHORIZATION: basic {basic}",
}
def touched_paths(diff: str) -> list[str]:
"""Every path a unified git diff creates, edits, renames or deletes."""
paths: list[str] = []
for a, b in DIFF_PATH.findall(diff):
paths += [a, b]
return list(dict.fromkeys(paths))
def check_diff_policy(diff: str, allow_workflow_changes: bool = False) -> None:
if allow_workflow_changes:
return
blocked = [p for p in touched_paths(diff) if p.startswith(PROTECTED_PREFIXES)]
if blocked:
raise PermissionError(
"The agent changed CI configuration, which this template refuses to push: "
+ ", ".join(blocked)
+ ". Set ALLOW_WORKFLOW_CHANGES=true to allow it."
)
def run_git(args: list[str], cwd: Path, env: dict[str, str]) -> str:
result = subprocess.run(["git", *args], cwd=cwd, env=env, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"git {args[0]} failed: {result.stderr.strip()[-2000:]}")
return result.stdout.strip()
def clone(repo: str, base: str, dest: Path, github_token: str) -> None:
env = git_env(github_token)
run_git(
["clone", "--depth", "1", "--branch", base, f"https://github.com/{repo}.git", str(dest)],
cwd=dest.parent,
env=env,
)
def push_branch(
repo: str, base: str, branch: str, diff: str, message: str, workdir: Path, github_token: str
) -> None:
"""Apply the diff to a fresh clone of base, commit it, force-push the branch.
git apply only writes files; nothing from the repo or the diff is executed
on the host. Force-pushing the agent's own branch makes retries safe.
"""
env = git_env(github_token)
repo_dir = workdir / "repo"
clone(repo, base, repo_dir, github_token)
patch = workdir / "change.patch"
patch.write_text(diff)
run_git(["checkout", "-b", branch], repo_dir, env)
run_git(["apply", "--index", "--whitespace=nowarn", str(patch)], repo_dir, env)
run_git(
[
"-c",
"user.name=OpenHands on Render",
"-c",
"user.email=openhands@users.noreply.github.com",
"commit",
"--no-verify",
"-m",
message,
],
repo_dir,
env,
)
run_git(["push", "--force", "origin", f"HEAD:refs/heads/{branch}"], repo_dir, env)
async def open_or_update_pr(
repo: str,
base: str,
branch: str,
title: str,
body: str,
github_token: str,
transport: httpx.AsyncBaseTransport | None = None, # for tests
) -> str:
"""Open a pull request for branch, or reuse the open one. Returns its URL."""
owner = repo.split("/")[0]
headers = {
"Authorization": f"Bearer {github_token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
async with httpx.AsyncClient(
base_url=API, headers=headers, timeout=30, transport=transport
) as http:
existing = await http.get(
f"/repos/{repo}/pulls", params={"head": f"{owner}:{branch}", "state": "open"}
)
existing.raise_for_status()
if existing.json():
pr = existing.json()[0]
update = await http.patch(f"/repos/{repo}/pulls/{pr['number']}", json={"body": body})
update.raise_for_status()
return pr["html_url"]
created = await http.post(
f"/repos/{repo}/pulls",
json={"title": title, "head": branch, "base": base, "body": body, "draft": False},
)
created.raise_for_status()
return created.json()["html_url"]