blob: 9442db29c2ea167b281f0ced454f95a7a4616171 [file] [log] [blame]
Alexandru M Stanfb5b5ee2014-12-04 21:32:551#!/usr/bin/env python2
Mike Frysingerf80ca212018-07-13 19:02:522# -*- coding: utf-8 -*-
Alexandru M Stanfb5b5ee2014-12-04 21:32:553# 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 19:02:526
Alexandru M Stanfb5b5ee2014-12-04 21:32:557"""This is a tool for picking patches from upstream and applying them."""
8
9from __future__ import print_function
10
Brian Norris9f8a2be2018-06-01 18:14:0811import ConfigParser
Alexandru M Stanfb5b5ee2014-12-04 21:32:5512import argparse
13import os
14import re
15import signal
16import subprocess
17import sys
18
19LINUX_URLS = (
20 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
21 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
22 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
23)
24
Brian Norris9f8a2be2018-06-01 18:14:0825_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
26
Guenter Roeckbdbb9cc2018-04-19 17:05:0827def _get_conflicts():
28 """Report conflicting files."""
29 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
30 conflicts = []
Douglas Anderson46287f92018-04-30 16:58:2431 lines = subprocess.check_output(['git', 'status', '--porcelain',
Guenter Roeckbdbb9cc2018-04-19 17:05:0832 '--untracked-files=no']).split('\n')
Douglas Anderson46287f92018-04-30 16:58:2433 for line in lines:
34 if not line:
Guenter Roeckbdbb9cc2018-04-19 17:05:0835 continue
Douglas Anderson46287f92018-04-30 16:58:2436 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 17:05:0837 if resolution in resolutions:
38 conflicts.append(' ' + name)
39 if not conflicts:
40 return ""
41 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
42
Guenter Roeckd66daa72018-04-19 17:31:2543def _find_linux_remote():
44 """Find a remote pointing to a Linux upstream repository."""
45 git_remote = subprocess.Popen(['git', 'remote'], stdout=subprocess.PIPE)
46 remotes = git_remote.communicate()[0].strip()
47 for remote in remotes.splitlines():
48 rurl = subprocess.Popen(['git', 'remote', 'get-url', remote],
49 stdout=subprocess.PIPE)
50 url = rurl.communicate()[0].strip()
51 if not rurl.returncode and url in LINUX_URLS:
52 return remote
53 return None
54
Guenter Roeckbdbb9cc2018-04-19 17:05:0855def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 21:32:5556 """Pause and go in the background till user resolves the conflicts."""
57
58 git_root = subprocess.check_output(['git', 'rev-parse',
59 '--show-toplevel']).strip('\n')
60
61 paths = (
62 os.path.join(git_root, '.git', 'rebase-apply'),
63 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
64 )
65 for path in paths:
66 if os.path.exists(path):
67 sys.stderr.write('Found "%s".\n' % path)
Guenter Roeckbdbb9cc2018-04-19 17:05:0868 sys.stderr.write(conflicts)
Alexandru M Stanfb5b5ee2014-12-04 21:32:5569 sys.stderr.write('Please resolve the conflicts and restart the ' +
70 'shell job when done. Kill this job if you ' +
71 'aborted the conflict.\n')
72 os.kill(os.getpid(), signal.SIGTSTP)
73 # TODO: figure out what the state is after the merging, and go based on
74 # that (should we abort? skip? continue?)
75 # Perhaps check last commit message to see if it's the one we were using.
76
Brian Norris9f8a2be2018-06-01 18:14:0877def _get_pw_url(project):
78 """Retrieve the patchwork server URL from .pwclientrc.
79
Mike Frysingerf80ca212018-07-13 19:02:5280 Args:
81 project: patchwork project name; if None, we retrieve the default
82 from pwclientrc
Brian Norris9f8a2be2018-06-01 18:14:0883 """
84 config = ConfigParser.ConfigParser()
85 config.read([_PWCLIENTRC])
86
87 if project is None:
88 try:
89 project = config.get('options', 'default')
90 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
91 sys.stderr.write(
92 'Error: no default patchwork project found in %s.\n'
93 % _PWCLIENTRC)
94 sys.exit(1)
95
96 if not config.has_option(project, 'url'):
97 sys.stderr.write('Error: patchwork URL not found for project \'%s\'\n'
98 % project)
99 sys.exit(1)
100
101 url = config.get(project, 'url')
102 return re.sub('(/xmlrpc/)$', '', url)
103
Alexandru M Stanfb5b5ee2014-12-04 21:32:55104def main(args):
105 """This is the main entrypoint for fromupstream.
106
107 Args:
108 args: sys.argv[1:]
109
110 Returns:
111 An int return code.
112 """
113 parser = argparse.ArgumentParser()
114
115 parser.add_argument('--bug', '-b',
Douglas Andersonb8881842018-05-05 00:02:52116 type=str, required=True, help='BUG= line')
Alexandru M Stanfb5b5ee2014-12-04 21:32:55117 parser.add_argument('--test', '-t',
Douglas Andersonb8881842018-05-05 00:02:52118 type=str, required=True, help='TEST= line')
Alexandru M Stanfb5b5ee2014-12-04 21:32:55119 parser.add_argument('--changeid', '-c',
120 help='Overrides the gerrit generated Change-Id line')
121
122 parser.add_argument('--replace',
123 action='store_true',
124 help='Replaces the HEAD commit with this one, taking ' +
125 'its properties(BUG, TEST, Change-Id). Useful for ' +
126 'updating commits.')
127 parser.add_argument('--nosignoff',
128 dest='signoff', action='store_false')
129
130 parser.add_argument('--tag',
131 help='Overrides the tag from the title')
132 parser.add_argument('--source', '-s',
133 dest='source_line', type=str,
134 help='Overrides the source line, last line, ex: ' +
135 '(am from http://....)')
136 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-05 00:02:03137 nargs='+',
Brian Norris9f8a2be2018-06-01 18:14:08138 help='Patchwork ID (pw://### or pw://PROJECT/###, ' +
139 'where PROJECT is defined in ~/.pwclientrc; if no ' +
140 'PROJECT is specified, the default is retrieved from ' +
141 '~/.pwclientrc), ' +
142 'linux commit like linux://HASH, or ' +
Brian Norrisc9aeb2e2018-06-01 17:37:29143 'git reference like fromgit://remote/branch/HASH')
Alexandru M Stanfb5b5ee2014-12-04 21:32:55144
145 args = vars(parser.parse_args(args))
146
147 if args['replace']:
148 old_commit_message = subprocess.check_output(
149 ['git', 'show', '-s', '--format=%B', 'HEAD']
150 ).strip('\n')
151 args['changeid'] = re.findall('Change-Id: (.*)$',
152 old_commit_message, re.MULTILINE)[0]
153 if args['bug'] == parser.get_default('bug'):
154 args['bug'] = '\nBUG='.join(re.findall('BUG=(.*)$',
155 old_commit_message,
156 re.MULTILINE))
157 if args['test'] == parser.get_default('test'):
158 args['test'] = '\nTEST='.join(re.findall('TEST=(.*)$',
159 old_commit_message,
160 re.MULTILINE))
161 # TODO: deal with multiline BUG/TEST better
162 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
163
164 while len(args['locations']) > 0:
165 location = args['locations'].pop(0)
166
167 patchwork_match = re.match(
Brian Norris9f8a2be2018-06-01 18:14:08168 r'pw://(([-A-z]+)/)?(\d+)', location
Alexandru M Stanfb5b5ee2014-12-04 21:32:55169 )
170 linux_match = re.match(
171 r'linux://([0-9a-f]+)', location
172 )
173 fromgit_match = re.match(
174 r'fromgit://([^/]+)/(.+)/([0-9a-f]+)$', location
175 )
176
177 if patchwork_match is not None:
Brian Norris9f8a2be2018-06-01 18:14:08178 pw_project = patchwork_match.group(2)
179 patch_id = int(patchwork_match.group(3))
Alexandru M Stanfb5b5ee2014-12-04 21:32:55180
181 if args['source_line'] is None:
Brian Norris9f8a2be2018-06-01 18:14:08182 url = _get_pw_url(pw_project)
183 args['source_line'] = '(am from %s/patch/%d/)' % (url, patch_id)
184
Alexandru M Stanfb5b5ee2014-12-04 21:32:55185 if args['tag'] is None:
186 args['tag'] = 'FROMLIST: '
187
Brian Norris9f8a2be2018-06-01 18:14:08188 pw_args = []
189 if pw_project is not None:
190 pw_args += ['-p', pw_project]
191
192 pw_pipe = subprocess.Popen(['pwclient', 'view'] + pw_args +
193 [str(patch_id)], stdout=subprocess.PIPE)
Alexandru M Stanfb5b5ee2014-12-04 21:32:55194 s = pw_pipe.communicate()[0]
195
196 if not s:
197 sys.stderr.write('Error: No patch content found\n')
198 sys.exit(1)
199 git_am = subprocess.Popen(['git', 'am', '-3'], stdin=subprocess.PIPE)
Douglas Anderson8a6e1122018-07-02 23:03:53200 git_am.communicate(s)
Alexandru M Stanfb5b5ee2014-12-04 21:32:55201 ret = git_am.returncode
202 elif linux_match:
203 commit = linux_match.group(1)
204
205 # Confirm a 'linux' remote is setup.
Guenter Roeckd66daa72018-04-19 17:31:25206 linux_remote = _find_linux_remote()
207 if not linux_remote:
208 sys.stderr.write('Error: need a valid upstream remote\n')
Alexandru M Stanfb5b5ee2014-12-04 21:32:55209 sys.exit(1)
210
Guenter Roeckd66daa72018-04-19 17:31:25211 linux_master = '%s/master' % linux_remote
Alexandru M Stanfb5b5ee2014-12-04 21:32:55212 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
Guenter Roeckd66daa72018-04-19 17:31:25213 commit, linux_master])
Alexandru M Stanfb5b5ee2014-12-04 21:32:55214 if ret:
Guenter Roeckd66daa72018-04-19 17:31:25215 sys.stderr.write('Error: Commit not in %s\n' % linux_master)
Alexandru M Stanfb5b5ee2014-12-04 21:32:55216 sys.exit(1)
217
218 if args['source_line'] is None:
219 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
220 stdout=subprocess.PIPE)
221 commit = git_pipe.communicate()[0].strip()
222
223 args['source_line'] = ('(cherry picked from commit %s)' %
224 (commit))
225 if args['tag'] is None:
226 args['tag'] = 'UPSTREAM: '
227
228 ret = subprocess.call(['git', 'cherry-pick', commit])
229 elif fromgit_match is not None:
230 remote = fromgit_match.group(1)
231 branch = fromgit_match.group(2)
232 commit = fromgit_match.group(3)
233
234 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
235 commit, '%s/%s' % (remote, branch)])
236 if ret:
237 sys.stderr.write('Error: Commit not in %s/%s\n' %
238 (remote, branch))
239 sys.exit(1)
240
241 git_pipe = subprocess.Popen(['git', 'remote', 'get-url', remote],
242 stdout=subprocess.PIPE)
243 url = git_pipe.communicate()[0].strip()
244
245 if args['source_line'] is None:
246 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
247 stdout=subprocess.PIPE)
248 commit = git_pipe.communicate()[0].strip()
249
250 args['source_line'] = \
251 '(cherry picked from commit %s\n %s %s)' % \
252 (commit, url, branch)
253 if args['tag'] is None:
254 args['tag'] = 'FROMGIT: '
255
256 ret = subprocess.call(['git', 'cherry-pick', commit])
257 else:
258 sys.stderr.write('Don\'t know what "%s" means.\n' % location)
259 sys.exit(1)
260
261 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 17:05:08262 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 16:50:42263 if args['tag'] == 'UPSTREAM: ':
264 args['tag'] = 'BACKPORT: '
265 else:
266 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 17:05:08267 _pause_for_merge(conflicts)
268 else:
269 conflicts = ""
Alexandru M Stanfb5b5ee2014-12-04 21:32:55270
271 # extract commit message
272 commit_message = subprocess.check_output(
273 ['git', 'show', '-s', '--format=%B', 'HEAD']
274 ).strip('\n')
275
Guenter Roeck2e4f2512018-04-24 16:20:51276 # Remove stray Change-Id, most likely from merge resolution
277 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
278
Brian Norris7a41b982018-06-01 17:28:29279 # Note the source location before tagging anything else
280 commit_message += '\n' + args['source_line']
281
Alexandru M Stanfb5b5ee2014-12-04 21:32:55282 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
283 # next commands know where to work on
284 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 17:05:08285 commit_message += conflicts
Alexandru M Stanfb5b5ee2014-12-04 21:32:55286 commit_message += '\n' + 'BUG=' + args['bug']
287 commit_message += '\n' + 'TEST=' + args['test']
288 if args['signoff']:
289 extra = ['-s']
290 else:
291 extra = []
292 commit = subprocess.Popen(
293 ['git', 'commit'] + extra + ['--amend', '-F', '-'],
294 stdin=subprocess.PIPE
295 ).communicate(commit_message)
296
297 # re-extract commit message
298 commit_message = subprocess.check_output(
299 ['git', 'show', '-s', '--format=%B', 'HEAD']
300 ).strip('\n')
301
302 # replace changeid if needed
303 if args['changeid'] is not None:
304 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
305 args['changeid'], commit_message)
306 args['changeid'] = None
307
308 # decorate it that it's from outside
309 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 21:32:55310
311 # commit everything
312 commit = subprocess.Popen(
313 ['git', 'commit', '--amend', '-F', '-'], stdin=subprocess.PIPE
314 ).communicate(commit_message)
315
316 return 0
317
318if __name__ == '__main__':
319 sys.exit(main(sys.argv[1:]))