blob: 9df74c97b96aaab7ed39918897d767058f99ae90 [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
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 11:14:08 -070025_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
26
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070027def _get_conflicts():
28 """Report conflicting files."""
29 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
30 conflicts = []
Douglas Anderson46287f92018-04-30 09:58:24 -070031 lines = subprocess.check_output(['git', 'status', '--porcelain',
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070032 '--untracked-files=no']).split('\n')
Douglas Anderson46287f92018-04-30 09:58:24 -070033 for line in lines:
34 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070035 continue
Douglas Anderson46287f92018-04-30 09:58:24 -070036 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070037 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 10:31:25 -070043def _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 10:05:08 -070055def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080056 """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 10:05:08 -070068 sys.stderr.write(conflicts)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080069 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 11:14:08 -070077def _get_pw_url(project):
78 """Retrieve the patchwork server URL from .pwclientrc.
79
Mike Frysingerf80ca212018-07-13 15:02:52 -040080 Args:
81 project: patchwork project name; if None, we retrieve the default
82 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -070083 """
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 13:32:55 -0800104def 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-04 17:02:52 -0700116 type=str, required=True, help='BUG= line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800117 parser.add_argument('--test', '-t',
Douglas Andersonb8881842018-05-04 17:02:52 -0700118 type=str, required=True, help='TEST= line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800119 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-04 17:02:03 -0700137 nargs='+',
Brian Norris9f8a2be2018-06-01 11:14:08 -0700138 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 10:37:29 -0700143 'git reference like fromgit://remote/branch/HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800144
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
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800162
163 while len(args['locations']) > 0:
164 location = args['locations'].pop(0)
165
166 patchwork_match = re.match(
Brian Norris9f8a2be2018-06-01 11:14:08 -0700167 r'pw://(([-A-z]+)/)?(\d+)', location
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800168 )
169 linux_match = re.match(
170 r'linux://([0-9a-f]+)', location
171 )
172 fromgit_match = re.match(
173 r'fromgit://([^/]+)/(.+)/([0-9a-f]+)$', location
174 )
175
176 if patchwork_match is not None:
Brian Norris9f8a2be2018-06-01 11:14:08 -0700177 pw_project = patchwork_match.group(2)
178 patch_id = int(patchwork_match.group(3))
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800179
180 if args['source_line'] is None:
Brian Norris9f8a2be2018-06-01 11:14:08 -0700181 url = _get_pw_url(pw_project)
182 args['source_line'] = '(am from %s/patch/%d/)' % (url, patch_id)
183
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800184 if args['tag'] is None:
185 args['tag'] = 'FROMLIST: '
186
Brian Norris9f8a2be2018-06-01 11:14:08 -0700187 pw_args = []
188 if pw_project is not None:
189 pw_args += ['-p', pw_project]
190
191 pw_pipe = subprocess.Popen(['pwclient', 'view'] + pw_args +
192 [str(patch_id)], stdout=subprocess.PIPE)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800193 s = pw_pipe.communicate()[0]
194
195 if not s:
196 sys.stderr.write('Error: No patch content found\n')
197 sys.exit(1)
Guenter Roeckabe49d82018-07-25 14:11:48 -0700198
199 if args['replace']:
200 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
201
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800202 git_am = subprocess.Popen(['git', 'am', '-3'], stdin=subprocess.PIPE)
Douglas Anderson8a6e1122018-07-02 16:03:53 -0700203 git_am.communicate(s)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800204 ret = git_am.returncode
205 elif linux_match:
206 commit = linux_match.group(1)
207
208 # Confirm a 'linux' remote is setup.
Guenter Roeckd66daa72018-04-19 10:31:25 -0700209 linux_remote = _find_linux_remote()
210 if not linux_remote:
211 sys.stderr.write('Error: need a valid upstream remote\n')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800212 sys.exit(1)
213
Guenter Roeckd66daa72018-04-19 10:31:25 -0700214 linux_master = '%s/master' % linux_remote
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800215 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
Guenter Roeckd66daa72018-04-19 10:31:25 -0700216 commit, linux_master])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800217 if ret:
Guenter Roeckd66daa72018-04-19 10:31:25 -0700218 sys.stderr.write('Error: Commit not in %s\n' % linux_master)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800219 sys.exit(1)
220
221 if args['source_line'] is None:
222 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
223 stdout=subprocess.PIPE)
224 commit = git_pipe.communicate()[0].strip()
225
226 args['source_line'] = ('(cherry picked from commit %s)' %
227 (commit))
228 if args['tag'] is None:
229 args['tag'] = 'UPSTREAM: '
230
Guenter Roeckabe49d82018-07-25 14:11:48 -0700231 if args['replace']:
232 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
233
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800234 ret = subprocess.call(['git', 'cherry-pick', commit])
235 elif fromgit_match is not None:
236 remote = fromgit_match.group(1)
237 branch = fromgit_match.group(2)
238 commit = fromgit_match.group(3)
239
240 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
241 commit, '%s/%s' % (remote, branch)])
242 if ret:
243 sys.stderr.write('Error: Commit not in %s/%s\n' %
244 (remote, branch))
245 sys.exit(1)
246
247 git_pipe = subprocess.Popen(['git', 'remote', 'get-url', remote],
248 stdout=subprocess.PIPE)
249 url = git_pipe.communicate()[0].strip()
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'] = \
257 '(cherry picked from commit %s\n %s %s)' % \
258 (commit, url, branch)
259 if args['tag'] is None:
260 args['tag'] = 'FROMGIT: '
261
Guenter Roeckabe49d82018-07-25 14:11:48 -0700262 if args['replace']:
263 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
264
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800265 ret = subprocess.call(['git', 'cherry-pick', commit])
266 else:
267 sys.stderr.write('Don\'t know what "%s" means.\n' % location)
268 sys.exit(1)
269
270 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700271 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700272 if args['tag'] == 'UPSTREAM: ':
273 args['tag'] = 'BACKPORT: '
274 else:
275 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700276 _pause_for_merge(conflicts)
277 else:
278 conflicts = ""
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800279
280 # extract commit message
281 commit_message = subprocess.check_output(
282 ['git', 'show', '-s', '--format=%B', 'HEAD']
283 ).strip('\n')
284
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700285 # Remove stray Change-Id, most likely from merge resolution
286 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
287
Brian Norris7a41b982018-06-01 10:28:29 -0700288 # Note the source location before tagging anything else
289 commit_message += '\n' + args['source_line']
290
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800291 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
292 # next commands know where to work on
293 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700294 commit_message += conflicts
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800295 commit_message += '\n' + 'BUG=' + args['bug']
296 commit_message += '\n' + 'TEST=' + args['test']
297 if args['signoff']:
298 extra = ['-s']
299 else:
300 extra = []
301 commit = subprocess.Popen(
302 ['git', 'commit'] + extra + ['--amend', '-F', '-'],
303 stdin=subprocess.PIPE
304 ).communicate(commit_message)
305
306 # re-extract commit message
307 commit_message = subprocess.check_output(
308 ['git', 'show', '-s', '--format=%B', 'HEAD']
309 ).strip('\n')
310
311 # replace changeid if needed
312 if args['changeid'] is not None:
313 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
314 args['changeid'], commit_message)
315 args['changeid'] = None
316
317 # decorate it that it's from outside
318 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800319
320 # commit everything
321 commit = subprocess.Popen(
322 ['git', 'commit', '--amend', '-F', '-'], stdin=subprocess.PIPE
323 ).communicate(commit_message)
324
325 return 0
326
327if __name__ == '__main__':
328 sys.exit(main(sys.argv[1:]))