blob: 3590a429be9eec2c05beb424207e9b5c465dcf81 [file] [log] [blame]
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -08001#!/usr/bin/env python2
Mike Frysingerf80ca212018-07-13 15:02:52 -04002# -*- coding: utf-8 -*-
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -08003# Copyright 2017 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
Mike Frysingerf80ca212018-07-13 15:02:52 -04006
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -08007"""This is a tool for picking patches from upstream and applying them."""
8
9from __future__ import print_function
10
Brian Norris9f8a2be2018-06-01 11:14:08 -070011import ConfigParser
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080012import argparse
Brian Norrisc3421042018-08-15 14:17:26 -070013import mailbox
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080014import os
15import re
16import signal
17import subprocess
18import sys
Brian Norris2d4e9762018-08-15 13:11:47 -070019import urllib
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080020
21LINUX_URLS = (
22 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
23 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
24 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
25)
26
Brian Norris9f8a2be2018-06-01 11:14:08 -070027_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
28
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070029def _get_conflicts():
30 """Report conflicting files."""
31 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
32 conflicts = []
Douglas Anderson46287f92018-04-30 09:58:24 -070033 lines = subprocess.check_output(['git', 'status', '--porcelain',
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070034 '--untracked-files=no']).split('\n')
Douglas Anderson46287f92018-04-30 09:58:24 -070035 for line in lines:
36 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070037 continue
Douglas Anderson46287f92018-04-30 09:58:24 -070038 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070039 if resolution in resolutions:
40 conflicts.append(' ' + name)
41 if not conflicts:
42 return ""
43 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
44
Guenter Roeckd66daa72018-04-19 10:31:25 -070045def _find_linux_remote():
46 """Find a remote pointing to a Linux upstream repository."""
47 git_remote = subprocess.Popen(['git', 'remote'], stdout=subprocess.PIPE)
48 remotes = git_remote.communicate()[0].strip()
49 for remote in remotes.splitlines():
50 rurl = subprocess.Popen(['git', 'remote', 'get-url', remote],
51 stdout=subprocess.PIPE)
52 url = rurl.communicate()[0].strip()
53 if not rurl.returncode and url in LINUX_URLS:
54 return remote
55 return None
56
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070057def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080058 """Pause and go in the background till user resolves the conflicts."""
59
60 git_root = subprocess.check_output(['git', 'rev-parse',
61 '--show-toplevel']).strip('\n')
62
63 paths = (
64 os.path.join(git_root, '.git', 'rebase-apply'),
65 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
66 )
67 for path in paths:
68 if os.path.exists(path):
69 sys.stderr.write('Found "%s".\n' % path)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070070 sys.stderr.write(conflicts)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080071 sys.stderr.write('Please resolve the conflicts and restart the ' +
72 'shell job when done. Kill this job if you ' +
73 'aborted the conflict.\n')
74 os.kill(os.getpid(), signal.SIGTSTP)
75 # TODO: figure out what the state is after the merging, and go based on
76 # that (should we abort? skip? continue?)
77 # Perhaps check last commit message to see if it's the one we were using.
78
Brian Norris9f8a2be2018-06-01 11:14:08 -070079def _get_pw_url(project):
80 """Retrieve the patchwork server URL from .pwclientrc.
81
Mike Frysingerf80ca212018-07-13 15:02:52 -040082 Args:
83 project: patchwork project name; if None, we retrieve the default
84 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -070085 """
86 config = ConfigParser.ConfigParser()
87 config.read([_PWCLIENTRC])
88
89 if project is None:
90 try:
91 project = config.get('options', 'default')
92 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
93 sys.stderr.write(
94 'Error: no default patchwork project found in %s.\n'
95 % _PWCLIENTRC)
96 sys.exit(1)
97
98 if not config.has_option(project, 'url'):
99 sys.stderr.write('Error: patchwork URL not found for project \'%s\'\n'
100 % project)
101 sys.exit(1)
102
103 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700104 # Strip trailing 'xmlrpc' and/or trailing slash.
105 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700106
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800107def main(args):
108 """This is the main entrypoint for fromupstream.
109
110 Args:
111 args: sys.argv[1:]
112
113 Returns:
114 An int return code.
115 """
116 parser = argparse.ArgumentParser()
117
118 parser.add_argument('--bug', '-b',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700119 type=str, help='BUG= line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800120 parser.add_argument('--test', '-t',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700121 type=str, help='TEST= line')
Stephen Boyd24b309b2018-11-06 22:11:00 -0800122 parser.add_argument('--crbug', action='append',
123 type=int, help='BUG=chromium: line')
124 parser.add_argument('--buganizer', action='append',
125 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800126 parser.add_argument('--changeid', '-c',
127 help='Overrides the gerrit generated Change-Id line')
128
129 parser.add_argument('--replace',
130 action='store_true',
131 help='Replaces the HEAD commit with this one, taking ' +
132 'its properties(BUG, TEST, Change-Id). Useful for ' +
133 'updating commits.')
134 parser.add_argument('--nosignoff',
135 dest='signoff', action='store_false')
136
137 parser.add_argument('--tag',
138 help='Overrides the tag from the title')
139 parser.add_argument('--source', '-s',
140 dest='source_line', type=str,
141 help='Overrides the source line, last line, ex: ' +
142 '(am from http://....)')
143 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700144 nargs='+',
Brian Norris9f8a2be2018-06-01 11:14:08 -0700145 help='Patchwork ID (pw://### or pw://PROJECT/###, ' +
146 'where PROJECT is defined in ~/.pwclientrc; if no ' +
147 'PROJECT is specified, the default is retrieved from ' +
148 '~/.pwclientrc), ' +
149 'linux commit like linux://HASH, or ' +
Stephen Boyd66ea1912018-10-30 11:26:54 -0700150 'git reference like git://remote/branch/HASH or ' +
151 'git://repoURL#branch/HASH or ' +
152 'https://repoURL#branch/HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800153
154 args = vars(parser.parse_args(args))
155
Stephen Boyd24b309b2018-11-06 22:11:00 -0800156 buglist = [args['bug']] if args['bug'] else []
157 if args['buganizer']:
158 buglist += ['b:{0}'.format(x) for x in args['buganizer']]
159 if args['crbug']:
160 buglist += ['chromium:{0}'.format(x) for x in args['crbug']]
161 args['bug'] = ', '.join(buglist)
162
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800163 if args['replace']:
164 old_commit_message = subprocess.check_output(
165 ['git', 'show', '-s', '--format=%B', 'HEAD']
166 ).strip('\n')
Guenter Roeckf7cebec2018-07-26 16:37:21 -0700167 changeid = re.findall('Change-Id: (.*)$', old_commit_message, re.MULTILINE)
168 if changeid:
169 args['changeid'] = changeid[0]
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700170 if args['bug'] == parser.get_default('bug') and \
171 re.findall('BUG=(.*)$', old_commit_message, re.MULTILINE):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800172 args['bug'] = '\nBUG='.join(re.findall('BUG=(.*)$',
173 old_commit_message,
174 re.MULTILINE))
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700175 if args['test'] == parser.get_default('test') and \
176 re.findall('TEST=(.*)$', old_commit_message, re.MULTILINE):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800177 args['test'] = '\nTEST='.join(re.findall('TEST=(.*)$',
178 old_commit_message,
179 re.MULTILINE))
180 # TODO: deal with multiline BUG/TEST better
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800181
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700182 if args['bug'] is None or args['test'] is None:
Stephen Boyde6fdf912018-11-09 10:30:57 -0800183 parser.error('BUG=/TEST= lines are required; --replace can help ' +
184 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700185
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800186 while len(args['locations']) > 0:
187 location = args['locations'].pop(0)
188
189 patchwork_match = re.match(
Brian Norris9f8a2be2018-06-01 11:14:08 -0700190 r'pw://(([-A-z]+)/)?(\d+)', location
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800191 )
192 linux_match = re.match(
193 r'linux://([0-9a-f]+)', location
194 )
195 fromgit_match = re.match(
Stephen Boyd66ea1912018-10-30 11:26:54 -0700196 r'(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$', location
197 )
198 gitfetch_match = re.match(
199 r'((git|https)://.+)#(.+)/([0-9a-f]+)$', location
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800200 )
201
202 if patchwork_match is not None:
Brian Norris9f8a2be2018-06-01 11:14:08 -0700203 pw_project = patchwork_match.group(2)
204 patch_id = int(patchwork_match.group(3))
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800205
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800206 if args['tag'] is None:
207 args['tag'] = 'FROMLIST: '
208
Brian Norris2d4e9762018-08-15 13:11:47 -0700209 url = _get_pw_url(pw_project)
210 opener = urllib.urlopen("%s/patch/%d/mbox" % (url, patch_id))
211 if opener.getcode() != 200:
212 sys.stderr.write('Error: could not download patch - error code %d\n' \
213 % opener.getcode())
214 sys.exit(1)
215 patch_contents = opener.read()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700216
Brian Norris2d4e9762018-08-15 13:11:47 -0700217 if not patch_contents:
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800218 sys.stderr.write('Error: No patch content found\n')
219 sys.exit(1)
Guenter Roeckabe49d82018-07-25 14:11:48 -0700220
Brian Norris2d4e9762018-08-15 13:11:47 -0700221 if args['source_line'] is None:
222 args['source_line'] = '(am from %s/patch/%d/)' % (url, patch_id)
Brian Norrisc3421042018-08-15 14:17:26 -0700223 message_id = mailbox.Message(patch_contents)['Message-Id']
224 message_id = re.sub('^<|>$', '', message_id.strip())
225 args['source_line'] += \
226 '\n(also found at https://lkml.kernel.org/r/%s)' % \
227 message_id
Brian Norris2d4e9762018-08-15 13:11:47 -0700228
Guenter Roeckabe49d82018-07-25 14:11:48 -0700229 if args['replace']:
230 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
231
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800232 git_am = subprocess.Popen(['git', 'am', '-3'], stdin=subprocess.PIPE)
Brian Norris2d4e9762018-08-15 13:11:47 -0700233 git_am.communicate(patch_contents)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800234 ret = git_am.returncode
235 elif linux_match:
236 commit = linux_match.group(1)
237
238 # Confirm a 'linux' remote is setup.
Guenter Roeckd66daa72018-04-19 10:31:25 -0700239 linux_remote = _find_linux_remote()
240 if not linux_remote:
241 sys.stderr.write('Error: need a valid upstream remote\n')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800242 sys.exit(1)
243
Guenter Roeckd66daa72018-04-19 10:31:25 -0700244 linux_master = '%s/master' % linux_remote
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800245 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
Guenter Roeckd66daa72018-04-19 10:31:25 -0700246 commit, linux_master])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800247 if ret:
Guenter Roeckd66daa72018-04-19 10:31:25 -0700248 sys.stderr.write('Error: Commit not in %s\n' % linux_master)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800249 sys.exit(1)
250
251 if args['source_line'] is None:
252 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
253 stdout=subprocess.PIPE)
254 commit = git_pipe.communicate()[0].strip()
255
256 args['source_line'] = ('(cherry picked from commit %s)' %
257 (commit))
258 if args['tag'] is None:
259 args['tag'] = 'UPSTREAM: '
260
Guenter Roeckabe49d82018-07-25 14:11:48 -0700261 if args['replace']:
262 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
263
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800264 ret = subprocess.call(['git', 'cherry-pick', commit])
265 elif fromgit_match is not None:
Stephen Boyd66ea1912018-10-30 11:26:54 -0700266 remote = fromgit_match.group(2)
267 branch = fromgit_match.group(3)
268 commit = fromgit_match.group(4)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800269
270 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
271 commit, '%s/%s' % (remote, branch)])
272 if ret:
273 sys.stderr.write('Error: Commit not in %s/%s\n' %
274 (remote, branch))
275 sys.exit(1)
276
277 git_pipe = subprocess.Popen(['git', 'remote', 'get-url', remote],
278 stdout=subprocess.PIPE)
279 url = git_pipe.communicate()[0].strip()
280
281 if args['source_line'] is None:
282 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
283 stdout=subprocess.PIPE)
284 commit = git_pipe.communicate()[0].strip()
285
286 args['source_line'] = \
287 '(cherry picked from commit %s\n %s %s)' % \
288 (commit, url, branch)
289 if args['tag'] is None:
290 args['tag'] = 'FROMGIT: '
291
Guenter Roeckabe49d82018-07-25 14:11:48 -0700292 if args['replace']:
293 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
294
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800295 ret = subprocess.call(['git', 'cherry-pick', commit])
Stephen Boyd66ea1912018-10-30 11:26:54 -0700296 elif gitfetch_match is not None:
297 remote = gitfetch_match.group(1)
298 branch = gitfetch_match.group(3)
299 commit = gitfetch_match.group(4)
300
301 ret = subprocess.call(['git', 'fetch', remote, branch])
302 if ret:
303 sys.stderr.write('Error: Branch not in %s\n' % remote)
304 sys.exit(1)
305
306 url = remote
307
308 if args['source_line'] is None:
309 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
310 stdout=subprocess.PIPE)
311 commit = git_pipe.communicate()[0].strip()
312
313 args['source_line'] = \
314 '(cherry picked from commit %s\n %s %s)' % \
315 (commit, url, branch)
316 if args['tag'] is None:
317 args['tag'] = 'FROMGIT: '
318
319 ret = subprocess.call(['git', 'cherry-pick', commit])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800320 else:
321 sys.stderr.write('Don\'t know what "%s" means.\n' % location)
322 sys.exit(1)
323
324 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700325 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700326 if args['tag'] == 'UPSTREAM: ':
327 args['tag'] = 'BACKPORT: '
328 else:
329 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700330 _pause_for_merge(conflicts)
331 else:
332 conflicts = ""
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800333
334 # extract commit message
335 commit_message = subprocess.check_output(
336 ['git', 'show', '-s', '--format=%B', 'HEAD']
337 ).strip('\n')
338
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700339 # Remove stray Change-Id, most likely from merge resolution
340 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
341
Brian Norris7a41b982018-06-01 10:28:29 -0700342 # Note the source location before tagging anything else
343 commit_message += '\n' + args['source_line']
344
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800345 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
346 # next commands know where to work on
347 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700348 commit_message += conflicts
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800349 commit_message += '\n' + 'BUG=' + args['bug']
350 commit_message += '\n' + 'TEST=' + args['test']
351 if args['signoff']:
352 extra = ['-s']
353 else:
354 extra = []
Stephen Boydaa4e7e02018-11-09 08:48:46 -0800355 subprocess.Popen(
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800356 ['git', 'commit'] + extra + ['--amend', '-F', '-'],
357 stdin=subprocess.PIPE
358 ).communicate(commit_message)
359
360 # re-extract commit message
361 commit_message = subprocess.check_output(
362 ['git', 'show', '-s', '--format=%B', 'HEAD']
363 ).strip('\n')
364
365 # replace changeid if needed
366 if args['changeid'] is not None:
367 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
368 args['changeid'], commit_message)
369 args['changeid'] = None
370
371 # decorate it that it's from outside
372 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800373
374 # commit everything
Stephen Boydaa4e7e02018-11-09 08:48:46 -0800375 subprocess.Popen(
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800376 ['git', 'commit', '--amend', '-F', '-'], stdin=subprocess.PIPE
377 ).communicate(commit_message)
378
379 return 0
380
381if __name__ == '__main__':
382 sys.exit(main(sys.argv[1:]))