##// END OF EJS Templates
allow backporting several PRs at once
MinRK -
Show More
@@ -1,166 +1,171 b''
1 1 #!/usr/bin/env python
2 2 """
3 3 Backport pull requests to a particular branch.
4 4
5 Usage: backport_pr.py branch [PR]
5 Usage: backport_pr.py branch [PR] [PR2]
6 6
7 7 e.g.:
8 8
9 python tools/backport_pr.py 0.13.1 123
9 python tools/backport_pr.py 0.13.1 123 155
10 10
11 11 to backport PR #123 onto branch 0.13.1
12 12
13 13 or
14 14
15 15 python tools/backport_pr.py 2.1
16 16
17 17 to see what PRs are marked for backport with milestone=2.1 that have yet to be applied
18 18 to branch 2.x.
19 19
20 20 """
21 21
22 22 from __future__ import print_function
23 23
24 24 import os
25 25 import re
26 26 import sys
27 27
28 28 from subprocess import Popen, PIPE, check_call, check_output
29 29 try:
30 30 from urllib.request import urlopen
31 31 except:
32 from urllib import urlopen
32 from urllib import urlopen
33 33
34 34 from gh_api import (
35 35 get_issues_list,
36 36 get_pull_request,
37 37 get_pull_request_files,
38 38 is_pull_request,
39 39 get_milestone_id,
40 40 )
41 41
42 42 def find_rejects(root='.'):
43 43 for dirname, dirs, files in os.walk(root):
44 44 for fname in files:
45 45 if fname.endswith('.rej'):
46 46 yield os.path.join(dirname, fname)
47 47
48 48 def get_current_branch():
49 49 branches = check_output(['git', 'branch'])
50 50 for branch in branches.splitlines():
51 51 if branch.startswith(b'*'):
52 52 return branch[1:].strip().decode('utf-8')
53 53
54 54 def backport_pr(branch, num, project='ipython/ipython'):
55 55 current_branch = get_current_branch()
56 56 if branch != current_branch:
57 57 check_call(['git', 'checkout', branch])
58 58 check_call(['git', 'pull'])
59 59 pr = get_pull_request(project, num, auth=True)
60 60 files = get_pull_request_files(project, num, auth=True)
61 61 patch_url = pr['patch_url']
62 62 title = pr['title']
63 63 description = pr['body']
64 64 fname = "PR%i.patch" % num
65 65 if os.path.exists(fname):
66 66 print("using patch from {fname}".format(**locals()))
67 67 with open(fname) as f:
68 68 patch = f.read()
69 69 else:
70 70 req = urlopen(patch_url)
71 71 patch = req.read()
72 72
73 73 msg = "Backport PR #%i: %s" % (num, title) + '\n\n' + description
74 74 check = Popen(['git', 'apply', '--check', '--verbose'], stdin=PIPE)
75 75 a,b = check.communicate(patch)
76 76
77 77 if check.returncode:
78 78 print("patch did not apply, saving to {fname}".format(**locals()))
79 79 print("edit {fname} until `cat {fname} | git apply --check` succeeds".format(**locals()))
80 80 print("then run tools/backport_pr.py {num} again".format(**locals()))
81 81 if not os.path.exists(fname):
82 82 with open(fname, 'wb') as f:
83 83 f.write(patch)
84 84 return 1
85 85
86 86 p = Popen(['git', 'apply'], stdin=PIPE)
87 87 a,b = p.communicate(patch)
88 88
89 89 filenames = [ f['filename'] for f in files ]
90 90
91 91 check_call(['git', 'add'] + filenames)
92 92
93 93 check_call(['git', 'commit', '-m', msg])
94 94
95 95 print("PR #%i applied, with msg:" % num)
96 96 print()
97 97 print(msg)
98 98 print()
99 99
100 100 if branch != current_branch:
101 101 check_call(['git', 'checkout', current_branch])
102 102
103 103 return 0
104 104
105 105 backport_re = re.compile(r"[Bb]ackport.*?(\d+)")
106 106
107 107 def already_backported(branch, since_tag=None):
108 108 """return set of PRs that have been backported already"""
109 109 if since_tag is None:
110 110 since_tag = check_output(['git','describe', branch, '--abbrev=0']).decode('utf8').strip()
111 111 cmd = ['git', 'log', '%s..%s' % (since_tag, branch), '--oneline']
112 112 lines = check_output(cmd).decode('utf8')
113 113 return set(int(num) for num in backport_re.findall(lines))
114 114
115 115 def should_backport(labels=None, milestone=None):
116 116 """return set of PRs marked for backport"""
117 117 if labels is None and milestone is None:
118 118 raise ValueError("Specify one of labels or milestone.")
119 119 elif labels is not None and milestone is not None:
120 120 raise ValueError("Specify only one of labels or milestone.")
121 121 if labels is not None:
122 122 issues = get_issues_list("ipython/ipython",
123 123 labels=labels,
124 124 state='closed',
125 125 auth=True,
126 126 )
127 127 else:
128 128 milestone_id = get_milestone_id("ipython/ipython", milestone,
129 129 auth=True)
130 130 issues = get_issues_list("ipython/ipython",
131 131 milestone=milestone_id,
132 132 state='closed',
133 133 auth=True,
134 134 )
135 135
136 136 should_backport = set()
137 137 for issue in issues:
138 138 if not is_pull_request(issue):
139 139 continue
140 140 pr = get_pull_request("ipython/ipython", issue['number'],
141 141 auth=True)
142 142 if not pr['merged']:
143 143 print ("Marked PR closed without merge: %i" % pr['number'])
144 144 continue
145 145 if pr['base']['ref'] != 'master':
146 146 continue
147 147 should_backport.add(pr['number'])
148 148 return should_backport
149 149
150 150 if __name__ == '__main__':
151 151
152 152 if len(sys.argv) < 2:
153 153 print(__doc__)
154 154 sys.exit(1)
155 155
156 156 if len(sys.argv) < 3:
157 157 milestone = sys.argv[1]
158 158 branch = milestone.split('.')[0] + '.x'
159 159 already = already_backported(branch)
160 160 should = should_backport(milestone=milestone)
161 161 print ("The following PRs should be backported:")
162 162 for pr in sorted(should.difference(already)):
163 163 print (pr)
164 164 sys.exit(0)
165 165
166 sys.exit(backport_pr(sys.argv[1], int(sys.argv[2])))
166 for prno in map(int, sys.argv[2:]):
167 print("Backporting PR #%i" % prno)
168 rc = backport_pr(sys.argv[1], prno)
169 if rc:
170 print("Backporting PR #%i failed" % prno)
171 sys.exit(rc)
General Comments 0
You need to be logged in to leave comments. Login now