blob: f8e7bf54ee1fe3df61a337823fdea7b476699d7c [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-Subedi5ce64192020-11-02 16:10:17 -080028# Note: Do not include trailing / in any of these
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070029UPSTREAM_URLS = (
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080030 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
31 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
32 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070033 'git://w1.fi/srv/git/hostap.git',
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070034 'git://git.kernel.org/pub/scm/bluetooth/bluez.git',
Douglas Anderson482a6d62020-09-21 09:31:54 -070035 'https://github.com/andersson/qrtr.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070036)
37
Stephen Boydb68c17a2019-09-26 15:08:02 -070038PATCHWORK_URLS = (
39 'https://lore.kernel.org/patchwork',
40 'https://patchwork.kernel.org',
41 'https://patchwork.ozlabs.org',
42 'https://patchwork.freedesktop.org',
43 'https://patchwork.linux-mips.org',
44)
45
Harry Cuttsae372f32019-02-12 18:01:14 -080046COMMIT_MESSAGE_WIDTH = 75
47
Brian Norris9f8a2be2018-06-01 11:14:08 -070048_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
49
Alexandru M Stan725c71f2019-12-11 16:53:33 -080050def _git(args, stdin=None, encoding='utf-8'):
51 """Calls a git subcommand.
52
53 Similar to subprocess.check_output.
54
55 Args:
Brian Norris6baeb2e2020-03-18 12:13:30 -070056 args: subcommand + args passed to 'git'.
Alexandru M Stan725c71f2019-12-11 16:53:33 -080057 stdin: a string or bytes (depending on encoding) that will be passed
58 to the git subcommand.
59 encoding: either 'utf-8' (default) or None. Override it to None if
60 you want both stdin and stdout to be raw bytes.
61
62 Returns:
63 the stdout of the git subcommand, same type as stdin. The output is
64 also run through strip to make sure there's no extra whitespace.
65
66 Raises:
67 subprocess.CalledProcessError: when return code is not zero.
68 The exception has a .returncode attribute.
69 """
70 return subprocess.run(
71 ['git'] + args,
72 encoding=encoding,
73 input=stdin,
74 stdout=subprocess.PIPE,
75 check=True,
76 ).stdout.strip()
77
78def _git_returncode(*args, **kwargs):
79 """Same as _git, but return returncode instead of stdout.
80
81 Similar to subprocess.call.
82
83 Never raises subprocess.CalledProcessError.
84 """
85 try:
86 _git(*args, **kwargs)
87 return 0
88 except subprocess.CalledProcessError as e:
89 return e.returncode
90
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070091def _get_conflicts():
92 """Report conflicting files."""
93 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
94 conflicts = []
Alexandru M Stan725c71f2019-12-11 16:53:33 -080095 output = _git(['status', '--porcelain', '--untracked-files=no'])
96 for line in output.splitlines():
Douglas Anderson46287f92018-04-30 09:58:24 -070097 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070098 continue
Douglas Anderson46287f92018-04-30 09:58:24 -070099 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700100 if resolution in resolutions:
101 conflicts.append(' ' + name)
102 if not conflicts:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700103 return ''
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700104 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
105
Brian Norris8043cfd2020-03-19 11:46:16 -0700106def _find_upstream_remote(urls):
107 """Find a remote pointing to an upstream repository."""
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800108 for remote in _git(['remote']).splitlines():
109 try:
Abhishek Pandit-Subedi5ce64192020-11-02 16:10:17 -0800110 if _git(['remote', 'get-url', remote]).rstrip('/') in urls:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800111 return remote
112 except subprocess.CalledProcessError:
113 # Kinda weird, get-url failing on an item that git just gave us.
114 continue
Guenter Roeckd66daa72018-04-19 10:31:25 -0700115 return None
116
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700117def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800118 """Pause and go in the background till user resolves the conflicts."""
119
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800120 git_root = _git(['rev-parse', '--show-toplevel'])
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800121 previous_head_hash = _git(['rev-parse', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800122
123 paths = (
124 os.path.join(git_root, '.git', 'rebase-apply'),
125 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
126 )
127 for path in paths:
128 if os.path.exists(path):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800129 errprint('Found "%s".' % path)
130 errprint(conflicts)
131 errprint('Please resolve the conflicts and restart the '
132 'shell job when done. Kill this job if you '
133 'aborted the conflict.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800134 os.kill(os.getpid(), signal.SIGTSTP)
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800135
136 # Check the conflicts actually got resolved. Otherwise we'll end up
137 # modifying the wrong commit message and probably confusing people.
138 while previous_head_hash == _git(['rev-parse', 'HEAD']):
139 errprint('Error: no new commit has been made. Did you forget to run '
140 '`git am --continue` or `git cherry-pick --continue`?')
141 errprint('Please create a new commit and restart the shell job (or kill'
142 ' it if you aborted the conflict).')
143 os.kill(os.getpid(), signal.SIGTSTP)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800144
Brian Norris9f8a2be2018-06-01 11:14:08 -0700145def _get_pw_url(project):
146 """Retrieve the patchwork server URL from .pwclientrc.
147
Mike Frysingerf80ca212018-07-13 15:02:52 -0400148 Args:
149 project: patchwork project name; if None, we retrieve the default
150 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -0700151 """
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800152 config = configparser.ConfigParser()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700153 config.read([_PWCLIENTRC])
154
155 if project is None:
156 try:
157 project = config.get('options', 'default')
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800158 except (configparser.NoSectionError, configparser.NoOptionError) as e:
159 errprint('Error: no default patchwork project found in %s. (%r)'
160 % (_PWCLIENTRC, e))
Brian Norris9f8a2be2018-06-01 11:14:08 -0700161 sys.exit(1)
162
163 if not config.has_option(project, 'url'):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800164 errprint("Error: patchwork URL not found for project '%s'" % project)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700165 sys.exit(1)
166
167 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700168 # Strip trailing 'xmlrpc' and/or trailing slash.
169 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700170
Harry Cuttsae372f32019-02-12 18:01:14 -0800171def _wrap_commit_line(prefix, content):
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800172 line = prefix + content
173 indent = ' ' * len(prefix)
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800174
175 ret = textwrap.fill(line, COMMIT_MESSAGE_WIDTH, subsequent_indent=indent)
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800176 return ret[len(prefix):]
Harry Cuttsae372f32019-02-12 18:01:14 -0800177
Stephen Boydb68c17a2019-09-26 15:08:02 -0700178def _pick_patchwork(url, patch_id, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800179 if args['tag'] is None:
180 args['tag'] = 'FROMLIST: '
181
Brian Norris8553f032020-03-18 11:59:02 -0700182 try:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800183 opener = urllib.request.urlopen('%s/patch/%s/mbox' % (url, patch_id))
Brian Norris8553f032020-03-18 11:59:02 -0700184 except urllib.error.HTTPError as e:
185 errprint('Error: could not download patch: %s' % e)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800186 sys.exit(1)
187 patch_contents = opener.read()
188
189 if not patch_contents:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800190 errprint('Error: No patch content found')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800191 sys.exit(1)
192
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700193 message_id = mailbox.Message(patch_contents)['Message-Id']
194 message_id = re.sub('^<|>$', '', message_id.strip())
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800195 if args['source_line'] is None:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800196 args['source_line'] = '(am from %s/patch/%s/)' % (url, patch_id)
Brian Norris8553f032020-03-18 11:59:02 -0700197 for url_template in [
Brian Norris655b5ce2020-05-08 11:37:38 -0700198 'https://lore.kernel.org/r/%s',
Brian Norris8553f032020-03-18 11:59:02 -0700199 # hostap project (and others) are here, but not kernel.org.
200 'https://marc.info/?i=%s',
201 # public-inbox comes last as a "default"; it has a nice error page
202 # pointing to other redirectors, even if it doesn't have what
203 # you're looking for directly.
204 'https://public-inbox.org/git/%s',
205 ]:
206 alt_url = url_template % message_id
207 if args['debug']:
208 print('Probing archive for message at: %s' % alt_url)
209 try:
210 urllib.request.urlopen(alt_url)
211 except urllib.error.HTTPError as e:
212 # Skip all HTTP errors. We can expect 404 for archives that
213 # don't have this MessageId, or 300 for public-inbox ("not
214 # found, but try these other redirects"). It's less clear what
215 # to do with transitory (or is it permanent?) server failures.
216 if args['debug']:
217 print('Skipping URL %s, error: %s' % (alt_url, e))
218 continue
219 # Success!
220 if args['debug']:
221 print('Found at %s' % alt_url)
222 break
223 else:
224 errprint(
225 "WARNING: couldn't find working MessageId URL; "
226 'defaulting to "%s"' % alt_url)
227 args['source_line'] += '\n(also found at %s)' % alt_url
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800228
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700229 # Auto-snarf the Change-Id if it was encoded into the Message-Id.
230 mo = re.match(r'.*(I[a-f0-9]{40})@changeid$', message_id)
231 if mo and args['changeid'] is None:
232 args['changeid'] = mo.group(1)
233
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800234 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800235 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800236
Douglas Andersona2e91c42020-08-21 08:46:09 -0700237 return _git_returncode(['am', '-3'], stdin=patch_contents, encoding=None)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800238
Stephen Boydb68c17a2019-09-26 15:08:02 -0700239def _match_patchwork(match, args):
240 """Match location: pw://### or pw://PROJECT/###."""
241 pw_project = match.group(2)
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800242 patch_id = match.group(3)
Stephen Boydb68c17a2019-09-26 15:08:02 -0700243
244 if args['debug']:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800245 print('_match_patchwork: pw_project=%s, patch_id=%s' %
Stephen Boydb68c17a2019-09-26 15:08:02 -0700246 (pw_project, patch_id))
247
248 url = _get_pw_url(pw_project)
249 return _pick_patchwork(url, patch_id, args)
250
251def _match_msgid(match, args):
252 """Match location: msgid://MSGID."""
253 msgid = match.group(1)
254
255 if args['debug']:
256 print('_match_msgid: message_id=%s' % (msgid))
257
258 # Patchwork requires the brackets so force it
259 msgid = '<' + msgid + '>'
260 url = None
261 for url in PATCHWORK_URLS:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800262 rpc = xmlrpc.client.ServerProxy(url + '/xmlrpc/')
Douglas Anderson297a3062020-09-09 12:47:09 -0700263 try:
264 res = rpc.patch_list({'msgid': msgid})
265 except ssl.SSLCertVerificationError:
266 errprint('Error: server "%s" gave an SSL error, skipping' % url)
267 continue
Stephen Boydb68c17a2019-09-26 15:08:02 -0700268 if res:
269 patch_id = res[0]['id']
270 break
271 else:
272 errprint('Error: could not find patch based on message id')
273 sys.exit(1)
274
275 return _pick_patchwork(url, patch_id, args)
276
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700277def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800278 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700279 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800280
Brian Norris8043cfd2020-03-19 11:46:16 -0700281 # Confirm an upstream remote is setup.
282 remote = _find_upstream_remote(urls)
283 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800284 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800285 sys.exit(1)
286
Brian Norris8043cfd2020-03-19 11:46:16 -0700287 remote_ref = '%s/master' % remote
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800288 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700289 _git(['merge-base', '--is-ancestor', commit, remote_ref])
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800290 except subprocess.CalledProcessError:
Brian Norris8043cfd2020-03-19 11:46:16 -0700291 errprint('Error: Commit not in %s' % remote_ref)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800292 sys.exit(1)
293
294 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800295 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800296 args['source_line'] = ('(cherry picked from commit %s)' %
297 (commit))
298 if args['tag'] is None:
299 args['tag'] = 'UPSTREAM: '
300
301 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800302 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800303
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800304 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800305
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700306def _match_upstream(match, args):
307 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700308 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700309 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700310
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800311def _match_fromgit(match, args):
312 """Match location: git://remote/branch/HASH."""
313 remote = match.group(2)
314 branch = match.group(3)
315 commit = match.group(4)
316
317 if args['debug']:
318 print('_match_fromgit: remote=%s branch=%s commit=%s' %
319 (remote, branch, commit))
320
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800321 try:
322 _git(['merge-base', '--is-ancestor', commit,
323 '%s/%s' % (remote, branch)])
324 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800325 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800326 sys.exit(1)
327
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800328 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800329
330 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800331 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800332 args['source_line'] = (
333 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800334 if args['tag'] is None:
335 args['tag'] = 'FROMGIT: '
336
337 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800338 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800339
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800340 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800341
342def _match_gitfetch(match, args):
343 """Match location: (git|https)://repoURL#branch/HASH."""
344 remote = match.group(1)
345 branch = match.group(3)
346 commit = match.group(4)
347
348 if args['debug']:
349 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
350 (remote, branch, commit))
351
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800352 try:
353 _git(['fetch', remote, branch])
354 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800355 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800356 sys.exit(1)
357
358 url = remote
359
360 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800361 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800362 args['source_line'] = (
363 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800364 if args['tag'] is None:
365 args['tag'] = 'FROMGIT: '
366
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800367 if args['replace']:
368 _git(['reset', '--hard', 'HEAD~1'])
369
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800370 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800371
Stephen Boyd96396032020-02-25 10:12:59 -0800372def _match_gitweb(match, args):
373 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
374 remote = match.group(1)
375 branch = match.group(2)
376 commit = match.group(3)
377
378 if args['debug']:
379 print('_match_gitweb: remote=%s branch=%s commit=%s' %
380 (remote, branch, commit))
381
382 try:
383 _git(['fetch', remote, branch])
384 except subprocess.CalledProcessError:
385 errprint('Error: Branch not in %s' % remote)
386 sys.exit(1)
387
388 url = remote
389
390 if args['source_line'] is None:
391 commit = _git(['rev-parse', commit])
392 args['source_line'] = (
393 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
394 if args['tag'] is None:
395 args['tag'] = 'FROMGIT: '
396
397 if args['replace']:
398 _git(['reset', '--hard', 'HEAD~1'])
399
400 return _git_returncode(['cherry-pick', commit])
401
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800402def main(args):
403 """This is the main entrypoint for fromupstream.
404
405 Args:
406 args: sys.argv[1:]
407
408 Returns:
409 An int return code.
410 """
411 parser = argparse.ArgumentParser()
412
413 parser.add_argument('--bug', '-b',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700414 type=str, help='BUG= line')
Brian Norris6bcfa392020-08-20 10:38:05 -0700415 parser.add_argument('--test', '-t', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700416 type=str, help='TEST= line')
Stephen Boyd24b309b2018-11-06 22:11:00 -0800417 parser.add_argument('--crbug', action='append',
418 type=int, help='BUG=chromium: line')
419 parser.add_argument('--buganizer', action='append',
420 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800421 parser.add_argument('--changeid', '-c',
422 help='Overrides the gerrit generated Change-Id line')
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800423 parser.add_argument('--cqdepend',
424 type=str, help='Cq-Depend: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800425
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800426 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800427 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800428 help='Replaces the HEAD commit with this one, taking '
429 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800430 'updating commits.')
431 parser.add_argument('--nosignoff',
432 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800433 parser.add_argument('--debug', '-d', action='store_true',
434 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800435
436 parser.add_argument('--tag',
437 help='Overrides the tag from the title')
438 parser.add_argument('--source', '-s',
439 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800440 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800441 '(am from http://....)')
442 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700443 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800444 help='Patchwork ID (pw://### or pw://PROJECT/###, '
445 'where PROJECT is defined in ~/.pwclientrc; if no '
446 'PROJECT is specified, the default is retrieved from '
447 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700448 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700449 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700450 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800451 'git reference like git://remote/branch/HASH or '
452 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800453 'https://repoURL#branch/HASH or '
454 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800455
456 args = vars(parser.parse_args(args))
457
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800458 cq_depends = [args['cqdepend']] if args['cqdepend'] else []
459
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800460 bug_lines = []
461 if args['bug']:
462 # un-wrap intentionally
463 bug_lines += [args['bug']]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800464 if args['buganizer']:
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800465 buganizers = ', '.join('b:%d' % x for x in args['buganizer'])
Brian Norris00148182020-08-20 10:46:51 -0700466 bug_lines += [x.strip(' ,') for x in
467 _wrap_commit_line('BUG=', buganizers).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800468 if args['crbug']:
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800469 crbugs = ', '.join('chromium:%d' % x for x in args['crbug'])
Brian Norris00148182020-08-20 10:46:51 -0700470 bug_lines += [x.strip(' ,') for x in
471 _wrap_commit_line('BUG=', crbugs).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800472
Brian Norris6bcfa392020-08-20 10:38:05 -0700473 test_lines = [_wrap_commit_line('TEST=', x) for x in args['test']]
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800474
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800475 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800476 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800477
478 # It is possible that multiple Change-Ids are in the commit message
479 # (due to cherry picking). We only want to pull out the first one.
480 changeid_match = re.search('^Change-Id: (.*)$',
481 old_commit_message, re.MULTILINE)
Tzung-Bi Shih5fd0fd52020-08-13 11:06:33 +0800482 if args['changeid'] is None and changeid_match:
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800483 args['changeid'] = changeid_match.group(1)
484
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800485 if not cq_depends:
486 cq_depends = re.findall(r'^Cq-Depend:\s+(.*)$',
487 old_commit_message, re.MULTILINE)
Tzung-Bi Shihdfe82002020-08-13 11:00:56 +0800488
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800489 if not bug_lines:
490 bug_lines = re.findall(r'^BUG=(.*)$',
491 old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800492
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800493 if not test_lines:
494 # Note: use (?=...) to avoid to consume the source string
495 test_lines = re.findall(r"""
496 ^TEST=(.*?) # Match start from TEST= until
497 \n # (to remove the tailing newlines)
498 (?=^$| # a blank line
499 ^Cq-Depend:| # or Cq-Depend:
500 ^Change-Id:| # or Change-Id:
501 ^BUG=| # or following BUG=
502 ^TEST=) # or another TEST=
503 """,
504 old_commit_message, re.MULTILINE | re.DOTALL | re.VERBOSE)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800505
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800506 if not bug_lines or not test_lines:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800507 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800508 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700509
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800510 if args['debug']:
511 pprint.pprint(args)
512
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800513 re_matches = (
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800514 (re.compile(r'^pw://(([^/]+)/)?(.+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700515 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700516 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
517 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800518 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800519 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800520 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800521 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800522 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800523
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100524 # Backup user provided parameters
525 user_source_line = args['source_line']
526 user_tag = args['tag']
527 user_changeid = args['changeid']
528
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800529 for location in args['locations']:
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100530 # Restore user parameters
531 args['source_line'] = user_source_line
532 args['tag'] = user_tag
533 args['changeid'] = user_changeid
534
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800535 if args['debug']:
536 print('location=%s' % location)
537
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800538 for reg, handler in re_matches:
539 match = reg.match(location)
540 if match:
541 ret = handler(match, args)
542 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800543 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800544 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800545 sys.exit(1)
546
547 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700548 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700549 if args['tag'] == 'UPSTREAM: ':
550 args['tag'] = 'BACKPORT: '
551 else:
552 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700553 _pause_for_merge(conflicts)
554 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700555 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800556
557 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800558 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800559
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700560 # Remove stray Change-Id, most likely from merge resolution
561 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
562
Brian Norris7a41b982018-06-01 10:28:29 -0700563 # Note the source location before tagging anything else
564 commit_message += '\n' + args['source_line']
565
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800566 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
567 # next commands know where to work on
568 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700569 commit_message += conflicts
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800570 commit_message += '\n'
571 commit_message += '\n'.join('BUG=%s' % bug for bug in bug_lines)
572 commit_message += '\n'
573 commit_message += '\n'.join('TEST=%s' % t for t in test_lines)
Brian Norris674209e2020-04-22 15:33:53 -0700574
575 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800576 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700577 signoff = 'Signed-off-by: %s <%s>' % (
578 _git(['config', 'user.name']),
579 _git(['config', 'user.email']))
580 if not signoff in commit_message.splitlines():
581 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800582 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800583
584 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800585 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800586
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700587 # If we see a "Link: " that seems to point to a Message-Id with an
588 # automatic Change-Id we'll snarf it out.
589 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
590 re.MULTILINE)
591 if mo and args['changeid'] is None:
592 args['changeid'] = mo.group(1)
593
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800594 # replace changeid if needed
595 if args['changeid'] is not None:
596 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
597 args['changeid'], commit_message)
598 args['changeid'] = None
599
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800600 if cq_depends:
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800601 commit_message = re.sub(
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800602 r'(Change-Id: \w+)',
603 r'%s\n\1' % '\n'.join('Cq-Depend: %s' % c for c in cq_depends),
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800604 commit_message)
605
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800606 # decorate it that it's from outside
607 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800608
609 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800610 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800611
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900612 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800613
614if __name__ == '__main__':
615 sys.exit(main(sys.argv[1:]))