Skip to content

Commit 4af579e

Browse files
authored
Merge pull request openSUSE#1806 from dmach/git-obs-pr-dump
Implement 'git-obs pr dump' command to store pull request information on disk
2 parents 7a91139 + ef3c488 commit 4af579e

File tree

8 files changed

+665
-39
lines changed

8 files changed

+665
-39
lines changed

osc/commands_git/pr_dump.py

Lines changed: 354 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,354 @@
1+
import os
2+
from typing import Optional
3+
4+
import osc.commandline_git
5+
6+
7+
class PullRequestDumpCommand(osc.commandline_git.GitObsCommand):
8+
"""
9+
Dump a pull request to disk
10+
11+
Return codes:
12+
- 0: default return code
13+
- 1-9: reserved for error states
14+
- 11: pull request(s) skipped due to no longer being open
15+
"""
16+
# NOTE: the return codes are according to `git-obs pr review interactive`
17+
18+
name = "dump"
19+
parent = "PullRequestCommand"
20+
21+
def init_arguments(self):
22+
from osc.commandline_git import complete_checkout_pr
23+
24+
self.add_argument(
25+
"--subdir-fmt",
26+
metavar="FMT",
27+
default="{pr.base_owner}/{pr.base_repo}/{pr.number}",
28+
help=(
29+
"Formatting string for a subdir associated with each pull request\n"
30+
"(default: '{pr.base_owner}/{pr.base_repo}/{pr.number}')\n"
31+
"Available values:\n"
32+
" - 'pr' object which is an instance of 'osc.gitea_api.PullRequest'\n"
33+
" - 'login_name', 'login_user' from the currently used Gitea login entry"
34+
),
35+
)
36+
37+
self.add_argument(
38+
"id",
39+
nargs="+",
40+
help="Pull request ID in <owner>/<repo>#<number> format",
41+
).completer = complete_checkout_pr
42+
43+
def clone_or_update(
44+
self,
45+
owner: str,
46+
repo: str,
47+
*,
48+
pr_number: Optional[int] = None,
49+
branch: Optional[str] = None,
50+
commit: str,
51+
directory: str,
52+
reference: Optional[str] = None,
53+
):
54+
from osc import gitea_api
55+
56+
if not pr_number and not branch:
57+
raise ValueError("Either 'pr_number' or 'branch' must be specified")
58+
59+
if not os.path.isdir(os.path.join(directory, ".git")):
60+
gitea_api.Repo.clone(
61+
self.gitea_conn,
62+
owner,
63+
repo,
64+
directory=directory,
65+
add_remotes=True,
66+
reference=reference,
67+
)
68+
69+
git = gitea_api.Git(directory)
70+
git_owner, git_repo = git.get_owner_repo()
71+
assert git_owner == owner, f"owner does not match: {git_owner} != {owner}"
72+
assert git_repo == repo, f"repo does not match: {git_repo} != {repo}"
73+
74+
if pr_number:
75+
# checkout the pull request and check if HEAD matches head/sha from Gitea
76+
pr_branch = git.fetch_pull_request(pr_number, commit=commit, force=True)
77+
git.switch(pr_branch)
78+
head_commit = git.get_branch_head()
79+
assert (
80+
head_commit == commit
81+
), f"HEAD of the current branch '{pr_branch}' is '{head_commit}' but the Gitea pull request points to '{commit}'"
82+
elif branch:
83+
git.switch(branch)
84+
85+
# run 'git fetch' only when the branch head is different to the expected commit
86+
head_commit = git.get_branch_head()
87+
if head_commit != commit:
88+
git.fetch()
89+
90+
if not git.branch_contains_commit(commit=commit, remote="origin"):
91+
raise RuntimeError(f"Branch '{branch}' doesn't contain commit '{commit}'")
92+
git.reset(commit, hard=True)
93+
else:
94+
raise ValueError("Either 'pr_number' or 'branch' must be specified")
95+
96+
def run(self, args):
97+
import json
98+
import shutil
99+
import sys
100+
from osc import gitea_api
101+
from osc import obs_api
102+
from osc.output import tty
103+
from osc.util.xml import xml_indent
104+
from osc.util.xml import ET
105+
106+
self.print_gitea_settings()
107+
108+
skipped = []
109+
pull_request_ids = args.id
110+
111+
for pr_id in pull_request_ids:
112+
owner, repo, number = gitea_api.PullRequest.split_id(pr_id)
113+
pr_obj = gitea_api.PullRequest.get(self.gitea_conn, owner, repo, number)
114+
115+
if pr_obj.state != "open":
116+
skipped.append(f"{owner}/{repo}#{number}")
117+
continue
118+
119+
path = args.subdir_fmt.format(
120+
pr=pr_obj,
121+
login_name=self.gitea_login.name,
122+
login_user=self.gitea_login.user,
123+
)
124+
# sanitize path for os.path.join()
125+
path = path.strip("/")
126+
127+
review_obj_list = pr_obj.get_reviews(self.gitea_conn)
128+
129+
# see https://github.com/go-gitea/gitea/blob/main/modules/structs/pull_review.go - look for "type ReviewStateType string"
130+
state_map = {
131+
"APPROVED": "accepted",
132+
"REQUEST_CHANGES": "declined",
133+
"REQUEST_REVIEW": "new", # review hasn't started
134+
"PENDING": "review", # review is in progress
135+
"COMMENT": "deleted", # just to make XML validation happy, we'll replace it with "comment" later
136+
}
137+
138+
xml_review_list = []
139+
for review_obj in review_obj_list:
140+
xml_review_list.append(
141+
{
142+
"state": state_map[review_obj.state],
143+
"who": review_obj.who,
144+
"created": review_obj.submitted_at,
145+
"when": review_obj.updated_at,
146+
"comment": review_obj.body,
147+
}
148+
)
149+
150+
# store timeline as <history/> entries
151+
timeline = gitea_api.IssueTimelineEntry.list(self.gitea_conn, owner, repo, number)
152+
xml_history_list = []
153+
for entry in timeline:
154+
if entry.is_empty():
155+
xml_history_list.append(
156+
{
157+
"who": "",
158+
"when": "",
159+
"description": "ERROR: Gitea returned ``None`` instead of a timeline entry",
160+
"comment": "",
161+
}
162+
)
163+
continue
164+
165+
text, body = entry.format()
166+
if text is None:
167+
continue
168+
xml_history_list.append(
169+
{
170+
"who": entry.user,
171+
"when": gitea_api.dt_sanitize(entry.created_at),
172+
"description": text,
173+
"comment": body or "",
174+
}
175+
)
176+
177+
req = obs_api.Request(
178+
id=pr_id,
179+
title=pr_obj.title,
180+
description=pr_obj.body,
181+
creator=pr_obj.user,
182+
# each pull request maps to only one action
183+
action_list=[
184+
{
185+
"type": "submit",
186+
"source": {
187+
"project": pr_obj.head_owner,
188+
"package": pr_obj.head_repo,
189+
"rev": pr_obj.head_commit,
190+
},
191+
"target": {
192+
"project": pr_obj.base_owner,
193+
"package": pr_obj.base_repo,
194+
},
195+
},
196+
],
197+
review_list=xml_review_list,
198+
history_list=xml_history_list,
199+
)
200+
201+
# HACK: changes to request XML that are not compatible with OBS
202+
req_xml = req.to_xml()
203+
204+
req_xml_action = req_xml.find("action")
205+
assert req_xml_action is not None
206+
req_xml_action.attrib["type"] = "gitea-pull-request"
207+
req_xml_action.insert(
208+
0,
209+
ET.Comment(
210+
"The type='gitea-pull-request' attribute value is a custom extension to the OBS XML schema."
211+
),
212+
)
213+
214+
req_xml_action_source = req_xml_action.find("source")
215+
assert req_xml_action_source is not None
216+
req_xml_action_source.append(
217+
ET.Comment("The 'branch' attribute is a custom extension to the OBS XML schema.")
218+
)
219+
req_xml_action_source.attrib["branch"] = pr_obj.head_branch
220+
221+
req_xml_action_target = req_xml_action.find("target")
222+
assert req_xml_action_target is not None
223+
req_xml_action_target.append(
224+
ET.Comment("The 'rev' and 'branch' attributes are custom extensions to the OBS XML schema.")
225+
)
226+
req_xml_action_target.attrib["rev"] = pr_obj.base_commit
227+
req_xml_action_target.attrib["branch"] = pr_obj.base_branch
228+
229+
req_xml_review_list = req_xml.findall("review")
230+
for req_xml_review in req_xml_review_list:
231+
if req_xml_review.attrib["state"] == "deleted":
232+
req_xml_review.attrib["state"] = "comment"
233+
req_xml_review.insert(
234+
0,
235+
ET.Comment("The state='comment' attribute value is a custom extension to the OBS XML schema."),
236+
)
237+
238+
metadata_dir = os.path.join(path, "metadata")
239+
try:
240+
# remove old metadata first to ensure that we never keep any of the old files on an update
241+
shutil.rmtree(metadata_dir)
242+
except FileNotFoundError:
243+
pass
244+
os.makedirs(metadata_dir, exist_ok=True)
245+
246+
with open(os.path.join(metadata_dir, "obs-request.xml"), "wb") as f:
247+
xml_indent(req_xml)
248+
ET.ElementTree(req_xml).write(f, encoding="utf-8")
249+
250+
with open(os.path.join(metadata_dir, "pr.json"), "w", encoding="utf-8") as f:
251+
json.dump(pr_obj._data, f, indent=4, sort_keys=True)
252+
253+
with open(os.path.join(metadata_dir, "base.json"), "w", encoding="utf-8") as f:
254+
json.dump(pr_obj._data["base"], f, indent=4, sort_keys=True)
255+
256+
with open(os.path.join(metadata_dir, "head.json"), "w", encoding="utf-8") as f:
257+
json.dump(pr_obj._data["head"], f, indent=4, sort_keys=True)
258+
259+
with open(os.path.join(metadata_dir, "reviews.json"), "w", encoding="utf-8") as f:
260+
json.dump([i._data for i in review_obj_list], f, indent=4, sort_keys=True)
261+
262+
with open(os.path.join(metadata_dir, "timeline.json"), "w", encoding="utf-8") as f:
263+
# the list doesn't come from Gitea API but is post-processed for our overall sanity
264+
json.dump(xml_history_list, f, indent=4, sort_keys=True)
265+
266+
base_dir = os.path.join(path, "base")
267+
# we must use the `merge_base` instead of `head_commit`, because the latter changes after merging the PR and the `base` directory would contain incorrect data
268+
self.clone_or_update(owner, repo, branch=pr_obj.base_branch, commit=pr_obj.merge_base, directory=base_dir)
269+
270+
head_dir = os.path.join(path, "head")
271+
self.clone_or_update(
272+
owner, repo, pr_number=pr_obj.number, commit=pr_obj.head_commit, directory=head_dir, reference=base_dir
273+
)
274+
275+
with open(os.path.join(metadata_dir, "submodules-base.json"), "w", encoding="utf-8") as f:
276+
base_submodules = gitea_api.Git(base_dir).get_submodules()
277+
json.dump(base_submodules, f, indent=4, sort_keys=True)
278+
279+
with open(os.path.join(metadata_dir, "submodules-head.json"), "w", encoding="utf-8") as f:
280+
head_submodules = gitea_api.Git(head_dir).get_submodules()
281+
json.dump(head_submodules, f, indent=4, sort_keys=True)
282+
283+
submodule_diff = {
284+
"added": {},
285+
"removed": {},
286+
"unchanged": {},
287+
"changed": {},
288+
}
289+
290+
# TODO: determine if the submodules point to packages or something else; submodules may point to arbitrary git repos such as other packages, projects or anything else
291+
all_submodules = sorted(set(base_submodules) | set(head_submodules))
292+
for i in all_submodules:
293+
294+
if base_submodules[i]:
295+
url = base_submodules[i].get("url","")
296+
if not url.startswith("../../"):
297+
print(f"Warning: incorrect path ({url}) in base submodule ({i})", file=sys.stderr)
298+
else:
299+
url = base_submodules[i].get("url","")
300+
if url.startswith("../../"):
301+
print(f"Warning: incorrect path ({url}) in head submodule ({i})", file=sys.stderr)
302+
303+
if i in base_submodules and i not in head_submodules:
304+
submodule_diff["removed"][i] = base_submodules[i]
305+
elif i not in base_submodules and i in head_submodules:
306+
submodule_diff["added"][i] = head_submodules[i]
307+
else:
308+
for key in ["branch", "path", "url"]:
309+
# we don't expect migrating packages to another paths, branches etc.
310+
if key not in base_submodules[i] and key in head_submodules[i]:
311+
# we allow adding new keys in the pull request to fix missing data
312+
pass
313+
else:
314+
base_value = base_submodules[i].get(key, None)
315+
head_value = head_submodules[i].get(key, None)
316+
assert base_value == head_value, f"Submodule metadata has changed: key='{key}', base_value='{base_value}', head_value='{head_value}'"
317+
318+
base_commit = base_submodules[i].get("commit","")
319+
head_commit = head_submodules[i].get("commit","")
320+
321+
if base_commit == head_commit:
322+
submodule_diff["unchanged"][i] = base_submodules[i]
323+
continue
324+
325+
# we expect the data to be identical in base and head with the exception of the commit
326+
# we also drop `commit` and add `base_commit` and `head_commit`
327+
data = base_submodules[i].copy()
328+
if base_commit:
329+
del data["commit"]
330+
data["base_commit"] = base_commit
331+
data["head_commit"] = head_commit
332+
submodule_diff["changed"][i] = data
333+
334+
with open(os.path.join(metadata_dir, "submodules-diff.json"), "w", encoding="utf-8") as f:
335+
json.dump(submodule_diff, f, indent=4, sort_keys=True)
336+
337+
referenced_pull_requests = {}
338+
for ref_owner, ref_repo, ref_number in pr_obj.parse_pr_references():
339+
ref_id = f"{ref_owner}/{ref_repo}#{ref_number}"
340+
referenced_pr_obj = gitea_api.PullRequest.get(self.gitea_conn, ref_owner, ref_repo, ref_number)
341+
referenced_pull_requests[ref_id] = referenced_pr_obj.dict()
342+
343+
with open(
344+
os.path.join(metadata_dir, "referenced-pull-requests.json"),
345+
"w",
346+
encoding="utf-8",
347+
) as f:
348+
json.dump(referenced_pull_requests, f, indent=4, sort_keys=True)
349+
350+
if skipped:
351+
print(f"{tty.colorize('WARNING', 'yellow,bold')}: Skipped pull requests that were no longer open: {' '.join(skipped)}", file=sys.stderr)
352+
return 11
353+
354+
return 0

osc/commands_git/pr_list.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,9 @@ def run(self, args):
6969
review_states = args.review_states or ["REQUEST_REVIEW"]
7070
new_pr_obj_list = []
7171
for pr_obj in pr_obj_list:
72-
all_reviews = gitea_api.PullRequest.get_reviews(self.gitea_conn, owner, repo, pr_obj.number).json()
73-
user_reviews = {i["user"]["login"]: i["state"] for i in all_reviews if i["user"] and i["state"] in review_states}
74-
team_reviews = {i["team"]["name"]: i["state"] for i in all_reviews if i["team"] and i["state"] in review_states}
72+
all_reviews = pr_obj.get_reviews(self.gitea_conn)
73+
user_reviews = {i.user: i.state for i in all_reviews if i.user and i.state in review_states}
74+
team_reviews = {i.team: i.state for i in all_reviews if i.team and i.state in review_states}
7575

7676
user_reviewers = [i for i in args.reviewers if not i.startswith("@")]
7777
team_reviewers = [i[1:] for i in args.reviewers if i.startswith("@")]

0 commit comments

Comments
 (0)