blob: a029ab7613c773b79ee586062fb0e07e9b99c72e [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
Douglas Anderson297a3062020-09-09 12:47:09 -070018import ssl
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080019import subprocess
20import sys
Harry Cuttsae372f32019-02-12 18:01:14 -080021import textwrap
Alexandru M Stan725c71f2019-12-11 16:53:33 -080022import urllib.request
23import xmlrpc.client
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080024
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +080025errprint = functools.partial(print, file=sys.stderr)
26
Brian Norris00148182020-08-20 10:46:51 -070027# pylint: disable=line-too-long
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070028UPSTREAM_URLS = (
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080029 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
30 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
31 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070032 'git://w1.fi/srv/git/hostap.git',
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070033 'git://git.kernel.org/pub/scm/bluetooth/bluez.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070034)
35
Stephen Boydb68c17a2019-09-26 15:08:02 -070036PATCHWORK_URLS = (
37 'https://lore.kernel.org/patchwork',
38 'https://patchwork.kernel.org',
39 'https://patchwork.ozlabs.org',
40 'https://patchwork.freedesktop.org',
41 'https://patchwork.linux-mips.org',
42)
43
Harry Cuttsae372f32019-02-12 18:01:14 -080044COMMIT_MESSAGE_WIDTH = 75
45
Brian Norris9f8a2be2018-06-01 11:14:08 -070046_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
47
Alexandru M Stan725c71f2019-12-11 16:53:33 -080048def _git(args, stdin=None, encoding='utf-8'):
49 """Calls a git subcommand.
50
51 Similar to subprocess.check_output.
52
53 Args:
Brian Norris6baeb2e2020-03-18 12:13:30 -070054 args: subcommand + args passed to 'git'.
Alexandru M Stan725c71f2019-12-11 16:53:33 -080055 stdin: a string or bytes (depending on encoding) that will be passed
56 to the git subcommand.
57 encoding: either 'utf-8' (default) or None. Override it to None if
58 you want both stdin and stdout to be raw bytes.
59
60 Returns:
61 the stdout of the git subcommand, same type as stdin. The output is
62 also run through strip to make sure there's no extra whitespace.
63
64 Raises:
65 subprocess.CalledProcessError: when return code is not zero.
66 The exception has a .returncode attribute.
67 """
68 return subprocess.run(
69 ['git'] + args,
70 encoding=encoding,
71 input=stdin,
72 stdout=subprocess.PIPE,
73 check=True,
74 ).stdout.strip()
75
76def _git_returncode(*args, **kwargs):
77 """Same as _git, but return returncode instead of stdout.
78
79 Similar to subprocess.call.
80
81 Never raises subprocess.CalledProcessError.
82 """
83 try:
84 _git(*args, **kwargs)
85 return 0
86 except subprocess.CalledProcessError as e:
87 return e.returncode
88
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070089def _get_conflicts():
90 """Report conflicting files."""
91 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
92 conflicts = []
Alexandru M Stan725c71f2019-12-11 16:53:33 -080093 output = _git(['status', '--porcelain', '--untracked-files=no'])
94 for line in output.splitlines():
Douglas Anderson46287f92018-04-30 09:58:24 -070095 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070096 continue
Douglas Anderson46287f92018-04-30 09:58:24 -070097 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070098 if resolution in resolutions:
99 conflicts.append(' ' + name)
100 if not conflicts:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700101 return ''
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700102 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
103
Brian Norris8043cfd2020-03-19 11:46:16 -0700104def _find_upstream_remote(urls):
105 """Find a remote pointing to an upstream repository."""
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800106 for remote in _git(['remote']).splitlines():
107 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700108 if _git(['remote', 'get-url', remote]) in urls:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800109 return remote
110 except subprocess.CalledProcessError:
111 # Kinda weird, get-url failing on an item that git just gave us.
112 continue
Guenter Roeckd66daa72018-04-19 10:31:25 -0700113 return None
114
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700115def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800116 """Pause and go in the background till user resolves the conflicts."""
117
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800118 git_root = _git(['rev-parse', '--show-toplevel'])
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800119 previous_head_hash = _git(['rev-parse', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800120
121 paths = (
122 os.path.join(git_root, '.git', 'rebase-apply'),
123 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
124 )
125 for path in paths:
126 if os.path.exists(path):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800127 errprint('Found "%s".' % path)
128 errprint(conflicts)
129 errprint('Please resolve the conflicts and restart the '
130 'shell job when done. Kill this job if you '
131 'aborted the conflict.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800132 os.kill(os.getpid(), signal.SIGTSTP)
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800133
134 # Check the conflicts actually got resolved. Otherwise we'll end up
135 # modifying the wrong commit message and probably confusing people.
136 while previous_head_hash == _git(['rev-parse', 'HEAD']):
137 errprint('Error: no new commit has been made. Did you forget to run '
138 '`git am --continue` or `git cherry-pick --continue`?')
139 errprint('Please create a new commit and restart the shell job (or kill'
140 ' it if you aborted the conflict).')
141 os.kill(os.getpid(), signal.SIGTSTP)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800142
Brian Norris9f8a2be2018-06-01 11:14:08 -0700143def _get_pw_url(project):
144 """Retrieve the patchwork server URL from .pwclientrc.
145
Mike Frysingerf80ca212018-07-13 15:02:52 -0400146 Args:
147 project: patchwork project name; if None, we retrieve the default
148 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -0700149 """
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800150 config = configparser.ConfigParser()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700151 config.read([_PWCLIENTRC])
152
153 if project is None:
154 try:
155 project = config.get('options', 'default')
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800156 except (configparser.NoSectionError, configparser.NoOptionError) as e:
157 errprint('Error: no default patchwork project found in %s. (%r)'
158 % (_PWCLIENTRC, e))
Brian Norris9f8a2be2018-06-01 11:14:08 -0700159 sys.exit(1)
160
161 if not config.has_option(project, 'url'):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800162 errprint("Error: patchwork URL not found for project '%s'" % project)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700163 sys.exit(1)
164
165 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700166 # Strip trailing 'xmlrpc' and/or trailing slash.
167 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700168
Harry Cuttsae372f32019-02-12 18:01:14 -0800169def _wrap_commit_line(prefix, content):
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800170 line = prefix + content
171 indent = ' ' * len(prefix)
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800172
173 ret = textwrap.fill(line, COMMIT_MESSAGE_WIDTH, subsequent_indent=indent)
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800174 return ret[len(prefix):]
Harry Cuttsae372f32019-02-12 18:01:14 -0800175
Stephen Boydb68c17a2019-09-26 15:08:02 -0700176def _pick_patchwork(url, patch_id, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800177 if args['tag'] is None:
178 args['tag'] = 'FROMLIST: '
179
Brian Norris8553f032020-03-18 11:59:02 -0700180 try:
181 opener = urllib.request.urlopen('%s/patch/%d/mbox' % (url, patch_id))
182 except urllib.error.HTTPError as e:
183 errprint('Error: could not download patch: %s' % e)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800184 sys.exit(1)
185 patch_contents = opener.read()
186
187 if not patch_contents:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800188 errprint('Error: No patch content found')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800189 sys.exit(1)
190
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700191 message_id = mailbox.Message(patch_contents)['Message-Id']
192 message_id = re.sub('^<|>$', '', message_id.strip())
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800193 if args['source_line'] is None:
194 args['source_line'] = '(am from %s/patch/%d/)' % (url, patch_id)
Brian Norris8553f032020-03-18 11:59:02 -0700195 for url_template in [
Brian Norris655b5ce2020-05-08 11:37:38 -0700196 'https://lore.kernel.org/r/%s',
Brian Norris8553f032020-03-18 11:59:02 -0700197 # hostap project (and others) are here, but not kernel.org.
198 'https://marc.info/?i=%s',
199 # public-inbox comes last as a "default"; it has a nice error page
200 # pointing to other redirectors, even if it doesn't have what
201 # you're looking for directly.
202 'https://public-inbox.org/git/%s',
203 ]:
204 alt_url = url_template % message_id
205 if args['debug']:
206 print('Probing archive for message at: %s' % alt_url)
207 try:
208 urllib.request.urlopen(alt_url)
209 except urllib.error.HTTPError as e:
210 # Skip all HTTP errors. We can expect 404 for archives that
211 # don't have this MessageId, or 300 for public-inbox ("not
212 # found, but try these other redirects"). It's less clear what
213 # to do with transitory (or is it permanent?) server failures.
214 if args['debug']:
215 print('Skipping URL %s, error: %s' % (alt_url, e))
216 continue
217 # Success!
218 if args['debug']:
219 print('Found at %s' % alt_url)
220 break
221 else:
222 errprint(
223 "WARNING: couldn't find working MessageId URL; "
224 'defaulting to "%s"' % alt_url)
225 args['source_line'] += '\n(also found at %s)' % alt_url
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800226
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700227 # Auto-snarf the Change-Id if it was encoded into the Message-Id.
228 mo = re.match(r'.*(I[a-f0-9]{40})@changeid$', message_id)
229 if mo and args['changeid'] is None:
230 args['changeid'] = mo.group(1)
231
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800232 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800233 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800234
Douglas Andersona2e91c42020-08-21 08:46:09 -0700235 return _git_returncode(['am', '-3'], stdin=patch_contents, 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/')
Douglas Anderson297a3062020-09-09 12:47:09 -0700261 try:
262 res = rpc.patch_list({'msgid': msgid})
263 except ssl.SSLCertVerificationError:
264 errprint('Error: server "%s" gave an SSL error, skipping' % url)
265 continue
Stephen Boydb68c17a2019-09-26 15:08:02 -0700266 if res:
267 patch_id = res[0]['id']
268 break
269 else:
270 errprint('Error: could not find patch based on message id')
271 sys.exit(1)
272
273 return _pick_patchwork(url, patch_id, args)
274
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700275def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800276 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700277 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800278
Brian Norris8043cfd2020-03-19 11:46:16 -0700279 # Confirm an upstream remote is setup.
280 remote = _find_upstream_remote(urls)
281 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800282 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800283 sys.exit(1)
284
Brian Norris8043cfd2020-03-19 11:46:16 -0700285 remote_ref = '%s/master' % remote
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800286 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700287 _git(['merge-base', '--is-ancestor', commit, remote_ref])
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800288 except subprocess.CalledProcessError:
Brian Norris8043cfd2020-03-19 11:46:16 -0700289 errprint('Error: Commit not in %s' % remote_ref)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800290 sys.exit(1)
291
292 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800293 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800294 args['source_line'] = ('(cherry picked from commit %s)' %
295 (commit))
296 if args['tag'] is None:
297 args['tag'] = 'UPSTREAM: '
298
299 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800300 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800301
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800302 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800303
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700304def _match_upstream(match, args):
305 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700306 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700307 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700308
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800309def _match_fromgit(match, args):
310 """Match location: git://remote/branch/HASH."""
311 remote = match.group(2)
312 branch = match.group(3)
313 commit = match.group(4)
314
315 if args['debug']:
316 print('_match_fromgit: remote=%s branch=%s commit=%s' %
317 (remote, branch, commit))
318
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800319 try:
320 _git(['merge-base', '--is-ancestor', commit,
321 '%s/%s' % (remote, branch)])
322 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800323 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800324 sys.exit(1)
325
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800326 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800327
328 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800329 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800330 args['source_line'] = (
331 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800332 if args['tag'] is None:
333 args['tag'] = 'FROMGIT: '
334
335 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800336 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800337
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800338 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800339
340def _match_gitfetch(match, args):
341 """Match location: (git|https)://repoURL#branch/HASH."""
342 remote = match.group(1)
343 branch = match.group(3)
344 commit = match.group(4)
345
346 if args['debug']:
347 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
348 (remote, branch, commit))
349
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800350 try:
351 _git(['fetch', remote, branch])
352 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800353 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800354 sys.exit(1)
355
356 url = remote
357
358 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800359 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800360 args['source_line'] = (
361 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800362 if args['tag'] is None:
363 args['tag'] = 'FROMGIT: '
364
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800365 if args['replace']:
366 _git(['reset', '--hard', 'HEAD~1'])
367
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800368 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800369
Stephen Boyd96396032020-02-25 10:12:59 -0800370def _match_gitweb(match, args):
371 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
372 remote = match.group(1)
373 branch = match.group(2)
374 commit = match.group(3)
375
376 if args['debug']:
377 print('_match_gitweb: remote=%s branch=%s commit=%s' %
378 (remote, branch, commit))
379
380 try:
381 _git(['fetch', remote, branch])
382 except subprocess.CalledProcessError:
383 errprint('Error: Branch not in %s' % remote)
384 sys.exit(1)
385
386 url = remote
387
388 if args['source_line'] is None:
389 commit = _git(['rev-parse', commit])
390 args['source_line'] = (
391 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
392 if args['tag'] is None:
393 args['tag'] = 'FROMGIT: '
394
395 if args['replace']:
396 _git(['reset', '--hard', 'HEAD~1'])
397
398 return _git_returncode(['cherry-pick', commit])
399
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800400def main(args):
401 """This is the main entrypoint for fromupstream.
402
403 Args:
404 args: sys.argv[1:]
405
406 Returns:
407 An int return code.
408 """
409 parser = argparse.ArgumentParser()
410
411 parser.add_argument('--bug', '-b',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700412 type=str, help='BUG= line')
Brian Norris6bcfa392020-08-20 10:38:05 -0700413 parser.add_argument('--test', '-t', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700414 type=str, help='TEST= line')
Stephen Boyd24b309b2018-11-06 22:11:00 -0800415 parser.add_argument('--crbug', action='append',
416 type=int, help='BUG=chromium: line')
417 parser.add_argument('--buganizer', action='append',
418 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800419 parser.add_argument('--changeid', '-c',
420 help='Overrides the gerrit generated Change-Id line')
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800421 parser.add_argument('--cqdepend',
422 type=str, help='Cq-Depend: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800423
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800424 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800425 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800426 help='Replaces the HEAD commit with this one, taking '
427 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800428 'updating commits.')
429 parser.add_argument('--nosignoff',
430 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800431 parser.add_argument('--debug', '-d', action='store_true',
432 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800433
434 parser.add_argument('--tag',
435 help='Overrides the tag from the title')
436 parser.add_argument('--source', '-s',
437 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800438 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800439 '(am from http://....)')
440 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700441 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800442 help='Patchwork ID (pw://### or pw://PROJECT/###, '
443 'where PROJECT is defined in ~/.pwclientrc; if no '
444 'PROJECT is specified, the default is retrieved from '
445 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700446 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700447 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700448 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800449 'git reference like git://remote/branch/HASH or '
450 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800451 'https://repoURL#branch/HASH or '
452 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800453
454 args = vars(parser.parse_args(args))
455
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800456 cq_depends = [args['cqdepend']] if args['cqdepend'] else []
457
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800458 bug_lines = []
459 if args['bug']:
460 # un-wrap intentionally
461 bug_lines += [args['bug']]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800462 if args['buganizer']:
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800463 buganizers = ', '.join('b:%d' % x for x in args['buganizer'])
Brian Norris00148182020-08-20 10:46:51 -0700464 bug_lines += [x.strip(' ,') for x in
465 _wrap_commit_line('BUG=', buganizers).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800466 if args['crbug']:
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800467 crbugs = ', '.join('chromium:%d' % x for x in args['crbug'])
Brian Norris00148182020-08-20 10:46:51 -0700468 bug_lines += [x.strip(' ,') for x in
469 _wrap_commit_line('BUG=', crbugs).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800470
Brian Norris6bcfa392020-08-20 10:38:05 -0700471 test_lines = [_wrap_commit_line('TEST=', x) for x in args['test']]
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800472
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800473 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800474 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800475
476 # It is possible that multiple Change-Ids are in the commit message
477 # (due to cherry picking). We only want to pull out the first one.
478 changeid_match = re.search('^Change-Id: (.*)$',
479 old_commit_message, re.MULTILINE)
Tzung-Bi Shih5fd0fd52020-08-13 11:06:33 +0800480 if args['changeid'] is None and changeid_match:
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800481 args['changeid'] = changeid_match.group(1)
482
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800483 if not cq_depends:
484 cq_depends = re.findall(r'^Cq-Depend:\s+(.*)$',
485 old_commit_message, re.MULTILINE)
Tzung-Bi Shihdfe82002020-08-13 11:00:56 +0800486
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800487 if not bug_lines:
488 bug_lines = re.findall(r'^BUG=(.*)$',
489 old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800490
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800491 if not test_lines:
492 # Note: use (?=...) to avoid to consume the source string
493 test_lines = re.findall(r"""
494 ^TEST=(.*?) # Match start from TEST= until
495 \n # (to remove the tailing newlines)
496 (?=^$| # a blank line
497 ^Cq-Depend:| # or Cq-Depend:
498 ^Change-Id:| # or Change-Id:
499 ^BUG=| # or following BUG=
500 ^TEST=) # or another TEST=
501 """,
502 old_commit_message, re.MULTILINE | re.DOTALL | re.VERBOSE)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800503
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800504 if not bug_lines or not test_lines:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800505 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800506 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700507
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800508 if args['debug']:
509 pprint.pprint(args)
510
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800511 re_matches = (
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800512 (re.compile(r'^pw://(([^/]+)/)?(\d+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700513 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700514 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
515 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800516 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800517 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800518 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800519 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800520 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800521
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800522 for location in args['locations']:
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800523 if args['debug']:
524 print('location=%s' % location)
525
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800526 for reg, handler in re_matches:
527 match = reg.match(location)
528 if match:
529 ret = handler(match, args)
530 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800531 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800532 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800533 sys.exit(1)
534
535 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700536 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700537 if args['tag'] == 'UPSTREAM: ':
538 args['tag'] = 'BACKPORT: '
539 else:
540 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700541 _pause_for_merge(conflicts)
542 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700543 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800544
545 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800546 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800547
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700548 # Remove stray Change-Id, most likely from merge resolution
549 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
550
Brian Norris7a41b982018-06-01 10:28:29 -0700551 # Note the source location before tagging anything else
552 commit_message += '\n' + args['source_line']
553
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800554 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
555 # next commands know where to work on
556 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700557 commit_message += conflicts
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800558 commit_message += '\n'
559 commit_message += '\n'.join('BUG=%s' % bug for bug in bug_lines)
560 commit_message += '\n'
561 commit_message += '\n'.join('TEST=%s' % t for t in test_lines)
Brian Norris674209e2020-04-22 15:33:53 -0700562
563 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800564 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700565 signoff = 'Signed-off-by: %s <%s>' % (
566 _git(['config', 'user.name']),
567 _git(['config', 'user.email']))
568 if not signoff in commit_message.splitlines():
569 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800570 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800571
572 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800573 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800574
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700575 # If we see a "Link: " that seems to point to a Message-Id with an
576 # automatic Change-Id we'll snarf it out.
577 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
578 re.MULTILINE)
579 if mo and args['changeid'] is None:
580 args['changeid'] = mo.group(1)
581
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800582 # replace changeid if needed
583 if args['changeid'] is not None:
584 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
585 args['changeid'], commit_message)
586 args['changeid'] = None
587
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800588 if cq_depends:
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800589 commit_message = re.sub(
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800590 r'(Change-Id: \w+)',
591 r'%s\n\1' % '\n'.join('Cq-Depend: %s' % c for c in cq_depends),
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800592 commit_message)
593
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800594 # decorate it that it's from outside
595 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800596
597 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800598 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800599
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900600 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800601
602if __name__ == '__main__':
603 sys.exit(main(sys.argv[1:]))