blob: d48d436fb864ec875246d3a654202c103a9c4de0 [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 = (
Douglas Andersoncebcefd2020-09-24 10:37:36 -070030 # Acceptable Linux URLs
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080031 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
32 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
33 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
Douglas Andersoncebcefd2020-09-24 10:37:36 -070034
35 # Acceptible Linux Firmware URLs
36 'git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
37 'https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
38 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
39
40 # Upstream for various other projects
Brian Norris8043cfd2020-03-19 11:46:16 -070041 'git://w1.fi/srv/git/hostap.git',
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070042 'git://git.kernel.org/pub/scm/bluetooth/bluez.git',
Douglas Anderson482a6d62020-09-21 09:31:54 -070043 'https://github.com/andersson/qrtr.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070044)
45
Stephen Boydb68c17a2019-09-26 15:08:02 -070046PATCHWORK_URLS = (
47 'https://lore.kernel.org/patchwork',
48 'https://patchwork.kernel.org',
49 'https://patchwork.ozlabs.org',
50 'https://patchwork.freedesktop.org',
51 'https://patchwork.linux-mips.org',
52)
53
Harry Cuttsae372f32019-02-12 18:01:14 -080054COMMIT_MESSAGE_WIDTH = 75
55
Brian Norris9f8a2be2018-06-01 11:14:08 -070056_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
57
Douglas Andersoncebcefd2020-09-24 10:37:36 -070058def _git(args, stdin=None, encoding='utf-8', no_stderr=False):
Alexandru M Stan725c71f2019-12-11 16:53:33 -080059 """Calls a git subcommand.
60
61 Similar to subprocess.check_output.
62
63 Args:
Brian Norris6baeb2e2020-03-18 12:13:30 -070064 args: subcommand + args passed to 'git'.
Alexandru M Stan725c71f2019-12-11 16:53:33 -080065 stdin: a string or bytes (depending on encoding) that will be passed
66 to the git subcommand.
67 encoding: either 'utf-8' (default) or None. Override it to None if
68 you want both stdin and stdout to be raw bytes.
Douglas Andersoncebcefd2020-09-24 10:37:36 -070069 no_stderr: If True, we'll eat stderr
Alexandru M Stan725c71f2019-12-11 16:53:33 -080070
71 Returns:
72 the stdout of the git subcommand, same type as stdin. The output is
73 also run through strip to make sure there's no extra whitespace.
74
75 Raises:
76 subprocess.CalledProcessError: when return code is not zero.
77 The exception has a .returncode attribute.
78 """
79 return subprocess.run(
80 ['git'] + args,
81 encoding=encoding,
82 input=stdin,
83 stdout=subprocess.PIPE,
Douglas Andersoncebcefd2020-09-24 10:37:36 -070084 stderr=(subprocess.PIPE if no_stderr else None),
Alexandru M Stan725c71f2019-12-11 16:53:33 -080085 check=True,
86 ).stdout.strip()
87
88def _git_returncode(*args, **kwargs):
89 """Same as _git, but return returncode instead of stdout.
90
91 Similar to subprocess.call.
92
93 Never raises subprocess.CalledProcessError.
94 """
95 try:
96 _git(*args, **kwargs)
97 return 0
98 except subprocess.CalledProcessError as e:
99 return e.returncode
100
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700101def _get_conflicts():
102 """Report conflicting files."""
103 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
104 conflicts = []
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800105 output = _git(['status', '--porcelain', '--untracked-files=no'])
106 for line in output.splitlines():
Douglas Anderson46287f92018-04-30 09:58:24 -0700107 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700108 continue
Douglas Anderson46287f92018-04-30 09:58:24 -0700109 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700110 if resolution in resolutions:
111 conflicts.append(' ' + name)
112 if not conflicts:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700113 return ''
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700114 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
115
Brian Norris8043cfd2020-03-19 11:46:16 -0700116def _find_upstream_remote(urls):
117 """Find a remote pointing to an upstream repository."""
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800118 for remote in _git(['remote']).splitlines():
119 try:
Abhishek Pandit-Subedi5ce64192020-11-02 16:10:17 -0800120 if _git(['remote', 'get-url', remote]).rstrip('/') in urls:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800121 return remote
122 except subprocess.CalledProcessError:
123 # Kinda weird, get-url failing on an item that git just gave us.
124 continue
Guenter Roeckd66daa72018-04-19 10:31:25 -0700125 return None
126
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700127def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800128 """Pause and go in the background till user resolves the conflicts."""
129
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800130 git_root = _git(['rev-parse', '--show-toplevel'])
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800131 previous_head_hash = _git(['rev-parse', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800132
133 paths = (
134 os.path.join(git_root, '.git', 'rebase-apply'),
135 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
136 )
137 for path in paths:
138 if os.path.exists(path):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800139 errprint('Found "%s".' % path)
140 errprint(conflicts)
141 errprint('Please resolve the conflicts and restart the '
142 'shell job when done. Kill this job if you '
143 'aborted the conflict.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800144 os.kill(os.getpid(), signal.SIGTSTP)
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800145
146 # Check the conflicts actually got resolved. Otherwise we'll end up
147 # modifying the wrong commit message and probably confusing people.
148 while previous_head_hash == _git(['rev-parse', 'HEAD']):
149 errprint('Error: no new commit has been made. Did you forget to run '
150 '`git am --continue` or `git cherry-pick --continue`?')
151 errprint('Please create a new commit and restart the shell job (or kill'
152 ' it if you aborted the conflict).')
153 os.kill(os.getpid(), signal.SIGTSTP)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800154
Brian Norris9f8a2be2018-06-01 11:14:08 -0700155def _get_pw_url(project):
156 """Retrieve the patchwork server URL from .pwclientrc.
157
Mike Frysingerf80ca212018-07-13 15:02:52 -0400158 Args:
159 project: patchwork project name; if None, we retrieve the default
160 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -0700161 """
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800162 config = configparser.ConfigParser()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700163 config.read([_PWCLIENTRC])
164
165 if project is None:
166 try:
167 project = config.get('options', 'default')
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800168 except (configparser.NoSectionError, configparser.NoOptionError) as e:
169 errprint('Error: no default patchwork project found in %s. (%r)'
170 % (_PWCLIENTRC, e))
Brian Norris9f8a2be2018-06-01 11:14:08 -0700171 sys.exit(1)
172
173 if not config.has_option(project, 'url'):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800174 errprint("Error: patchwork URL not found for project '%s'" % project)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700175 sys.exit(1)
176
177 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700178 # Strip trailing 'xmlrpc' and/or trailing slash.
179 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700180
Harry Cuttsae372f32019-02-12 18:01:14 -0800181def _wrap_commit_line(prefix, content):
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800182 line = prefix + content
183 indent = ' ' * len(prefix)
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800184
185 ret = textwrap.fill(line, COMMIT_MESSAGE_WIDTH, subsequent_indent=indent)
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800186 return ret[len(prefix):]
Harry Cuttsae372f32019-02-12 18:01:14 -0800187
Stephen Boydb68c17a2019-09-26 15:08:02 -0700188def _pick_patchwork(url, patch_id, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800189 if args['tag'] is None:
190 args['tag'] = 'FROMLIST: '
191
Brian Norris8553f032020-03-18 11:59:02 -0700192 try:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800193 opener = urllib.request.urlopen('%s/patch/%s/mbox' % (url, patch_id))
Brian Norris8553f032020-03-18 11:59:02 -0700194 except urllib.error.HTTPError as e:
195 errprint('Error: could not download patch: %s' % e)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800196 sys.exit(1)
197 patch_contents = opener.read()
198
199 if not patch_contents:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800200 errprint('Error: No patch content found')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800201 sys.exit(1)
202
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700203 message_id = mailbox.Message(patch_contents)['Message-Id']
204 message_id = re.sub('^<|>$', '', message_id.strip())
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800205 if args['source_line'] is None:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800206 args['source_line'] = '(am from %s/patch/%s/)' % (url, patch_id)
Brian Norris8553f032020-03-18 11:59:02 -0700207 for url_template in [
Brian Norris655b5ce2020-05-08 11:37:38 -0700208 'https://lore.kernel.org/r/%s',
Brian Norris8553f032020-03-18 11:59:02 -0700209 # hostap project (and others) are here, but not kernel.org.
210 'https://marc.info/?i=%s',
211 # public-inbox comes last as a "default"; it has a nice error page
212 # pointing to other redirectors, even if it doesn't have what
213 # you're looking for directly.
214 'https://public-inbox.org/git/%s',
215 ]:
216 alt_url = url_template % message_id
217 if args['debug']:
218 print('Probing archive for message at: %s' % alt_url)
219 try:
220 urllib.request.urlopen(alt_url)
221 except urllib.error.HTTPError as e:
222 # Skip all HTTP errors. We can expect 404 for archives that
223 # don't have this MessageId, or 300 for public-inbox ("not
224 # found, but try these other redirects"). It's less clear what
225 # to do with transitory (or is it permanent?) server failures.
226 if args['debug']:
227 print('Skipping URL %s, error: %s' % (alt_url, e))
228 continue
229 # Success!
230 if args['debug']:
231 print('Found at %s' % alt_url)
232 break
233 else:
234 errprint(
235 "WARNING: couldn't find working MessageId URL; "
236 'defaulting to "%s"' % alt_url)
237 args['source_line'] += '\n(also found at %s)' % alt_url
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800238
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700239 # Auto-snarf the Change-Id if it was encoded into the Message-Id.
240 mo = re.match(r'.*(I[a-f0-9]{40})@changeid$', message_id)
241 if mo and args['changeid'] is None:
242 args['changeid'] = mo.group(1)
243
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800244 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800245 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800246
Douglas Andersona2e91c42020-08-21 08:46:09 -0700247 return _git_returncode(['am', '-3'], stdin=patch_contents, encoding=None)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800248
Stephen Boydb68c17a2019-09-26 15:08:02 -0700249def _match_patchwork(match, args):
250 """Match location: pw://### or pw://PROJECT/###."""
251 pw_project = match.group(2)
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800252 patch_id = match.group(3)
Stephen Boydb68c17a2019-09-26 15:08:02 -0700253
254 if args['debug']:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800255 print('_match_patchwork: pw_project=%s, patch_id=%s' %
Stephen Boydb68c17a2019-09-26 15:08:02 -0700256 (pw_project, patch_id))
257
258 url = _get_pw_url(pw_project)
259 return _pick_patchwork(url, patch_id, args)
260
261def _match_msgid(match, args):
262 """Match location: msgid://MSGID."""
263 msgid = match.group(1)
264
265 if args['debug']:
266 print('_match_msgid: message_id=%s' % (msgid))
267
268 # Patchwork requires the brackets so force it
269 msgid = '<' + msgid + '>'
270 url = None
271 for url in PATCHWORK_URLS:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800272 rpc = xmlrpc.client.ServerProxy(url + '/xmlrpc/')
Douglas Anderson297a3062020-09-09 12:47:09 -0700273 try:
274 res = rpc.patch_list({'msgid': msgid})
275 except ssl.SSLCertVerificationError:
276 errprint('Error: server "%s" gave an SSL error, skipping' % url)
277 continue
Stephen Boydb68c17a2019-09-26 15:08:02 -0700278 if res:
279 patch_id = res[0]['id']
280 break
281 else:
282 errprint('Error: could not find patch based on message id')
283 sys.exit(1)
284
285 return _pick_patchwork(url, patch_id, args)
286
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700287def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800288 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700289 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800290
Brian Norris8043cfd2020-03-19 11:46:16 -0700291 # Confirm an upstream remote is setup.
292 remote = _find_upstream_remote(urls)
293 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800294 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800295 sys.exit(1)
296
Douglas Andersoncebcefd2020-09-24 10:37:36 -0700297 branches = ['main', 'master']
298 for branch in branches:
299 remote_ref = '%s/%s' % (remote, branch)
300 try:
301 _git(['merge-base', '--is-ancestor', commit, remote_ref],
302 no_stderr=True)
303 except subprocess.CalledProcessError:
304 continue
305 break
306 else:
307 errprint('Error: Commit not in %s, branches: %s' % (
308 remote, ', '.join(branches)))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800309 sys.exit(1)
310
311 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800312 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800313 args['source_line'] = ('(cherry picked from commit %s)' %
314 (commit))
315 if args['tag'] is None:
316 args['tag'] = 'UPSTREAM: '
317
318 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800319 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800320
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800321 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800322
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700323def _match_upstream(match, args):
324 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700325 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700326 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700327
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800328def _match_fromgit(match, args):
329 """Match location: git://remote/branch/HASH."""
330 remote = match.group(2)
331 branch = match.group(3)
332 commit = match.group(4)
333
334 if args['debug']:
335 print('_match_fromgit: remote=%s branch=%s commit=%s' %
336 (remote, branch, commit))
337
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800338 try:
339 _git(['merge-base', '--is-ancestor', commit,
340 '%s/%s' % (remote, branch)])
341 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800342 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800343 sys.exit(1)
344
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800345 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800346
347 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800348 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800349 args['source_line'] = (
350 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800351 if args['tag'] is None:
352 args['tag'] = 'FROMGIT: '
353
354 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800355 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800356
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800357 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800358
359def _match_gitfetch(match, args):
360 """Match location: (git|https)://repoURL#branch/HASH."""
361 remote = match.group(1)
362 branch = match.group(3)
363 commit = match.group(4)
364
365 if args['debug']:
366 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
367 (remote, branch, commit))
368
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800369 try:
370 _git(['fetch', remote, branch])
371 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800372 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800373 sys.exit(1)
374
375 url = remote
376
377 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800378 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800379 args['source_line'] = (
380 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800381 if args['tag'] is None:
382 args['tag'] = 'FROMGIT: '
383
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800384 if args['replace']:
385 _git(['reset', '--hard', 'HEAD~1'])
386
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800387 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800388
Stephen Boyd96396032020-02-25 10:12:59 -0800389def _match_gitweb(match, args):
390 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
391 remote = match.group(1)
392 branch = match.group(2)
393 commit = match.group(3)
394
395 if args['debug']:
396 print('_match_gitweb: remote=%s branch=%s commit=%s' %
397 (remote, branch, commit))
398
399 try:
400 _git(['fetch', remote, branch])
401 except subprocess.CalledProcessError:
402 errprint('Error: Branch not in %s' % remote)
403 sys.exit(1)
404
405 url = remote
406
407 if args['source_line'] is None:
408 commit = _git(['rev-parse', commit])
409 args['source_line'] = (
410 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
411 if args['tag'] is None:
412 args['tag'] = 'FROMGIT: '
413
414 if args['replace']:
415 _git(['reset', '--hard', 'HEAD~1'])
416
417 return _git_returncode(['cherry-pick', commit])
418
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800419def main(args):
420 """This is the main entrypoint for fromupstream.
421
422 Args:
423 args: sys.argv[1:]
424
425 Returns:
426 An int return code.
427 """
428 parser = argparse.ArgumentParser()
429
430 parser.add_argument('--bug', '-b',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700431 type=str, help='BUG= line')
Brian Norris6bcfa392020-08-20 10:38:05 -0700432 parser.add_argument('--test', '-t', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700433 type=str, help='TEST= line')
Stephen Boyd24b309b2018-11-06 22:11:00 -0800434 parser.add_argument('--crbug', action='append',
435 type=int, help='BUG=chromium: line')
436 parser.add_argument('--buganizer', action='append',
437 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800438 parser.add_argument('--changeid', '-c',
439 help='Overrides the gerrit generated Change-Id line')
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800440 parser.add_argument('--cqdepend',
441 type=str, help='Cq-Depend: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800442
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800443 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800444 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800445 help='Replaces the HEAD commit with this one, taking '
446 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800447 'updating commits.')
448 parser.add_argument('--nosignoff',
449 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800450 parser.add_argument('--debug', '-d', action='store_true',
451 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800452
453 parser.add_argument('--tag',
454 help='Overrides the tag from the title')
455 parser.add_argument('--source', '-s',
456 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800457 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800458 '(am from http://....)')
459 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700460 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800461 help='Patchwork ID (pw://### or pw://PROJECT/###, '
462 'where PROJECT is defined in ~/.pwclientrc; if no '
463 'PROJECT is specified, the default is retrieved from '
464 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700465 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700466 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700467 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800468 'git reference like git://remote/branch/HASH or '
469 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800470 'https://repoURL#branch/HASH or '
471 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800472
473 args = vars(parser.parse_args(args))
474
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800475 cq_depends = [args['cqdepend']] if args['cqdepend'] else []
476
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800477 bug_lines = []
478 if args['bug']:
479 # un-wrap intentionally
480 bug_lines += [args['bug']]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800481 if args['buganizer']:
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800482 buganizers = ', '.join('b:%d' % x for x in args['buganizer'])
Brian Norris00148182020-08-20 10:46:51 -0700483 bug_lines += [x.strip(' ,') for x in
484 _wrap_commit_line('BUG=', buganizers).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800485 if args['crbug']:
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800486 crbugs = ', '.join('chromium:%d' % x for x in args['crbug'])
Brian Norris00148182020-08-20 10:46:51 -0700487 bug_lines += [x.strip(' ,') for x in
488 _wrap_commit_line('BUG=', crbugs).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800489
Brian Norris6bcfa392020-08-20 10:38:05 -0700490 test_lines = [_wrap_commit_line('TEST=', x) for x in args['test']]
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800491
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800492 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800493 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800494
495 # It is possible that multiple Change-Ids are in the commit message
496 # (due to cherry picking). We only want to pull out the first one.
497 changeid_match = re.search('^Change-Id: (.*)$',
498 old_commit_message, re.MULTILINE)
Tzung-Bi Shih5fd0fd52020-08-13 11:06:33 +0800499 if args['changeid'] is None and changeid_match:
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800500 args['changeid'] = changeid_match.group(1)
501
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800502 if not cq_depends:
503 cq_depends = re.findall(r'^Cq-Depend:\s+(.*)$',
504 old_commit_message, re.MULTILINE)
Tzung-Bi Shihdfe82002020-08-13 11:00:56 +0800505
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800506 if not bug_lines:
507 bug_lines = re.findall(r'^BUG=(.*)$',
508 old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800509
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800510 if not test_lines:
511 # Note: use (?=...) to avoid to consume the source string
512 test_lines = re.findall(r"""
513 ^TEST=(.*?) # Match start from TEST= until
514 \n # (to remove the tailing newlines)
515 (?=^$| # a blank line
516 ^Cq-Depend:| # or Cq-Depend:
517 ^Change-Id:| # or Change-Id:
518 ^BUG=| # or following BUG=
519 ^TEST=) # or another TEST=
520 """,
521 old_commit_message, re.MULTILINE | re.DOTALL | re.VERBOSE)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800522
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800523 if not bug_lines or not test_lines:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800524 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800525 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700526
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800527 if args['debug']:
528 pprint.pprint(args)
529
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800530 re_matches = (
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800531 (re.compile(r'^pw://(([^/]+)/)?(.+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700532 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700533 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
534 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800535 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800536 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800537 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800538 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800539 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800540
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100541 # Backup user provided parameters
542 user_source_line = args['source_line']
543 user_tag = args['tag']
544 user_changeid = args['changeid']
545
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800546 for location in args['locations']:
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100547 # Restore user parameters
548 args['source_line'] = user_source_line
549 args['tag'] = user_tag
550 args['changeid'] = user_changeid
551
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800552 if args['debug']:
553 print('location=%s' % location)
554
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800555 for reg, handler in re_matches:
556 match = reg.match(location)
557 if match:
558 ret = handler(match, args)
559 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800560 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800561 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800562 sys.exit(1)
563
564 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700565 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700566 if args['tag'] == 'UPSTREAM: ':
567 args['tag'] = 'BACKPORT: '
568 else:
569 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700570 _pause_for_merge(conflicts)
571 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700572 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800573
574 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800575 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800576
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700577 # Remove stray Change-Id, most likely from merge resolution
578 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
579
Brian Norris7a41b982018-06-01 10:28:29 -0700580 # Note the source location before tagging anything else
581 commit_message += '\n' + args['source_line']
582
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800583 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
584 # next commands know where to work on
585 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700586 commit_message += conflicts
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800587 commit_message += '\n'
588 commit_message += '\n'.join('BUG=%s' % bug for bug in bug_lines)
589 commit_message += '\n'
590 commit_message += '\n'.join('TEST=%s' % t for t in test_lines)
Brian Norris674209e2020-04-22 15:33:53 -0700591
592 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800593 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700594 signoff = 'Signed-off-by: %s <%s>' % (
595 _git(['config', 'user.name']),
596 _git(['config', 'user.email']))
597 if not signoff in commit_message.splitlines():
598 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800599 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800600
601 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800602 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800603
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700604 # If we see a "Link: " that seems to point to a Message-Id with an
605 # automatic Change-Id we'll snarf it out.
606 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
607 re.MULTILINE)
608 if mo and args['changeid'] is None:
609 args['changeid'] = mo.group(1)
610
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800611 # replace changeid if needed
612 if args['changeid'] is not None:
613 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
614 args['changeid'], commit_message)
615 args['changeid'] = None
616
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800617 if cq_depends:
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800618 commit_message = re.sub(
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800619 r'(Change-Id: \w+)',
620 r'%s\n\1' % '\n'.join('Cq-Depend: %s' % c for c in cq_depends),
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800621 commit_message)
622
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800623 # decorate it that it's from outside
624 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800625
626 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800627 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800628
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900629 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800630
631if __name__ == '__main__':
632 sys.exit(main(sys.argv[1:]))