blob: 832eaece932a2b1c10eb838707d91fcb16e3360a [file] [log] [blame]
Alexandru M Stan725c71f2019-12-11 16:53:33 -08001#!/usr/bin/env python3
Brian Norris6baeb2e2020-03-18 12:13:30 -07002# -*- coding: utf-8 -*-
3#
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -08004# Copyright 2017 The Chromium OS Authors. All rights reserved.
5# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
Mike Frysingerf80ca212018-07-13 15:02:52 -04007
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -08008"""This is a tool for picking patches from upstream and applying them."""
9
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080010import argparse
Alexandru M Stan725c71f2019-12-11 16:53:33 -080011import configparser
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +080012import functools
Brian Norrisc3421042018-08-15 14:17:26 -070013import mailbox
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080014import os
Tzung-Bi Shih5100c742019-09-02 10:28:32 +080015import pprint
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080016import re
17import signal
18import subprocess
19import sys
Harry Cuttsae372f32019-02-12 18:01:14 -080020import textwrap
Alexandru M Stan725c71f2019-12-11 16:53:33 -080021import urllib.request
22import xmlrpc.client
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080023
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +080024errprint = functools.partial(print, file=sys.stderr)
25
Brian Norris00148182020-08-20 10:46:51 -070026# pylint: disable=line-too-long
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070027UPSTREAM_URLS = (
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080028 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
29 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
30 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070031 'git://w1.fi/srv/git/hostap.git',
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070032 'git://git.kernel.org/pub/scm/bluetooth/bluez.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070033)
34
Stephen Boydb68c17a2019-09-26 15:08:02 -070035PATCHWORK_URLS = (
36 'https://lore.kernel.org/patchwork',
37 'https://patchwork.kernel.org',
38 'https://patchwork.ozlabs.org',
39 'https://patchwork.freedesktop.org',
40 'https://patchwork.linux-mips.org',
41)
42
Harry Cuttsae372f32019-02-12 18:01:14 -080043COMMIT_MESSAGE_WIDTH = 75
44
Brian Norris9f8a2be2018-06-01 11:14:08 -070045_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
46
Alexandru M Stan725c71f2019-12-11 16:53:33 -080047def _git(args, stdin=None, encoding='utf-8'):
48 """Calls a git subcommand.
49
50 Similar to subprocess.check_output.
51
52 Args:
Brian Norris6baeb2e2020-03-18 12:13:30 -070053 args: subcommand + args passed to 'git'.
Alexandru M Stan725c71f2019-12-11 16:53:33 -080054 stdin: a string or bytes (depending on encoding) that will be passed
55 to the git subcommand.
56 encoding: either 'utf-8' (default) or None. Override it to None if
57 you want both stdin and stdout to be raw bytes.
58
59 Returns:
60 the stdout of the git subcommand, same type as stdin. The output is
61 also run through strip to make sure there's no extra whitespace.
62
63 Raises:
64 subprocess.CalledProcessError: when return code is not zero.
65 The exception has a .returncode attribute.
66 """
67 return subprocess.run(
68 ['git'] + args,
69 encoding=encoding,
70 input=stdin,
71 stdout=subprocess.PIPE,
72 check=True,
73 ).stdout.strip()
74
75def _git_returncode(*args, **kwargs):
76 """Same as _git, but return returncode instead of stdout.
77
78 Similar to subprocess.call.
79
80 Never raises subprocess.CalledProcessError.
81 """
82 try:
83 _git(*args, **kwargs)
84 return 0
85 except subprocess.CalledProcessError as e:
86 return e.returncode
87
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070088def _get_conflicts():
89 """Report conflicting files."""
90 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
91 conflicts = []
Alexandru M Stan725c71f2019-12-11 16:53:33 -080092 output = _git(['status', '--porcelain', '--untracked-files=no'])
93 for line in output.splitlines():
Douglas Anderson46287f92018-04-30 09:58:24 -070094 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070095 continue
Douglas Anderson46287f92018-04-30 09:58:24 -070096 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070097 if resolution in resolutions:
98 conflicts.append(' ' + name)
99 if not conflicts:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700100 return ''
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700101 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
102
Brian Norris8043cfd2020-03-19 11:46:16 -0700103def _find_upstream_remote(urls):
104 """Find a remote pointing to an upstream repository."""
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800105 for remote in _git(['remote']).splitlines():
106 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700107 if _git(['remote', 'get-url', remote]) in urls:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800108 return remote
109 except subprocess.CalledProcessError:
110 # Kinda weird, get-url failing on an item that git just gave us.
111 continue
Guenter Roeckd66daa72018-04-19 10:31:25 -0700112 return None
113
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700114def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800115 """Pause and go in the background till user resolves the conflicts."""
116
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800117 git_root = _git(['rev-parse', '--show-toplevel'])
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800118 previous_head_hash = _git(['rev-parse', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800119
120 paths = (
121 os.path.join(git_root, '.git', 'rebase-apply'),
122 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
123 )
124 for path in paths:
125 if os.path.exists(path):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800126 errprint('Found "%s".' % path)
127 errprint(conflicts)
128 errprint('Please resolve the conflicts and restart the '
129 'shell job when done. Kill this job if you '
130 'aborted the conflict.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800131 os.kill(os.getpid(), signal.SIGTSTP)
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800132
133 # Check the conflicts actually got resolved. Otherwise we'll end up
134 # modifying the wrong commit message and probably confusing people.
135 while previous_head_hash == _git(['rev-parse', 'HEAD']):
136 errprint('Error: no new commit has been made. Did you forget to run '
137 '`git am --continue` or `git cherry-pick --continue`?')
138 errprint('Please create a new commit and restart the shell job (or kill'
139 ' it if you aborted the conflict).')
140 os.kill(os.getpid(), signal.SIGTSTP)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800141
Brian Norris9f8a2be2018-06-01 11:14:08 -0700142def _get_pw_url(project):
143 """Retrieve the patchwork server URL from .pwclientrc.
144
Mike Frysingerf80ca212018-07-13 15:02:52 -0400145 Args:
146 project: patchwork project name; if None, we retrieve the default
147 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -0700148 """
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800149 config = configparser.ConfigParser()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700150 config.read([_PWCLIENTRC])
151
152 if project is None:
153 try:
154 project = config.get('options', 'default')
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800155 except (configparser.NoSectionError, configparser.NoOptionError) as e:
156 errprint('Error: no default patchwork project found in %s. (%r)'
157 % (_PWCLIENTRC, e))
Brian Norris9f8a2be2018-06-01 11:14:08 -0700158 sys.exit(1)
159
160 if not config.has_option(project, 'url'):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800161 errprint("Error: patchwork URL not found for project '%s'" % project)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700162 sys.exit(1)
163
164 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700165 # Strip trailing 'xmlrpc' and/or trailing slash.
166 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700167
Harry Cuttsae372f32019-02-12 18:01:14 -0800168def _wrap_commit_line(prefix, content):
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800169 line = prefix + content
170 indent = ' ' * len(prefix)
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800171
172 ret = textwrap.fill(line, COMMIT_MESSAGE_WIDTH, subsequent_indent=indent)
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800173 return ret[len(prefix):]
Harry Cuttsae372f32019-02-12 18:01:14 -0800174
Stephen Boydb68c17a2019-09-26 15:08:02 -0700175def _pick_patchwork(url, patch_id, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800176 if args['tag'] is None:
177 args['tag'] = 'FROMLIST: '
178
Brian Norris8553f032020-03-18 11:59:02 -0700179 try:
180 opener = urllib.request.urlopen('%s/patch/%d/mbox' % (url, patch_id))
181 except urllib.error.HTTPError as e:
182 errprint('Error: could not download patch: %s' % e)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800183 sys.exit(1)
184 patch_contents = opener.read()
185
186 if not patch_contents:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800187 errprint('Error: No patch content found')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800188 sys.exit(1)
189
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700190 message_id = mailbox.Message(patch_contents)['Message-Id']
191 message_id = re.sub('^<|>$', '', message_id.strip())
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800192 if args['source_line'] is None:
193 args['source_line'] = '(am from %s/patch/%d/)' % (url, patch_id)
Brian Norris8553f032020-03-18 11:59:02 -0700194 for url_template in [
Brian Norris655b5ce2020-05-08 11:37:38 -0700195 'https://lore.kernel.org/r/%s',
Brian Norris8553f032020-03-18 11:59:02 -0700196 # hostap project (and others) are here, but not kernel.org.
197 'https://marc.info/?i=%s',
198 # public-inbox comes last as a "default"; it has a nice error page
199 # pointing to other redirectors, even if it doesn't have what
200 # you're looking for directly.
201 'https://public-inbox.org/git/%s',
202 ]:
203 alt_url = url_template % message_id
204 if args['debug']:
205 print('Probing archive for message at: %s' % alt_url)
206 try:
207 urllib.request.urlopen(alt_url)
208 except urllib.error.HTTPError as e:
209 # Skip all HTTP errors. We can expect 404 for archives that
210 # don't have this MessageId, or 300 for public-inbox ("not
211 # found, but try these other redirects"). It's less clear what
212 # to do with transitory (or is it permanent?) server failures.
213 if args['debug']:
214 print('Skipping URL %s, error: %s' % (alt_url, e))
215 continue
216 # Success!
217 if args['debug']:
218 print('Found at %s' % alt_url)
219 break
220 else:
221 errprint(
222 "WARNING: couldn't find working MessageId URL; "
223 'defaulting to "%s"' % alt_url)
224 args['source_line'] += '\n(also found at %s)' % alt_url
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800225
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700226 # Auto-snarf the Change-Id if it was encoded into the Message-Id.
227 mo = re.match(r'.*(I[a-f0-9]{40})@changeid$', message_id)
228 if mo and args['changeid'] is None:
229 args['changeid'] = mo.group(1)
230
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800231 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800232 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800233
Tzung-Bi Shih3a4ebda2020-08-10 09:45:19 +0800234 return _git_returncode(['am', '-3', '--reject'], stdin=patch_contents,
235 encoding=None)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800236
Stephen Boydb68c17a2019-09-26 15:08:02 -0700237def _match_patchwork(match, args):
238 """Match location: pw://### or pw://PROJECT/###."""
239 pw_project = match.group(2)
240 patch_id = int(match.group(3))
241
242 if args['debug']:
243 print('_match_patchwork: pw_project=%s, patch_id=%d' %
244 (pw_project, patch_id))
245
246 url = _get_pw_url(pw_project)
247 return _pick_patchwork(url, patch_id, args)
248
249def _match_msgid(match, args):
250 """Match location: msgid://MSGID."""
251 msgid = match.group(1)
252
253 if args['debug']:
254 print('_match_msgid: message_id=%s' % (msgid))
255
256 # Patchwork requires the brackets so force it
257 msgid = '<' + msgid + '>'
258 url = None
259 for url in PATCHWORK_URLS:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800260 rpc = xmlrpc.client.ServerProxy(url + '/xmlrpc/')
Stephen Boydb68c17a2019-09-26 15:08:02 -0700261 res = rpc.patch_list({'msgid': msgid})
262 if res:
263 patch_id = res[0]['id']
264 break
265 else:
266 errprint('Error: could not find patch based on message id')
267 sys.exit(1)
268
269 return _pick_patchwork(url, patch_id, args)
270
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700271def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800272 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700273 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800274
Brian Norris8043cfd2020-03-19 11:46:16 -0700275 # Confirm an upstream remote is setup.
276 remote = _find_upstream_remote(urls)
277 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800278 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800279 sys.exit(1)
280
Brian Norris8043cfd2020-03-19 11:46:16 -0700281 remote_ref = '%s/master' % remote
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800282 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700283 _git(['merge-base', '--is-ancestor', commit, remote_ref])
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800284 except subprocess.CalledProcessError:
Brian Norris8043cfd2020-03-19 11:46:16 -0700285 errprint('Error: Commit not in %s' % remote_ref)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800286 sys.exit(1)
287
288 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800289 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800290 args['source_line'] = ('(cherry picked from commit %s)' %
291 (commit))
292 if args['tag'] is None:
293 args['tag'] = 'UPSTREAM: '
294
295 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800296 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800297
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800298 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800299
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700300def _match_upstream(match, args):
301 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700302 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700303 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700304
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800305def _match_fromgit(match, args):
306 """Match location: git://remote/branch/HASH."""
307 remote = match.group(2)
308 branch = match.group(3)
309 commit = match.group(4)
310
311 if args['debug']:
312 print('_match_fromgit: remote=%s branch=%s commit=%s' %
313 (remote, branch, commit))
314
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800315 try:
316 _git(['merge-base', '--is-ancestor', commit,
317 '%s/%s' % (remote, branch)])
318 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800319 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800320 sys.exit(1)
321
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800322 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800323
324 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800325 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800326 args['source_line'] = (
327 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800328 if args['tag'] is None:
329 args['tag'] = 'FROMGIT: '
330
331 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800332 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800333
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800334 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800335
336def _match_gitfetch(match, args):
337 """Match location: (git|https)://repoURL#branch/HASH."""
338 remote = match.group(1)
339 branch = match.group(3)
340 commit = match.group(4)
341
342 if args['debug']:
343 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
344 (remote, branch, commit))
345
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800346 try:
347 _git(['fetch', remote, branch])
348 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800349 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800350 sys.exit(1)
351
352 url = remote
353
354 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800355 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800356 args['source_line'] = (
357 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800358 if args['tag'] is None:
359 args['tag'] = 'FROMGIT: '
360
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800361 if args['replace']:
362 _git(['reset', '--hard', 'HEAD~1'])
363
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800364 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800365
Stephen Boyd96396032020-02-25 10:12:59 -0800366def _match_gitweb(match, args):
367 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
368 remote = match.group(1)
369 branch = match.group(2)
370 commit = match.group(3)
371
372 if args['debug']:
373 print('_match_gitweb: remote=%s branch=%s commit=%s' %
374 (remote, branch, commit))
375
376 try:
377 _git(['fetch', remote, branch])
378 except subprocess.CalledProcessError:
379 errprint('Error: Branch not in %s' % remote)
380 sys.exit(1)
381
382 url = remote
383
384 if args['source_line'] is None:
385 commit = _git(['rev-parse', commit])
386 args['source_line'] = (
387 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
388 if args['tag'] is None:
389 args['tag'] = 'FROMGIT: '
390
391 if args['replace']:
392 _git(['reset', '--hard', 'HEAD~1'])
393
394 return _git_returncode(['cherry-pick', commit])
395
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800396def main(args):
397 """This is the main entrypoint for fromupstream.
398
399 Args:
400 args: sys.argv[1:]
401
402 Returns:
403 An int return code.
404 """
405 parser = argparse.ArgumentParser()
406
407 parser.add_argument('--bug', '-b',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700408 type=str, help='BUG= line')
Brian Norris6bcfa392020-08-20 10:38:05 -0700409 parser.add_argument('--test', '-t', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700410 type=str, help='TEST= line')
Stephen Boyd24b309b2018-11-06 22:11:00 -0800411 parser.add_argument('--crbug', action='append',
412 type=int, help='BUG=chromium: line')
413 parser.add_argument('--buganizer', action='append',
414 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800415 parser.add_argument('--changeid', '-c',
416 help='Overrides the gerrit generated Change-Id line')
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800417 parser.add_argument('--cqdepend',
418 type=str, help='Cq-Depend: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800419
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800420 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800421 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800422 help='Replaces the HEAD commit with this one, taking '
423 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800424 'updating commits.')
425 parser.add_argument('--nosignoff',
426 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800427 parser.add_argument('--debug', '-d', action='store_true',
428 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800429
430 parser.add_argument('--tag',
431 help='Overrides the tag from the title')
432 parser.add_argument('--source', '-s',
433 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800434 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800435 '(am from http://....)')
436 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700437 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800438 help='Patchwork ID (pw://### or pw://PROJECT/###, '
439 'where PROJECT is defined in ~/.pwclientrc; if no '
440 'PROJECT is specified, the default is retrieved from '
441 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700442 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700443 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700444 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800445 'git reference like git://remote/branch/HASH or '
446 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800447 'https://repoURL#branch/HASH or '
448 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800449
450 args = vars(parser.parse_args(args))
451
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800452 cq_depends = [args['cqdepend']] if args['cqdepend'] else []
453
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800454 bug_lines = []
455 if args['bug']:
456 # un-wrap intentionally
457 bug_lines += [args['bug']]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800458 if args['buganizer']:
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800459 buganizers = ', '.join('b:%d' % x for x in args['buganizer'])
Brian Norris00148182020-08-20 10:46:51 -0700460 bug_lines += [x.strip(' ,') for x in
461 _wrap_commit_line('BUG=', buganizers).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800462 if args['crbug']:
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800463 crbugs = ', '.join('chromium:%d' % x for x in args['crbug'])
Brian Norris00148182020-08-20 10:46:51 -0700464 bug_lines += [x.strip(' ,') for x in
465 _wrap_commit_line('BUG=', crbugs).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800466
Brian Norris6bcfa392020-08-20 10:38:05 -0700467 test_lines = [_wrap_commit_line('TEST=', x) for x in args['test']]
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800468
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800469 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800470 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800471
472 # It is possible that multiple Change-Ids are in the commit message
473 # (due to cherry picking). We only want to pull out the first one.
474 changeid_match = re.search('^Change-Id: (.*)$',
475 old_commit_message, re.MULTILINE)
Tzung-Bi Shih5fd0fd52020-08-13 11:06:33 +0800476 if args['changeid'] is None and changeid_match:
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800477 args['changeid'] = changeid_match.group(1)
478
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800479 if not cq_depends:
480 cq_depends = re.findall(r'^Cq-Depend:\s+(.*)$',
481 old_commit_message, re.MULTILINE)
Tzung-Bi Shihdfe82002020-08-13 11:00:56 +0800482
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800483 if not bug_lines:
484 bug_lines = re.findall(r'^BUG=(.*)$',
485 old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800486
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800487 if not test_lines:
488 # Note: use (?=...) to avoid to consume the source string
489 test_lines = re.findall(r"""
490 ^TEST=(.*?) # Match start from TEST= until
491 \n # (to remove the tailing newlines)
492 (?=^$| # a blank line
493 ^Cq-Depend:| # or Cq-Depend:
494 ^Change-Id:| # or Change-Id:
495 ^BUG=| # or following BUG=
496 ^TEST=) # or another TEST=
497 """,
498 old_commit_message, re.MULTILINE | re.DOTALL | re.VERBOSE)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800499
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800500 if not bug_lines or not test_lines:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800501 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800502 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700503
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800504 if args['debug']:
505 pprint.pprint(args)
506
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800507 re_matches = (
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800508 (re.compile(r'^pw://(([^/]+)/)?(\d+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700509 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700510 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
511 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800512 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800513 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800514 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800515 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800516 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800517
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800518 for location in args['locations']:
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800519 if args['debug']:
520 print('location=%s' % location)
521
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800522 for reg, handler in re_matches:
523 match = reg.match(location)
524 if match:
525 ret = handler(match, args)
526 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800527 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800528 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800529 sys.exit(1)
530
531 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700532 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700533 if args['tag'] == 'UPSTREAM: ':
534 args['tag'] = 'BACKPORT: '
535 else:
536 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700537 _pause_for_merge(conflicts)
538 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700539 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800540
541 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800542 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800543
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700544 # Remove stray Change-Id, most likely from merge resolution
545 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
546
Brian Norris7a41b982018-06-01 10:28:29 -0700547 # Note the source location before tagging anything else
548 commit_message += '\n' + args['source_line']
549
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800550 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
551 # next commands know where to work on
552 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700553 commit_message += conflicts
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800554 commit_message += '\n'
555 commit_message += '\n'.join('BUG=%s' % bug for bug in bug_lines)
556 commit_message += '\n'
557 commit_message += '\n'.join('TEST=%s' % t for t in test_lines)
Brian Norris674209e2020-04-22 15:33:53 -0700558
559 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800560 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700561 signoff = 'Signed-off-by: %s <%s>' % (
562 _git(['config', 'user.name']),
563 _git(['config', 'user.email']))
564 if not signoff in commit_message.splitlines():
565 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800566 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800567
568 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800569 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800570
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700571 # If we see a "Link: " that seems to point to a Message-Id with an
572 # automatic Change-Id we'll snarf it out.
573 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
574 re.MULTILINE)
575 if mo and args['changeid'] is None:
576 args['changeid'] = mo.group(1)
577
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800578 # replace changeid if needed
579 if args['changeid'] is not None:
580 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
581 args['changeid'], commit_message)
582 args['changeid'] = None
583
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800584 if cq_depends:
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800585 commit_message = re.sub(
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800586 r'(Change-Id: \w+)',
587 r'%s\n\1' % '\n'.join('Cq-Depend: %s' % c for c in cq_depends),
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800588 commit_message)
589
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800590 # decorate it that it's from outside
591 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800592
593 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800594 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800595
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900596 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800597
598if __name__ == '__main__':
599 sys.exit(main(sys.argv[1:]))