blob: c84bb33b5eeb7053431ec83a8740ea8af38bd894 [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
Ricardo Ribaldad1aaede2021-01-15 13:00:50 +010011from collections import OrderedDict
Alexandru M Stan725c71f2019-12-11 16:53:33 -080012import configparser
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +080013import functools
Brian Norrisc3421042018-08-15 14:17:26 -070014import mailbox
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080015import os
Tzung-Bi Shih5100c742019-09-02 10:28:32 +080016import pprint
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080017import re
18import signal
Douglas Anderson297a3062020-09-09 12:47:09 -070019import ssl
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080020import subprocess
21import sys
Harry Cuttsae372f32019-02-12 18:01:14 -080022import textwrap
Alexandru M Stan725c71f2019-12-11 16:53:33 -080023import urllib.request
24import xmlrpc.client
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080025
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +080026errprint = functools.partial(print, file=sys.stderr)
27
Brian Norris00148182020-08-20 10:46:51 -070028# pylint: disable=line-too-long
Abhishek Pandit-Subedi5ce64192020-11-02 16:10:17 -080029# Note: Do not include trailing / in any of these
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070030UPSTREAM_URLS = (
Douglas Andersoncebcefd2020-09-24 10:37:36 -070031 # Acceptable Linux URLs
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080032 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
33 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
34 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
Douglas Andersoncebcefd2020-09-24 10:37:36 -070035
36 # Acceptible Linux Firmware URLs
37 'git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
38 'https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
39 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
40
41 # Upstream for various other projects
Brian Norris8043cfd2020-03-19 11:46:16 -070042 'git://w1.fi/srv/git/hostap.git',
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070043 'git://git.kernel.org/pub/scm/bluetooth/bluez.git',
Douglas Anderson482a6d62020-09-21 09:31:54 -070044 'https://github.com/andersson/qrtr.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070045)
46
Stephen Boydb68c17a2019-09-26 15:08:02 -070047PATCHWORK_URLS = (
48 'https://lore.kernel.org/patchwork',
49 'https://patchwork.kernel.org',
50 'https://patchwork.ozlabs.org',
51 'https://patchwork.freedesktop.org',
52 'https://patchwork.linux-mips.org',
53)
54
Harry Cuttsae372f32019-02-12 18:01:14 -080055COMMIT_MESSAGE_WIDTH = 75
56
Brian Norris9f8a2be2018-06-01 11:14:08 -070057_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
58
Douglas Andersoncebcefd2020-09-24 10:37:36 -070059def _git(args, stdin=None, encoding='utf-8', no_stderr=False):
Alexandru M Stan725c71f2019-12-11 16:53:33 -080060 """Calls a git subcommand.
61
62 Similar to subprocess.check_output.
63
64 Args:
Brian Norris6baeb2e2020-03-18 12:13:30 -070065 args: subcommand + args passed to 'git'.
Alexandru M Stan725c71f2019-12-11 16:53:33 -080066 stdin: a string or bytes (depending on encoding) that will be passed
67 to the git subcommand.
68 encoding: either 'utf-8' (default) or None. Override it to None if
69 you want both stdin and stdout to be raw bytes.
Douglas Andersoncebcefd2020-09-24 10:37:36 -070070 no_stderr: If True, we'll eat stderr
Alexandru M Stan725c71f2019-12-11 16:53:33 -080071
72 Returns:
73 the stdout of the git subcommand, same type as stdin. The output is
74 also run through strip to make sure there's no extra whitespace.
75
76 Raises:
77 subprocess.CalledProcessError: when return code is not zero.
78 The exception has a .returncode attribute.
79 """
80 return subprocess.run(
81 ['git'] + args,
82 encoding=encoding,
83 input=stdin,
84 stdout=subprocess.PIPE,
Douglas Andersoncebcefd2020-09-24 10:37:36 -070085 stderr=(subprocess.PIPE if no_stderr else None),
Alexandru M Stan725c71f2019-12-11 16:53:33 -080086 check=True,
87 ).stdout.strip()
88
89def _git_returncode(*args, **kwargs):
90 """Same as _git, but return returncode instead of stdout.
91
92 Similar to subprocess.call.
93
94 Never raises subprocess.CalledProcessError.
95 """
96 try:
97 _git(*args, **kwargs)
98 return 0
99 except subprocess.CalledProcessError as e:
100 return e.returncode
101
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700102def _get_conflicts():
103 """Report conflicting files."""
104 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
105 conflicts = []
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800106 output = _git(['status', '--porcelain', '--untracked-files=no'])
107 for line in output.splitlines():
Douglas Anderson46287f92018-04-30 09:58:24 -0700108 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700109 continue
Douglas Anderson46287f92018-04-30 09:58:24 -0700110 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700111 if resolution in resolutions:
112 conflicts.append(' ' + name)
113 if not conflicts:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700114 return ''
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700115 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
116
Brian Norris8043cfd2020-03-19 11:46:16 -0700117def _find_upstream_remote(urls):
118 """Find a remote pointing to an upstream repository."""
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800119 for remote in _git(['remote']).splitlines():
120 try:
Abhishek Pandit-Subedi5ce64192020-11-02 16:10:17 -0800121 if _git(['remote', 'get-url', remote]).rstrip('/') in urls:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800122 return remote
123 except subprocess.CalledProcessError:
124 # Kinda weird, get-url failing on an item that git just gave us.
125 continue
Guenter Roeckd66daa72018-04-19 10:31:25 -0700126 return None
127
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700128def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800129 """Pause and go in the background till user resolves the conflicts."""
130
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800131 git_root = _git(['rev-parse', '--show-toplevel'])
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800132 previous_head_hash = _git(['rev-parse', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800133
134 paths = (
135 os.path.join(git_root, '.git', 'rebase-apply'),
136 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
137 )
138 for path in paths:
139 if os.path.exists(path):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800140 errprint('Found "%s".' % path)
141 errprint(conflicts)
142 errprint('Please resolve the conflicts and restart the '
143 'shell job when done. Kill this job if you '
144 'aborted the conflict.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800145 os.kill(os.getpid(), signal.SIGTSTP)
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800146
147 # Check the conflicts actually got resolved. Otherwise we'll end up
148 # modifying the wrong commit message and probably confusing people.
149 while previous_head_hash == _git(['rev-parse', 'HEAD']):
150 errprint('Error: no new commit has been made. Did you forget to run '
151 '`git am --continue` or `git cherry-pick --continue`?')
152 errprint('Please create a new commit and restart the shell job (or kill'
153 ' it if you aborted the conflict).')
154 os.kill(os.getpid(), signal.SIGTSTP)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800155
Brian Norris9f8a2be2018-06-01 11:14:08 -0700156def _get_pw_url(project):
157 """Retrieve the patchwork server URL from .pwclientrc.
158
Mike Frysingerf80ca212018-07-13 15:02:52 -0400159 Args:
160 project: patchwork project name; if None, we retrieve the default
161 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -0700162 """
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800163 config = configparser.ConfigParser()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700164 config.read([_PWCLIENTRC])
165
166 if project is None:
167 try:
168 project = config.get('options', 'default')
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800169 except (configparser.NoSectionError, configparser.NoOptionError) as e:
170 errprint('Error: no default patchwork project found in %s. (%r)'
171 % (_PWCLIENTRC, e))
Brian Norris9f8a2be2018-06-01 11:14:08 -0700172 sys.exit(1)
173
174 if not config.has_option(project, 'url'):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800175 errprint("Error: patchwork URL not found for project '%s'" % project)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700176 sys.exit(1)
177
178 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700179 # Strip trailing 'xmlrpc' and/or trailing slash.
180 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700181
Harry Cuttsae372f32019-02-12 18:01:14 -0800182def _wrap_commit_line(prefix, content):
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800183 line = prefix + content
184 indent = ' ' * len(prefix)
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800185
186 ret = textwrap.fill(line, COMMIT_MESSAGE_WIDTH, subsequent_indent=indent)
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800187 return ret[len(prefix):]
Harry Cuttsae372f32019-02-12 18:01:14 -0800188
Stephen Boydb68c17a2019-09-26 15:08:02 -0700189def _pick_patchwork(url, patch_id, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800190 if args['tag'] is None:
191 args['tag'] = 'FROMLIST: '
192
Brian Norris8553f032020-03-18 11:59:02 -0700193 try:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800194 opener = urllib.request.urlopen('%s/patch/%s/mbox' % (url, patch_id))
Brian Norris8553f032020-03-18 11:59:02 -0700195 except urllib.error.HTTPError as e:
196 errprint('Error: could not download patch: %s' % e)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800197 sys.exit(1)
198 patch_contents = opener.read()
199
200 if not patch_contents:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800201 errprint('Error: No patch content found')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800202 sys.exit(1)
203
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700204 message_id = mailbox.Message(patch_contents)['Message-Id']
205 message_id = re.sub('^<|>$', '', message_id.strip())
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800206 if args['source_line'] is None:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800207 args['source_line'] = '(am from %s/patch/%s/)' % (url, patch_id)
Brian Norris8553f032020-03-18 11:59:02 -0700208 for url_template in [
Brian Norris655b5ce2020-05-08 11:37:38 -0700209 'https://lore.kernel.org/r/%s',
Brian Norris8553f032020-03-18 11:59:02 -0700210 # hostap project (and others) are here, but not kernel.org.
211 'https://marc.info/?i=%s',
212 # public-inbox comes last as a "default"; it has a nice error page
213 # pointing to other redirectors, even if it doesn't have what
214 # you're looking for directly.
215 'https://public-inbox.org/git/%s',
216 ]:
217 alt_url = url_template % message_id
218 if args['debug']:
219 print('Probing archive for message at: %s' % alt_url)
220 try:
221 urllib.request.urlopen(alt_url)
222 except urllib.error.HTTPError as e:
223 # Skip all HTTP errors. We can expect 404 for archives that
224 # don't have this MessageId, or 300 for public-inbox ("not
225 # found, but try these other redirects"). It's less clear what
226 # to do with transitory (or is it permanent?) server failures.
227 if args['debug']:
228 print('Skipping URL %s, error: %s' % (alt_url, e))
229 continue
230 # Success!
231 if args['debug']:
232 print('Found at %s' % alt_url)
233 break
234 else:
235 errprint(
236 "WARNING: couldn't find working MessageId URL; "
237 'defaulting to "%s"' % alt_url)
238 args['source_line'] += '\n(also found at %s)' % alt_url
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800239
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700240 # Auto-snarf the Change-Id if it was encoded into the Message-Id.
241 mo = re.match(r'.*(I[a-f0-9]{40})@changeid$', message_id)
242 if mo and args['changeid'] is None:
243 args['changeid'] = mo.group(1)
244
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800245 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800246 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800247
Douglas Andersona2e91c42020-08-21 08:46:09 -0700248 return _git_returncode(['am', '-3'], stdin=patch_contents, encoding=None)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800249
Stephen Boydb68c17a2019-09-26 15:08:02 -0700250def _match_patchwork(match, args):
251 """Match location: pw://### or pw://PROJECT/###."""
252 pw_project = match.group(2)
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800253 patch_id = match.group(3)
Stephen Boydb68c17a2019-09-26 15:08:02 -0700254
255 if args['debug']:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800256 print('_match_patchwork: pw_project=%s, patch_id=%s' %
Stephen Boydb68c17a2019-09-26 15:08:02 -0700257 (pw_project, patch_id))
258
259 url = _get_pw_url(pw_project)
260 return _pick_patchwork(url, patch_id, args)
261
262def _match_msgid(match, args):
263 """Match location: msgid://MSGID."""
264 msgid = match.group(1)
265
266 if args['debug']:
267 print('_match_msgid: message_id=%s' % (msgid))
268
269 # Patchwork requires the brackets so force it
270 msgid = '<' + msgid + '>'
271 url = None
272 for url in PATCHWORK_URLS:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800273 rpc = xmlrpc.client.ServerProxy(url + '/xmlrpc/')
Douglas Anderson297a3062020-09-09 12:47:09 -0700274 try:
275 res = rpc.patch_list({'msgid': msgid})
276 except ssl.SSLCertVerificationError:
277 errprint('Error: server "%s" gave an SSL error, skipping' % url)
278 continue
Stephen Boydb68c17a2019-09-26 15:08:02 -0700279 if res:
280 patch_id = res[0]['id']
281 break
282 else:
283 errprint('Error: could not find patch based on message id')
284 sys.exit(1)
285
286 return _pick_patchwork(url, patch_id, args)
287
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700288def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800289 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700290 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800291
Brian Norris8043cfd2020-03-19 11:46:16 -0700292 # Confirm an upstream remote is setup.
293 remote = _find_upstream_remote(urls)
294 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800295 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800296 sys.exit(1)
297
Douglas Andersoncebcefd2020-09-24 10:37:36 -0700298 branches = ['main', 'master']
299 for branch in branches:
300 remote_ref = '%s/%s' % (remote, branch)
301 try:
302 _git(['merge-base', '--is-ancestor', commit, remote_ref],
303 no_stderr=True)
304 except subprocess.CalledProcessError:
305 continue
306 break
307 else:
308 errprint('Error: Commit not in %s, branches: %s' % (
309 remote, ', '.join(branches)))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800310 sys.exit(1)
311
312 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800313 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800314 args['source_line'] = ('(cherry picked from commit %s)' %
315 (commit))
316 if args['tag'] is None:
317 args['tag'] = 'UPSTREAM: '
318
319 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800320 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800321
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800322 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800323
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700324def _match_upstream(match, args):
325 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700326 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700327 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700328
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800329def _match_fromgit(match, args):
330 """Match location: git://remote/branch/HASH."""
331 remote = match.group(2)
332 branch = match.group(3)
333 commit = match.group(4)
334
335 if args['debug']:
336 print('_match_fromgit: remote=%s branch=%s commit=%s' %
337 (remote, branch, commit))
338
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800339 try:
340 _git(['merge-base', '--is-ancestor', commit,
341 '%s/%s' % (remote, branch)])
342 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800343 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800344 sys.exit(1)
345
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800346 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800347
348 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800349 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800350 args['source_line'] = (
351 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800352 if args['tag'] is None:
353 args['tag'] = 'FROMGIT: '
354
355 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800356 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800357
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800358 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800359
360def _match_gitfetch(match, args):
361 """Match location: (git|https)://repoURL#branch/HASH."""
362 remote = match.group(1)
363 branch = match.group(3)
364 commit = match.group(4)
365
366 if args['debug']:
367 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
368 (remote, branch, commit))
369
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800370 try:
371 _git(['fetch', remote, branch])
372 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800373 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800374 sys.exit(1)
375
376 url = remote
377
378 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800379 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800380 args['source_line'] = (
381 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800382 if args['tag'] is None:
383 args['tag'] = 'FROMGIT: '
384
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800385 if args['replace']:
386 _git(['reset', '--hard', 'HEAD~1'])
387
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800388 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800389
Stephen Boyd96396032020-02-25 10:12:59 -0800390def _match_gitweb(match, args):
391 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
392 remote = match.group(1)
393 branch = match.group(2)
394 commit = match.group(3)
395
396 if args['debug']:
397 print('_match_gitweb: remote=%s branch=%s commit=%s' %
398 (remote, branch, commit))
399
400 try:
401 _git(['fetch', remote, branch])
402 except subprocess.CalledProcessError:
403 errprint('Error: Branch not in %s' % remote)
404 sys.exit(1)
405
406 url = remote
407
408 if args['source_line'] is None:
409 commit = _git(['rev-parse', commit])
410 args['source_line'] = (
411 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
412 if args['tag'] is None:
413 args['tag'] = 'FROMGIT: '
414
415 if args['replace']:
416 _git(['reset', '--hard', 'HEAD~1'])
417
418 return _git_returncode(['cherry-pick', commit])
419
Ricardo Ribaldad1aaede2021-01-15 13:00:50 +0100420def _remove_dup_bugs(bugs):
421 """Remove the duplicated bugs from a string keeping the original order."""
422
423 # Standardize all the spacing around bugs
424 bugs = re.sub(r'\s*,\s*', ', ', bugs)
425
426 # Create a list of bugs
427 bugs = bugs.split(', ')
428
429 # Remove duplicates keeping order
430 bugs = list(OrderedDict.fromkeys(bugs).keys())
431
432 # Convert into a string again
433 bugs = ', '.join(bugs)
434
435 return bugs
436
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800437def main(args):
438 """This is the main entrypoint for fromupstream.
439
440 Args:
441 args: sys.argv[1:]
442
443 Returns:
444 An int return code.
445 """
446 parser = argparse.ArgumentParser()
447
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000448 parser.add_argument('--bug', '-b', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700449 type=str, help='BUG= line')
Brian Norris6bcfa392020-08-20 10:38:05 -0700450 parser.add_argument('--test', '-t', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700451 type=str, help='TEST= line')
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000452 parser.add_argument('--crbug', action='append', default=[],
Stephen Boyd24b309b2018-11-06 22:11:00 -0800453 type=int, help='BUG=chromium: line')
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000454 parser.add_argument('--buganizer', action='append', default=[],
Stephen Boyd24b309b2018-11-06 22:11:00 -0800455 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800456 parser.add_argument('--changeid', '-c',
457 help='Overrides the gerrit generated Change-Id line')
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800458 parser.add_argument('--cqdepend',
459 type=str, help='Cq-Depend: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800460
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800461 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800462 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800463 help='Replaces the HEAD commit with this one, taking '
464 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800465 'updating commits.')
466 parser.add_argument('--nosignoff',
467 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800468 parser.add_argument('--debug', '-d', action='store_true',
469 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800470
471 parser.add_argument('--tag',
472 help='Overrides the tag from the title')
473 parser.add_argument('--source', '-s',
474 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800475 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800476 '(am from http://....)')
477 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700478 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800479 help='Patchwork ID (pw://### or pw://PROJECT/###, '
480 'where PROJECT is defined in ~/.pwclientrc; if no '
481 'PROJECT is specified, the default is retrieved from '
482 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700483 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700484 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700485 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800486 'git reference like git://remote/branch/HASH or '
487 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800488 'https://repoURL#branch/HASH or '
489 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800490
491 args = vars(parser.parse_args(args))
492
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800493 cq_depends = [args['cqdepend']] if args['cqdepend'] else []
494
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000495 bugs = args['bug']
496 bugs += ['b:%d' % x for x in args['buganizer']]
497 bugs += ['chromium:%d' % x for x in args['crbug']]
498 bugs = ', '.join(bugs)
Ricardo Ribaldad1aaede2021-01-15 13:00:50 +0100499 bugs = _remove_dup_bugs(bugs)
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000500 bug_lines = [x.strip(' ,') for x in
501 _wrap_commit_line('BUG=', bugs).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800502
Brian Norris6bcfa392020-08-20 10:38:05 -0700503 test_lines = [_wrap_commit_line('TEST=', x) for x in args['test']]
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800504
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800505 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800506 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800507
508 # It is possible that multiple Change-Ids are in the commit message
509 # (due to cherry picking). We only want to pull out the first one.
510 changeid_match = re.search('^Change-Id: (.*)$',
511 old_commit_message, re.MULTILINE)
Tzung-Bi Shih5fd0fd52020-08-13 11:06:33 +0800512 if args['changeid'] is None and changeid_match:
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800513 args['changeid'] = changeid_match.group(1)
514
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800515 if not cq_depends:
516 cq_depends = re.findall(r'^Cq-Depend:\s+(.*)$',
517 old_commit_message, re.MULTILINE)
Tzung-Bi Shihdfe82002020-08-13 11:00:56 +0800518
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800519 if not bug_lines:
520 bug_lines = re.findall(r'^BUG=(.*)$',
521 old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800522
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800523 if not test_lines:
524 # Note: use (?=...) to avoid to consume the source string
525 test_lines = re.findall(r"""
526 ^TEST=(.*?) # Match start from TEST= until
527 \n # (to remove the tailing newlines)
528 (?=^$| # a blank line
529 ^Cq-Depend:| # or Cq-Depend:
530 ^Change-Id:| # or Change-Id:
531 ^BUG=| # or following BUG=
532 ^TEST=) # or another TEST=
533 """,
534 old_commit_message, re.MULTILINE | re.DOTALL | re.VERBOSE)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800535
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800536 if not bug_lines or not test_lines:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800537 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800538 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700539
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800540 if args['debug']:
541 pprint.pprint(args)
542
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800543 re_matches = (
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800544 (re.compile(r'^pw://(([^/]+)/)?(.+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700545 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700546 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
547 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800548 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800549 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800550 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800551 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800552 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800553
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100554 # Backup user provided parameters
555 user_source_line = args['source_line']
556 user_tag = args['tag']
557 user_changeid = args['changeid']
558
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800559 for location in args['locations']:
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100560 # Restore user parameters
561 args['source_line'] = user_source_line
562 args['tag'] = user_tag
563 args['changeid'] = user_changeid
564
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800565 if args['debug']:
566 print('location=%s' % location)
567
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800568 for reg, handler in re_matches:
569 match = reg.match(location)
570 if match:
571 ret = handler(match, args)
572 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800573 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800574 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800575 sys.exit(1)
576
577 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700578 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700579 if args['tag'] == 'UPSTREAM: ':
580 args['tag'] = 'BACKPORT: '
581 else:
582 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700583 _pause_for_merge(conflicts)
584 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700585 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800586
587 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800588 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800589
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700590 # Remove stray Change-Id, most likely from merge resolution
591 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
592
Brian Norris7a41b982018-06-01 10:28:29 -0700593 # Note the source location before tagging anything else
594 commit_message += '\n' + args['source_line']
595
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800596 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
597 # next commands know where to work on
598 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700599 commit_message += conflicts
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800600 commit_message += '\n'
601 commit_message += '\n'.join('BUG=%s' % bug for bug in bug_lines)
602 commit_message += '\n'
603 commit_message += '\n'.join('TEST=%s' % t for t in test_lines)
Brian Norris674209e2020-04-22 15:33:53 -0700604
605 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800606 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700607 signoff = 'Signed-off-by: %s <%s>' % (
608 _git(['config', 'user.name']),
609 _git(['config', 'user.email']))
610 if not signoff in commit_message.splitlines():
611 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800612 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800613
614 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800615 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800616
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700617 # If we see a "Link: " that seems to point to a Message-Id with an
618 # automatic Change-Id we'll snarf it out.
619 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
620 re.MULTILINE)
621 if mo and args['changeid'] is None:
622 args['changeid'] = mo.group(1)
623
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800624 # replace changeid if needed
625 if args['changeid'] is not None:
626 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
627 args['changeid'], commit_message)
628 args['changeid'] = None
629
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800630 if cq_depends:
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800631 commit_message = re.sub(
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800632 r'(Change-Id: \w+)',
633 r'%s\n\1' % '\n'.join('Cq-Depend: %s' % c for c in cq_depends),
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800634 commit_message)
635
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800636 # decorate it that it's from outside
637 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800638
639 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800640 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800641
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900642 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800643
644if __name__ == '__main__':
645 sys.exit(main(sys.argv[1:]))