Debian Codegraph @

hacking/backport/backport_of_line_adder.py

raw
1 #!/usr/bin/env python
2 # (c) 2020, Red Hat, Inc. <[email protected]>
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18
19 from __future__ import annotations
20
21 from github.PullRequest import PullRequest
22 from github import Github
23 import os
24 import re
25 import sys
26
27 PULL_URL_RE = re.compile(r'(?P<user>\S+)/(?P<repo>\S+)#(?P<ticket>\d+)')
28 PULL_HTTP_URL_RE = re.compile(r'https?://(?:www\.|)github.com/(?P<user>\S+)/(?P<repo>\S+)/pull/(?P<ticket>\d+)')
29 PULL_BACKPORT_IN_TITLE = re.compile(r'.*\(#?(?P<ticket1>\d+)\)|\(backport of #?(?P<ticket2>\d+)\).*', re.I)
30 PULL_CHERRY_PICKED_FROM = re.compile(r'\(?cherry(?:\-| )picked from(?: ?commit|) (?P<hash>\w+)(?:\)|\.|$)')
31 TICKET_NUMBER = re.compile(r'(?:^|\s)#(\d+)')
32
33
34 def normalize_pr_url(pr, allow_non_ansible_ansible=False, only_number=False):
35 """
36 Given a PullRequest, or a string containing a PR number, PR URL,
37 or internal PR URL (e.g. ansible-collections/community.general#1234),
38 return either a full github URL to the PR (if only_number is False),
39 or an int containing the PR number (if only_number is True).
40
41 Throws if it can't parse the input.
42 """
43 if isinstance(pr, PullRequest):
44 return pr.html_url
45
46 if pr.isnumeric():
47 if only_number:
48 return int(pr)
49 return 'https://github.com/ansible/ansible/pull/{0}'.format(pr)
50
51 # Allow for forcing ansible/ansible
52 if not allow_non_ansible_ansible and 'ansible/ansible' not in pr:
53 raise Exception('Non ansible/ansible repo given where not expected')
54
55 re_match = PULL_HTTP_URL_RE.match(pr)
56 if re_match:
57 if only_number:
58 return int(re_match.group('ticket'))
59 return pr
60
61 re_match = PULL_URL_RE.match(pr)
62 if re_match:
63 if only_number:
64 return int(re_match.group('ticket'))
65 return 'https://github.com/{0}/{1}/pull/{2}'.format(
66 re_match.group('user'),
67 re_match.group('repo'),
68 re_match.group('ticket'))
69
70 raise Exception('Did not understand given PR')
71
72
73 def url_to_org_repo(url):
74 """
75 Given a full Github PR URL, extract the user/org and repo name.
76 Return them in the form: "user/repo"
77 """
78 match = PULL_HTTP_URL_RE.match(url)
79 if not match:
80 return ''
81 return '{0}/{1}'.format(match.group('user'), match.group('repo'))
82
83
84 def generate_new_body(pr, source_pr):
85 """
86 Given the new PR (the backport) and the originating (source) PR,
87 construct the new body for the backport PR.
88
89 If the backport follows the usual ansible/ansible template, we look for the
90 '##### SUMMARY'-type line and add our "Backport of" line right below that.
91
92 If we can't find the SUMMARY line, we add our line at the very bottom.
93
94 This function does not side-effect, it simply returns the new body as a
95 string.
96 """
97 backport_text = '\nBackport of {0}\n'.format(source_pr)
98 body_lines = pr.body.split('\n')
99 new_body_lines = []
100
101 added = False
102 for line in body_lines:
103 if 'Backport of http' in line:
104 raise Exception('Already has a backport line, aborting.')
105 new_body_lines.append(line)
106 if line.startswith('#') and line.strip().endswith('SUMMARY'):
107 # This would be a fine place to add it
108 new_body_lines.append(backport_text)
109 added = True
110 if not added:
111 # Otherwise, no '#### SUMMARY' line, so just add it at the bottom
112 new_body_lines.append(backport_text)
113
114 return '\n'.join(new_body_lines)
115
116
117 def get_prs_for_commit(g, commit):
118 """
119 Given a commit hash, attempt to find the hash in any repo in the
120 ansible orgs, and then use it to determine what, if any, PR it appeared in.
121 """
122
123 commits = g.search_commits(
124 'hash:{0} org:ansible org:ansible-collections is:public'.format(commit)
125 ).get_page(0)
126 if not commits or len(commits) == 0:
127 return []
128 pulls = commits[0].get_pulls().get_page(0)
129 if not pulls or len(pulls) == 0:
130 return []
131 return pulls
132
133
134 def search_backport(pr, g, ansible_ansible):
135 """
136 Do magic. This is basically the "brain" of 'auto'.
137 It will search the PR (the newest PR - the backport) and try to find where
138 it originated.
139
140 First it will search in the title. Some titles include things like
141 "foo bar change (#12345)" or "foo bar change (backport of #54321)"
142 so we search for those and pull them out.
143
144 Next it will scan the body of the PR and look for:
145 - cherry-pick reference lines (e.g. "cherry-picked from commit XXXXX")
146 - other PRs (#nnnnnn) and (foo/bar#nnnnnnn)
147 - full URLs to other PRs
148
149 It will take all of the above, and return a list of "possibilities",
150 which is a list of PullRequest objects.
151 """
152
153 possibilities = []
154
155 # 1. Try searching for it in the title.
156 title_search = PULL_BACKPORT_IN_TITLE.match(pr.title)
157 if title_search:
158 ticket = title_search.group('ticket1')
159 if not ticket:
160 ticket = title_search.group('ticket2')
161 try:
162 possibilities.append(ansible_ansible.get_pull(int(ticket)))
163 except Exception:
164 pass
165
166 # 2. Search for clues in the body of the PR
167 body_lines = pr.body.split('\n')
168 for line in body_lines:
169 # a. Try searching for a `git cherry-pick` line
170 cherrypick = PULL_CHERRY_PICKED_FROM.match(line)
171 if cherrypick:
172 prs = get_prs_for_commit(g, cherrypick.group('hash'))
173 possibilities.extend(prs)
174 continue
175
176 # b. Try searching for other referenced PRs (by #nnnnn or full URL)
177 tickets = [('ansible', 'ansible', ticket) for ticket in TICKET_NUMBER.findall(line)]
178 tickets.extend(PULL_HTTP_URL_RE.findall(line))
179 tickets.extend(PULL_URL_RE.findall(line))
180 if tickets:
181 for ticket in tickets:
182 # Is it a PR (even if not in ansible/ansible)?
183 # TODO: As a small optimization/to avoid extra calls to GitHub,
184 # we could limit this check to non-URL matches. If it's a URL,
185 # we know it's definitely a pull request.
186 try:
187 repo_path = '{0}/{1}'.format(ticket[0], ticket[1])
188 repo = ansible_ansible
189 if repo_path != 'ansible/ansible':
190 repo = g.get_repo(repo_path)
191 ticket_pr = repo.get_pull(int(ticket))
192 possibilities.append(ticket_pr)
193 except Exception:
194 pass
195 continue # Future-proofing
196
197 return possibilities
198
199
200 def prompt_add():
201 """
202 Prompt the user and return whether or not they agree.
203 """
204 res = input('Shall I add the reference? [Y/n]: ')
205 return res.lower() in ('', 'y', 'yes')
206
207
208 def commit_edit(new_pr, pr):
209 """
210 Given the new PR (the backport), and the "possibility" that we have decided
211 on, prompt the user and then add the reference to the body of the new PR.
212
213 This method does the actual "destructive" work of editing the PR body.
214 """
215 print('I think this PR might have come from:')
216 print(pr.title)
217 print('-' * 50)
218 print(pr.html_url)
219 if prompt_add():
220 new_body = generate_new_body(new_pr, pr.html_url)
221 new_pr.edit(body=new_body)
222 print('I probably added the reference successfully.')
223
224
225 if __name__ == '__main__':
226 if (
227 len(sys.argv) != 3 or
228 not sys.argv[1].isnumeric()
229 ):
230 print('Usage: <new backport PR> <already merged PR, or "auto">')
231 sys.exit(1)
232
233 token = os.environ.get('GITHUB_TOKEN')
234 if not token:
235 print('Go to https://github.com/settings/tokens/new and generate a '
236 'token with "repo" access, then set GITHUB_TOKEN to that token.')
237 sys.exit(1)
238
239 # https://github.com/settings/tokens/new
240 g = Github(token)
241 ansible_ansible = g.get_repo('ansible/ansible')
242
243 try:
244 pr_num = normalize_pr_url(sys.argv[1], only_number=True)
245 new_pr = ansible_ansible.get_pull(pr_num)
246 except Exception:
247 print('Could not load PR {0}'.format(sys.argv[1]))
248 sys.exit(1)
249
250 if sys.argv[2] == 'auto':
251 print('Trying to find originating PR...')
252 possibilities = search_backport(new_pr, g, ansible_ansible)
253 if not possibilities:
254 print('No match found, manual review required.')
255 sys.exit(1)
256 # TODO: Logic above can return multiple possibilities/guesses, but we
257 # only handle one here. We can cycle/prompt through them or something.
258 # For now, use the first match, which is also the most likely
259 # candidate.
260 pr = possibilities[0]
261 commit_edit(new_pr, pr)
262 else:
263 try:
264 # TODO: Fix having to call this twice to save some regex evals
265 pr_num = normalize_pr_url(sys.argv[2], only_number=True, allow_non_ansible_ansible=True)
266 pr_url = normalize_pr_url(sys.argv[2], allow_non_ansible_ansible=True)
267 pr_repo = g.get_repo(url_to_org_repo(pr_url))
268 pr = pr_repo.get_pull(pr_num)
269 except Exception as e:
270 print(e)
271 print('Could not load PR {0}'.format(sys.argv[2]))
272 sys.exit(1)
273 commit_edit(new_pr, pr)