blob: adf328f958cad7f31d068b81627409077378db8d [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 Anderson3ef68772021-01-25 08:48:05 -080019import socket
Douglas Anderson297a3062020-09-09 12:47:09 -070020import ssl
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080021import subprocess
22import sys
Harry Cuttsae372f32019-02-12 18:01:14 -080023import textwrap
Alexandru M Stan725c71f2019-12-11 16:53:33 -080024import urllib.request
25import xmlrpc.client
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080026
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +080027errprint = functools.partial(print, file=sys.stderr)
28
Brian Norris00148182020-08-20 10:46:51 -070029# pylint: disable=line-too-long
Abhishek Pandit-Subedi5ce64192020-11-02 16:10:17 -080030# Note: Do not include trailing / in any of these
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070031UPSTREAM_URLS = (
Douglas Andersoncebcefd2020-09-24 10:37:36 -070032 # Acceptable Linux URLs
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080033 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
34 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
35 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
Douglas Andersoncebcefd2020-09-24 10:37:36 -070036
37 # Acceptible Linux Firmware URLs
38 'git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
39 'https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
40 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/firmware/linux-firmware.git',
41
42 # Upstream for various other projects
Brian Norris8043cfd2020-03-19 11:46:16 -070043 'git://w1.fi/srv/git/hostap.git',
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070044 'git://git.kernel.org/pub/scm/bluetooth/bluez.git',
Douglas Anderson482a6d62020-09-21 09:31:54 -070045 'https://github.com/andersson/qrtr.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070046)
47
Stephen Boydb68c17a2019-09-26 15:08:02 -070048PATCHWORK_URLS = (
49 'https://lore.kernel.org/patchwork',
50 'https://patchwork.kernel.org',
51 'https://patchwork.ozlabs.org',
52 'https://patchwork.freedesktop.org',
Stephen Boydb68c17a2019-09-26 15:08:02 -070053)
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
Douglas Anderson3ef68772021-01-25 08:48:05 -0800279 except socket.gaierror as e:
280 errprint('Error: server "%s" gave socket error "%s", skipping' % (url, e))
Stephen Boydb68c17a2019-09-26 15:08:02 -0700281 if res:
282 patch_id = res[0]['id']
283 break
284 else:
285 errprint('Error: could not find patch based on message id')
286 sys.exit(1)
287
288 return _pick_patchwork(url, patch_id, args)
289
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700290def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800291 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700292 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800293
Brian Norris8043cfd2020-03-19 11:46:16 -0700294 # Confirm an upstream remote is setup.
295 remote = _find_upstream_remote(urls)
296 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800297 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800298 sys.exit(1)
299
Douglas Andersoncebcefd2020-09-24 10:37:36 -0700300 branches = ['main', 'master']
301 for branch in branches:
302 remote_ref = '%s/%s' % (remote, branch)
303 try:
304 _git(['merge-base', '--is-ancestor', commit, remote_ref],
305 no_stderr=True)
306 except subprocess.CalledProcessError:
307 continue
308 break
309 else:
310 errprint('Error: Commit not in %s, branches: %s' % (
311 remote, ', '.join(branches)))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800312 sys.exit(1)
313
314 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800315 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800316 args['source_line'] = ('(cherry picked from commit %s)' %
317 (commit))
318 if args['tag'] is None:
319 args['tag'] = 'UPSTREAM: '
320
321 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800322 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800323
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800324 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800325
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700326def _match_upstream(match, args):
327 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700328 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700329 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700330
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800331def _match_fromgit(match, args):
332 """Match location: git://remote/branch/HASH."""
333 remote = match.group(2)
334 branch = match.group(3)
335 commit = match.group(4)
336
337 if args['debug']:
338 print('_match_fromgit: remote=%s branch=%s commit=%s' %
339 (remote, branch, commit))
340
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800341 try:
342 _git(['merge-base', '--is-ancestor', commit,
343 '%s/%s' % (remote, branch)])
344 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800345 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800346 sys.exit(1)
347
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800348 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800349
350 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800351 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800352 args['source_line'] = (
353 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800354 if args['tag'] is None:
355 args['tag'] = 'FROMGIT: '
356
357 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800358 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800359
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800360 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800361
362def _match_gitfetch(match, args):
363 """Match location: (git|https)://repoURL#branch/HASH."""
364 remote = match.group(1)
365 branch = match.group(3)
366 commit = match.group(4)
367
368 if args['debug']:
369 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
370 (remote, branch, commit))
371
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800372 try:
373 _git(['fetch', remote, branch])
374 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800375 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800376 sys.exit(1)
377
378 url = remote
379
380 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800381 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800382 args['source_line'] = (
383 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800384 if args['tag'] is None:
385 args['tag'] = 'FROMGIT: '
386
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800387 if args['replace']:
388 _git(['reset', '--hard', 'HEAD~1'])
389
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800390 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800391
Stephen Boyd96396032020-02-25 10:12:59 -0800392def _match_gitweb(match, args):
393 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
394 remote = match.group(1)
395 branch = match.group(2)
396 commit = match.group(3)
397
398 if args['debug']:
399 print('_match_gitweb: remote=%s branch=%s commit=%s' %
400 (remote, branch, commit))
401
402 try:
403 _git(['fetch', remote, branch])
404 except subprocess.CalledProcessError:
405 errprint('Error: Branch not in %s' % remote)
406 sys.exit(1)
407
408 url = remote
409
410 if args['source_line'] is None:
411 commit = _git(['rev-parse', commit])
412 args['source_line'] = (
413 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
414 if args['tag'] is None:
415 args['tag'] = 'FROMGIT: '
416
417 if args['replace']:
418 _git(['reset', '--hard', 'HEAD~1'])
419
420 return _git_returncode(['cherry-pick', commit])
421
Ricardo Ribaldad1aaede2021-01-15 13:00:50 +0100422def _remove_dup_bugs(bugs):
423 """Remove the duplicated bugs from a string keeping the original order."""
424
425 # Standardize all the spacing around bugs
426 bugs = re.sub(r'\s*,\s*', ', ', bugs)
427
428 # Create a list of bugs
429 bugs = bugs.split(', ')
430
431 # Remove duplicates keeping order
432 bugs = list(OrderedDict.fromkeys(bugs).keys())
433
434 # Convert into a string again
435 bugs = ', '.join(bugs)
436
437 return bugs
438
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800439def main(args):
440 """This is the main entrypoint for fromupstream.
441
442 Args:
443 args: sys.argv[1:]
444
445 Returns:
446 An int return code.
447 """
448 parser = argparse.ArgumentParser()
449
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000450 parser.add_argument('--bug', '-b', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700451 type=str, help='BUG= line')
Brian Norris6bcfa392020-08-20 10:38:05 -0700452 parser.add_argument('--test', '-t', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700453 type=str, help='TEST= line')
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000454 parser.add_argument('--crbug', action='append', default=[],
Stephen Boyd24b309b2018-11-06 22:11:00 -0800455 type=int, help='BUG=chromium: line')
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000456 parser.add_argument('--buganizer', action='append', default=[],
Stephen Boyd24b309b2018-11-06 22:11:00 -0800457 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800458 parser.add_argument('--changeid', '-c',
459 help='Overrides the gerrit generated Change-Id line')
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800460 parser.add_argument('--cqdepend',
461 type=str, help='Cq-Depend: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800462
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800463 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800464 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800465 help='Replaces the HEAD commit with this one, taking '
466 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800467 'updating commits.')
468 parser.add_argument('--nosignoff',
469 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800470 parser.add_argument('--debug', '-d', action='store_true',
471 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800472
473 parser.add_argument('--tag',
474 help='Overrides the tag from the title')
475 parser.add_argument('--source', '-s',
476 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800477 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800478 '(am from http://....)')
479 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700480 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800481 help='Patchwork ID (pw://### or pw://PROJECT/###, '
482 'where PROJECT is defined in ~/.pwclientrc; if no '
483 'PROJECT is specified, the default is retrieved from '
484 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700485 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700486 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700487 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800488 'git reference like git://remote/branch/HASH or '
489 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800490 'https://repoURL#branch/HASH or '
491 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800492
493 args = vars(parser.parse_args(args))
494
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800495 cq_depends = [args['cqdepend']] if args['cqdepend'] else []
496
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000497 bugs = args['bug']
498 bugs += ['b:%d' % x for x in args['buganizer']]
499 bugs += ['chromium:%d' % x for x in args['crbug']]
500 bugs = ', '.join(bugs)
Ricardo Ribaldad1aaede2021-01-15 13:00:50 +0100501 bugs = _remove_dup_bugs(bugs)
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000502 bug_lines = [x.strip(' ,') for x in
503 _wrap_commit_line('BUG=', bugs).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800504
Brian Norris6bcfa392020-08-20 10:38:05 -0700505 test_lines = [_wrap_commit_line('TEST=', x) for x in args['test']]
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800506
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800507 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800508 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800509
510 # It is possible that multiple Change-Ids are in the commit message
511 # (due to cherry picking). We only want to pull out the first one.
512 changeid_match = re.search('^Change-Id: (.*)$',
513 old_commit_message, re.MULTILINE)
Tzung-Bi Shih5fd0fd52020-08-13 11:06:33 +0800514 if args['changeid'] is None and changeid_match:
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800515 args['changeid'] = changeid_match.group(1)
516
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800517 if not cq_depends:
518 cq_depends = re.findall(r'^Cq-Depend:\s+(.*)$',
519 old_commit_message, re.MULTILINE)
Tzung-Bi Shihdfe82002020-08-13 11:00:56 +0800520
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800521 if not bug_lines:
522 bug_lines = re.findall(r'^BUG=(.*)$',
523 old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800524
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800525 if not test_lines:
526 # Note: use (?=...) to avoid to consume the source string
527 test_lines = re.findall(r"""
528 ^TEST=(.*?) # Match start from TEST= until
529 \n # (to remove the tailing newlines)
530 (?=^$| # a blank line
531 ^Cq-Depend:| # or Cq-Depend:
532 ^Change-Id:| # or Change-Id:
533 ^BUG=| # or following BUG=
534 ^TEST=) # or another TEST=
535 """,
536 old_commit_message, re.MULTILINE | re.DOTALL | re.VERBOSE)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800537
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800538 if not bug_lines or not test_lines:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800539 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800540 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700541
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800542 if args['debug']:
543 pprint.pprint(args)
544
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800545 re_matches = (
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800546 (re.compile(r'^pw://(([^/]+)/)?(.+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700547 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700548 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
549 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800550 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800551 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800552 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800553 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800554 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800555
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100556 # Backup user provided parameters
557 user_source_line = args['source_line']
558 user_tag = args['tag']
559 user_changeid = args['changeid']
560
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800561 for location in args['locations']:
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100562 # Restore user parameters
563 args['source_line'] = user_source_line
564 args['tag'] = user_tag
565 args['changeid'] = user_changeid
566
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800567 if args['debug']:
568 print('location=%s' % location)
569
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800570 for reg, handler in re_matches:
571 match = reg.match(location)
572 if match:
573 ret = handler(match, args)
574 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800575 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800576 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800577 sys.exit(1)
578
579 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700580 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700581 if args['tag'] == 'UPSTREAM: ':
582 args['tag'] = 'BACKPORT: '
583 else:
584 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700585 _pause_for_merge(conflicts)
586 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700587 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800588
589 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800590 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800591
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700592 # Remove stray Change-Id, most likely from merge resolution
593 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
594
Brian Norris7a41b982018-06-01 10:28:29 -0700595 # Note the source location before tagging anything else
596 commit_message += '\n' + args['source_line']
597
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800598 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
599 # next commands know where to work on
600 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700601 commit_message += conflicts
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800602 commit_message += '\n'
603 commit_message += '\n'.join('BUG=%s' % bug for bug in bug_lines)
604 commit_message += '\n'
605 commit_message += '\n'.join('TEST=%s' % t for t in test_lines)
Brian Norris674209e2020-04-22 15:33:53 -0700606
607 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800608 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700609 signoff = 'Signed-off-by: %s <%s>' % (
610 _git(['config', 'user.name']),
611 _git(['config', 'user.email']))
612 if not signoff in commit_message.splitlines():
613 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800614 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800615
616 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800617 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800618
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700619 # If we see a "Link: " that seems to point to a Message-Id with an
620 # automatic Change-Id we'll snarf it out.
621 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
622 re.MULTILINE)
623 if mo and args['changeid'] is None:
624 args['changeid'] = mo.group(1)
625
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800626 # replace changeid if needed
627 if args['changeid'] is not None:
628 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
629 args['changeid'], commit_message)
630 args['changeid'] = None
631
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800632 if cq_depends:
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800633 commit_message = re.sub(
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800634 r'(Change-Id: \w+)',
635 r'%s\n\1' % '\n'.join('Cq-Depend: %s' % c for c in cq_depends),
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800636 commit_message)
637
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800638 # decorate it that it's from outside
639 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800640
641 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800642 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800643
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900644 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800645
646if __name__ == '__main__':
647 sys.exit(main(sys.argv[1:]))