blob: 7c6bea1ba361892a1e95dd022b3d9e3ed10947bf [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')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800122 parser.add_argument('--changeid', '-c',
123 help='Overrides the gerrit generated Change-Id line')
124
125 parser.add_argument('--replace',
126 action='store_true',
127 help='Replaces the HEAD commit with this one, taking ' +
128 'its properties(BUG, TEST, Change-Id). Useful for ' +
129 'updating commits.')
130 parser.add_argument('--nosignoff',
131 dest='signoff', action='store_false')
132
133 parser.add_argument('--tag',
134 help='Overrides the tag from the title')
135 parser.add_argument('--source', '-s',
136 dest='source_line', type=str,
137 help='Overrides the source line, last line, ex: ' +
138 '(am from http://....)')
139 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700140 nargs='+',
Brian Norris9f8a2be2018-06-01 11:14:08 -0700141 help='Patchwork ID (pw://### or pw://PROJECT/###, ' +
142 'where PROJECT is defined in ~/.pwclientrc; if no ' +
143 'PROJECT is specified, the default is retrieved from ' +
144 '~/.pwclientrc), ' +
145 'linux commit like linux://HASH, or ' +
Brian Norrisc9aeb2e2018-06-01 10:37:29 -0700146 'git reference like fromgit://remote/branch/HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800147
148 args = vars(parser.parse_args(args))
149
150 if args['replace']:
151 old_commit_message = subprocess.check_output(
152 ['git', 'show', '-s', '--format=%B', 'HEAD']
153 ).strip('\n')
Guenter Roeckf7cebec2018-07-26 16:37:21 -0700154 changeid = re.findall('Change-Id: (.*)$', old_commit_message, re.MULTILINE)
155 if changeid:
156 args['changeid'] = changeid[0]
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700157 if args['bug'] == parser.get_default('bug') and \
158 re.findall('BUG=(.*)$', old_commit_message, re.MULTILINE):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800159 args['bug'] = '\nBUG='.join(re.findall('BUG=(.*)$',
160 old_commit_message,
161 re.MULTILINE))
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700162 if args['test'] == parser.get_default('test') and \
163 re.findall('TEST=(.*)$', old_commit_message, re.MULTILINE):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800164 args['test'] = '\nTEST='.join(re.findall('TEST=(.*)$',
165 old_commit_message,
166 re.MULTILINE))
167 # TODO: deal with multiline BUG/TEST better
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800168
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700169 if args['bug'] is None or args['test'] is None:
Stephen Boyde6fdf912018-11-09 10:30:57 -0800170 parser.error('BUG=/TEST= lines are required; --replace can help ' +
171 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700172
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800173 while len(args['locations']) > 0:
174 location = args['locations'].pop(0)
175
176 patchwork_match = re.match(
Brian Norris9f8a2be2018-06-01 11:14:08 -0700177 r'pw://(([-A-z]+)/)?(\d+)', location
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800178 )
179 linux_match = re.match(
180 r'linux://([0-9a-f]+)', location
181 )
182 fromgit_match = re.match(
183 r'fromgit://([^/]+)/(.+)/([0-9a-f]+)$', location
184 )
185
186 if patchwork_match is not None:
Brian Norris9f8a2be2018-06-01 11:14:08 -0700187 pw_project = patchwork_match.group(2)
188 patch_id = int(patchwork_match.group(3))
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800189
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800190 if args['tag'] is None:
191 args['tag'] = 'FROMLIST: '
192
Brian Norris2d4e9762018-08-15 13:11:47 -0700193 url = _get_pw_url(pw_project)
194 opener = urllib.urlopen("%s/patch/%d/mbox" % (url, patch_id))
195 if opener.getcode() != 200:
196 sys.stderr.write('Error: could not download patch - error code %d\n' \
197 % opener.getcode())
198 sys.exit(1)
199 patch_contents = opener.read()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700200
Brian Norris2d4e9762018-08-15 13:11:47 -0700201 if not patch_contents:
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800202 sys.stderr.write('Error: No patch content found\n')
203 sys.exit(1)
Guenter Roeckabe49d82018-07-25 14:11:48 -0700204
Brian Norris2d4e9762018-08-15 13:11:47 -0700205 if args['source_line'] is None:
206 args['source_line'] = '(am from %s/patch/%d/)' % (url, patch_id)
Brian Norrisc3421042018-08-15 14:17:26 -0700207 message_id = mailbox.Message(patch_contents)['Message-Id']
208 message_id = re.sub('^<|>$', '', message_id.strip())
209 args['source_line'] += \
210 '\n(also found at https://lkml.kernel.org/r/%s)' % \
211 message_id
Brian Norris2d4e9762018-08-15 13:11:47 -0700212
Guenter Roeckabe49d82018-07-25 14:11:48 -0700213 if args['replace']:
214 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
215
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800216 git_am = subprocess.Popen(['git', 'am', '-3'], stdin=subprocess.PIPE)
Brian Norris2d4e9762018-08-15 13:11:47 -0700217 git_am.communicate(patch_contents)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800218 ret = git_am.returncode
219 elif linux_match:
220 commit = linux_match.group(1)
221
222 # Confirm a 'linux' remote is setup.
Guenter Roeckd66daa72018-04-19 10:31:25 -0700223 linux_remote = _find_linux_remote()
224 if not linux_remote:
225 sys.stderr.write('Error: need a valid upstream remote\n')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800226 sys.exit(1)
227
Guenter Roeckd66daa72018-04-19 10:31:25 -0700228 linux_master = '%s/master' % linux_remote
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800229 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
Guenter Roeckd66daa72018-04-19 10:31:25 -0700230 commit, linux_master])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800231 if ret:
Guenter Roeckd66daa72018-04-19 10:31:25 -0700232 sys.stderr.write('Error: Commit not in %s\n' % linux_master)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800233 sys.exit(1)
234
235 if args['source_line'] is None:
236 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
237 stdout=subprocess.PIPE)
238 commit = git_pipe.communicate()[0].strip()
239
240 args['source_line'] = ('(cherry picked from commit %s)' %
241 (commit))
242 if args['tag'] is None:
243 args['tag'] = 'UPSTREAM: '
244
Guenter Roeckabe49d82018-07-25 14:11:48 -0700245 if args['replace']:
246 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
247
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800248 ret = subprocess.call(['git', 'cherry-pick', commit])
249 elif fromgit_match is not None:
250 remote = fromgit_match.group(1)
251 branch = fromgit_match.group(2)
252 commit = fromgit_match.group(3)
253
254 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
255 commit, '%s/%s' % (remote, branch)])
256 if ret:
257 sys.stderr.write('Error: Commit not in %s/%s\n' %
258 (remote, branch))
259 sys.exit(1)
260
261 git_pipe = subprocess.Popen(['git', 'remote', 'get-url', remote],
262 stdout=subprocess.PIPE)
263 url = git_pipe.communicate()[0].strip()
264
265 if args['source_line'] is None:
266 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
267 stdout=subprocess.PIPE)
268 commit = git_pipe.communicate()[0].strip()
269
270 args['source_line'] = \
271 '(cherry picked from commit %s\n %s %s)' % \
272 (commit, url, branch)
273 if args['tag'] is None:
274 args['tag'] = 'FROMGIT: '
275
Guenter Roeckabe49d82018-07-25 14:11:48 -0700276 if args['replace']:
277 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
278
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800279 ret = subprocess.call(['git', 'cherry-pick', commit])
280 else:
281 sys.stderr.write('Don\'t know what "%s" means.\n' % location)
282 sys.exit(1)
283
284 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700285 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700286 if args['tag'] == 'UPSTREAM: ':
287 args['tag'] = 'BACKPORT: '
288 else:
289 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700290 _pause_for_merge(conflicts)
291 else:
292 conflicts = ""
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800293
294 # extract commit message
295 commit_message = subprocess.check_output(
296 ['git', 'show', '-s', '--format=%B', 'HEAD']
297 ).strip('\n')
298
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700299 # Remove stray Change-Id, most likely from merge resolution
300 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
301
Brian Norris7a41b982018-06-01 10:28:29 -0700302 # Note the source location before tagging anything else
303 commit_message += '\n' + args['source_line']
304
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800305 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
306 # next commands know where to work on
307 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700308 commit_message += conflicts
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800309 commit_message += '\n' + 'BUG=' + args['bug']
310 commit_message += '\n' + 'TEST=' + args['test']
311 if args['signoff']:
312 extra = ['-s']
313 else:
314 extra = []
Stephen Boydaa4e7e02018-11-09 08:48:46 -0800315 subprocess.Popen(
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800316 ['git', 'commit'] + extra + ['--amend', '-F', '-'],
317 stdin=subprocess.PIPE
318 ).communicate(commit_message)
319
320 # re-extract commit message
321 commit_message = subprocess.check_output(
322 ['git', 'show', '-s', '--format=%B', 'HEAD']
323 ).strip('\n')
324
325 # replace changeid if needed
326 if args['changeid'] is not None:
327 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
328 args['changeid'], commit_message)
329 args['changeid'] = None
330
331 # decorate it that it's from outside
332 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800333
334 # commit everything
Stephen Boydaa4e7e02018-11-09 08:48:46 -0800335 subprocess.Popen(
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800336 ['git', 'commit', '--amend', '-F', '-'], stdin=subprocess.PIPE
337 ).communicate(commit_message)
338
339 return 0
340
341if __name__ == '__main__':
342 sys.exit(main(sys.argv[1:]))