blob: 42b6ad2f8164cbb6128ec0881bfd4d8140a4cc6e [file] [log] [blame]
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -08001#!/usr/bin/env python2
2#
3# 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.
6"""This is a tool for picking patches from upstream and applying them."""
7
8from __future__ import print_function
9
10import argparse
11import os
12import re
13import signal
14import subprocess
15import sys
16
17LINUX_URLS = (
18 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
19 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
20 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
21)
22
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070023def _get_conflicts():
24 """Report conflicting files."""
25 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
26 conflicts = []
Douglas Anderson46287f92018-04-30 09:58:24 -070027 lines = subprocess.check_output(['git', 'status', '--porcelain',
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070028 '--untracked-files=no']).split('\n')
Douglas Anderson46287f92018-04-30 09:58:24 -070029 for line in lines:
30 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070031 continue
Douglas Anderson46287f92018-04-30 09:58:24 -070032 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070033 if resolution in resolutions:
34 conflicts.append(' ' + name)
35 if not conflicts:
36 return ""
37 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
38
Guenter Roeckd66daa72018-04-19 10:31:25 -070039def _find_linux_remote():
40 """Find a remote pointing to a Linux upstream repository."""
41 git_remote = subprocess.Popen(['git', 'remote'], stdout=subprocess.PIPE)
42 remotes = git_remote.communicate()[0].strip()
43 for remote in remotes.splitlines():
44 rurl = subprocess.Popen(['git', 'remote', 'get-url', remote],
45 stdout=subprocess.PIPE)
46 url = rurl.communicate()[0].strip()
47 if not rurl.returncode and url in LINUX_URLS:
48 return remote
49 return None
50
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070051def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080052 """Pause and go in the background till user resolves the conflicts."""
53
54 git_root = subprocess.check_output(['git', 'rev-parse',
55 '--show-toplevel']).strip('\n')
56
57 paths = (
58 os.path.join(git_root, '.git', 'rebase-apply'),
59 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
60 )
61 for path in paths:
62 if os.path.exists(path):
63 sys.stderr.write('Found "%s".\n' % path)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070064 sys.stderr.write(conflicts)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080065 sys.stderr.write('Please resolve the conflicts and restart the ' +
66 'shell job when done. Kill this job if you ' +
67 'aborted the conflict.\n')
68 os.kill(os.getpid(), signal.SIGTSTP)
69 # TODO: figure out what the state is after the merging, and go based on
70 # that (should we abort? skip? continue?)
71 # Perhaps check last commit message to see if it's the one we were using.
72
73def main(args):
74 """This is the main entrypoint for fromupstream.
75
76 Args:
77 args: sys.argv[1:]
78
79 Returns:
80 An int return code.
81 """
82 parser = argparse.ArgumentParser()
83
84 parser.add_argument('--bug', '-b',
85 type=str, default='None', help='BUG= line')
86 parser.add_argument('--test', '-t',
87 type=str, default='Build and boot', help='TEST= line')
88 parser.add_argument('--changeid', '-c',
89 help='Overrides the gerrit generated Change-Id line')
90
91 parser.add_argument('--replace',
92 action='store_true',
93 help='Replaces the HEAD commit with this one, taking ' +
94 'its properties(BUG, TEST, Change-Id). Useful for ' +
95 'updating commits.')
96 parser.add_argument('--nosignoff',
97 dest='signoff', action='store_false')
98
99 parser.add_argument('--tag',
100 help='Overrides the tag from the title')
101 parser.add_argument('--source', '-s',
102 dest='source_line', type=str,
103 help='Overrides the source line, last line, ex: ' +
104 '(am from http://....)')
105 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700106 nargs='+',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800107 help='Patchwork url (either ' +
108 'https://patchwork.kernel.org/patch/###/ or ' +
109 'pw://###), linux commit like linux://HASH, git ' +
110 'refrerence like fromgit://remote/branch/HASH')
111
112 args = vars(parser.parse_args(args))
113
114 if args['replace']:
115 old_commit_message = subprocess.check_output(
116 ['git', 'show', '-s', '--format=%B', 'HEAD']
117 ).strip('\n')
118 args['changeid'] = re.findall('Change-Id: (.*)$',
119 old_commit_message, re.MULTILINE)[0]
120 if args['bug'] == parser.get_default('bug'):
121 args['bug'] = '\nBUG='.join(re.findall('BUG=(.*)$',
122 old_commit_message,
123 re.MULTILINE))
124 if args['test'] == parser.get_default('test'):
125 args['test'] = '\nTEST='.join(re.findall('TEST=(.*)$',
126 old_commit_message,
127 re.MULTILINE))
128 # TODO: deal with multiline BUG/TEST better
129 subprocess.call(['git', 'reset', '--hard', 'HEAD~1'])
130
131 while len(args['locations']) > 0:
132 location = args['locations'].pop(0)
133
134 patchwork_match = re.match(
135 r'((pw://)|(https?://patchwork.kernel.org/patch/))(\d+)/?', location
136 )
137 linux_match = re.match(
138 r'linux://([0-9a-f]+)', location
139 )
140 fromgit_match = re.match(
141 r'fromgit://([^/]+)/(.+)/([0-9a-f]+)$', location
142 )
143
144 if patchwork_match is not None:
145 patch_id = int(patchwork_match.group(4))
146
147 if args['source_line'] is None:
148 args['source_line'] = \
149 '(am from https://patchwork.kernel.org/patch/%d/)' % \
150 patch_id
151 if args['tag'] is None:
152 args['tag'] = 'FROMLIST: '
153
154 pw_pipe = subprocess.Popen(['pwclient', 'view', str(patch_id)],
155 stdout=subprocess.PIPE)
156 s = pw_pipe.communicate()[0]
157
158 if not s:
159 sys.stderr.write('Error: No patch content found\n')
160 sys.exit(1)
161 git_am = subprocess.Popen(['git', 'am', '-3'], stdin=subprocess.PIPE)
162 git_am.communicate(unicode(s).encode('utf-8'))
163 ret = git_am.returncode
164 elif linux_match:
165 commit = linux_match.group(1)
166
167 # Confirm a 'linux' remote is setup.
Guenter Roeckd66daa72018-04-19 10:31:25 -0700168 linux_remote = _find_linux_remote()
169 if not linux_remote:
170 sys.stderr.write('Error: need a valid upstream remote\n')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800171 sys.exit(1)
172
Guenter Roeckd66daa72018-04-19 10:31:25 -0700173 linux_master = '%s/master' % linux_remote
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800174 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
Guenter Roeckd66daa72018-04-19 10:31:25 -0700175 commit, linux_master])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800176 if ret:
Guenter Roeckd66daa72018-04-19 10:31:25 -0700177 sys.stderr.write('Error: Commit not in %s\n' % linux_master)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800178 sys.exit(1)
179
180 if args['source_line'] is None:
181 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
182 stdout=subprocess.PIPE)
183 commit = git_pipe.communicate()[0].strip()
184
185 args['source_line'] = ('(cherry picked from commit %s)' %
186 (commit))
187 if args['tag'] is None:
188 args['tag'] = 'UPSTREAM: '
189
190 ret = subprocess.call(['git', 'cherry-pick', commit])
191 elif fromgit_match is not None:
192 remote = fromgit_match.group(1)
193 branch = fromgit_match.group(2)
194 commit = fromgit_match.group(3)
195
196 ret = subprocess.call(['git', 'merge-base', '--is-ancestor',
197 commit, '%s/%s' % (remote, branch)])
198 if ret:
199 sys.stderr.write('Error: Commit not in %s/%s\n' %
200 (remote, branch))
201 sys.exit(1)
202
203 git_pipe = subprocess.Popen(['git', 'remote', 'get-url', remote],
204 stdout=subprocess.PIPE)
205 url = git_pipe.communicate()[0].strip()
206
207 if args['source_line'] is None:
208 git_pipe = subprocess.Popen(['git', 'rev-parse', commit],
209 stdout=subprocess.PIPE)
210 commit = git_pipe.communicate()[0].strip()
211
212 args['source_line'] = \
213 '(cherry picked from commit %s\n %s %s)' % \
214 (commit, url, branch)
215 if args['tag'] is None:
216 args['tag'] = 'FROMGIT: '
217
218 ret = subprocess.call(['git', 'cherry-pick', commit])
219 else:
220 sys.stderr.write('Don\'t know what "%s" means.\n' % location)
221 sys.exit(1)
222
223 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700224 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700225 if args['tag'] == 'UPSTREAM: ':
226 args['tag'] = 'BACKPORT: '
227 else:
228 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700229 _pause_for_merge(conflicts)
230 else:
231 conflicts = ""
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800232
233 # extract commit message
234 commit_message = subprocess.check_output(
235 ['git', 'show', '-s', '--format=%B', 'HEAD']
236 ).strip('\n')
237
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700238 # Remove stray Change-Id, most likely from merge resolution
239 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
240
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800241 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
242 # next commands know where to work on
243 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700244 commit_message += conflicts
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800245 commit_message += '\n' + 'BUG=' + args['bug']
246 commit_message += '\n' + 'TEST=' + args['test']
247 if args['signoff']:
248 extra = ['-s']
249 else:
250 extra = []
251 commit = subprocess.Popen(
252 ['git', 'commit'] + extra + ['--amend', '-F', '-'],
253 stdin=subprocess.PIPE
254 ).communicate(commit_message)
255
256 # re-extract commit message
257 commit_message = subprocess.check_output(
258 ['git', 'show', '-s', '--format=%B', 'HEAD']
259 ).strip('\n')
260
261 # replace changeid if needed
262 if args['changeid'] is not None:
263 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
264 args['changeid'], commit_message)
265 args['changeid'] = None
266
267 # decorate it that it's from outside
268 commit_message = args['tag'] + commit_message
269 commit_message += '\n' + args['source_line']
270
271 # commit everything
272 commit = subprocess.Popen(
273 ['git', 'commit', '--amend', '-F', '-'], stdin=subprocess.PIPE
274 ).communicate(commit_message)
275
276 return 0
277
278if __name__ == '__main__':
279 sys.exit(main(sys.argv[1:]))