blob: 2065eff3818bee9400ae7f11056f2daf59a614cd [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',
Douglas Andersona3d1cb92021-02-01 09:13:07 -080046 'https://review.coreboot.org/flashrom.git'
Brian Norris8043cfd2020-03-19 11:46:16 -070047)
48
Stephen Boydb68c17a2019-09-26 15:08:02 -070049PATCHWORK_URLS = (
50 'https://lore.kernel.org/patchwork',
51 'https://patchwork.kernel.org',
52 'https://patchwork.ozlabs.org',
53 'https://patchwork.freedesktop.org',
Stephen Boydb68c17a2019-09-26 15:08:02 -070054)
55
Harry Cuttsae372f32019-02-12 18:01:14 -080056COMMIT_MESSAGE_WIDTH = 75
57
Brian Norris9f8a2be2018-06-01 11:14:08 -070058_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
59
Douglas Andersoncebcefd2020-09-24 10:37:36 -070060def _git(args, stdin=None, encoding='utf-8', no_stderr=False):
Alexandru M Stan725c71f2019-12-11 16:53:33 -080061 """Calls a git subcommand.
62
63 Similar to subprocess.check_output.
64
65 Args:
Brian Norris6baeb2e2020-03-18 12:13:30 -070066 args: subcommand + args passed to 'git'.
Alexandru M Stan725c71f2019-12-11 16:53:33 -080067 stdin: a string or bytes (depending on encoding) that will be passed
68 to the git subcommand.
69 encoding: either 'utf-8' (default) or None. Override it to None if
70 you want both stdin and stdout to be raw bytes.
Douglas Andersoncebcefd2020-09-24 10:37:36 -070071 no_stderr: If True, we'll eat stderr
Alexandru M Stan725c71f2019-12-11 16:53:33 -080072
73 Returns:
74 the stdout of the git subcommand, same type as stdin. The output is
75 also run through strip to make sure there's no extra whitespace.
76
77 Raises:
78 subprocess.CalledProcessError: when return code is not zero.
79 The exception has a .returncode attribute.
80 """
81 return subprocess.run(
82 ['git'] + args,
83 encoding=encoding,
84 input=stdin,
85 stdout=subprocess.PIPE,
Douglas Andersoncebcefd2020-09-24 10:37:36 -070086 stderr=(subprocess.PIPE if no_stderr else None),
Alexandru M Stan725c71f2019-12-11 16:53:33 -080087 check=True,
88 ).stdout.strip()
89
90def _git_returncode(*args, **kwargs):
91 """Same as _git, but return returncode instead of stdout.
92
93 Similar to subprocess.call.
94
95 Never raises subprocess.CalledProcessError.
96 """
97 try:
98 _git(*args, **kwargs)
99 return 0
100 except subprocess.CalledProcessError as e:
101 return e.returncode
102
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700103def _get_conflicts():
104 """Report conflicting files."""
105 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
106 conflicts = []
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800107 output = _git(['status', '--porcelain', '--untracked-files=no'])
108 for line in output.splitlines():
Douglas Anderson46287f92018-04-30 09:58:24 -0700109 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700110 continue
Douglas Anderson46287f92018-04-30 09:58:24 -0700111 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700112 if resolution in resolutions:
113 conflicts.append(' ' + name)
114 if not conflicts:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700115 return ''
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700116 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
117
Brian Norris8043cfd2020-03-19 11:46:16 -0700118def _find_upstream_remote(urls):
119 """Find a remote pointing to an upstream repository."""
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800120 for remote in _git(['remote']).splitlines():
121 try:
Abhishek Pandit-Subedi5ce64192020-11-02 16:10:17 -0800122 if _git(['remote', 'get-url', remote]).rstrip('/') in urls:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800123 return remote
124 except subprocess.CalledProcessError:
125 # Kinda weird, get-url failing on an item that git just gave us.
126 continue
Guenter Roeckd66daa72018-04-19 10:31:25 -0700127 return None
128
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700129def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800130 """Pause and go in the background till user resolves the conflicts."""
131
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800132 git_root = _git(['rev-parse', '--show-toplevel'])
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800133 previous_head_hash = _git(['rev-parse', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800134
135 paths = (
136 os.path.join(git_root, '.git', 'rebase-apply'),
137 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
138 )
139 for path in paths:
140 if os.path.exists(path):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800141 errprint('Found "%s".' % path)
142 errprint(conflicts)
143 errprint('Please resolve the conflicts and restart the '
144 'shell job when done. Kill this job if you '
145 'aborted the conflict.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800146 os.kill(os.getpid(), signal.SIGTSTP)
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800147
148 # Check the conflicts actually got resolved. Otherwise we'll end up
149 # modifying the wrong commit message and probably confusing people.
150 while previous_head_hash == _git(['rev-parse', 'HEAD']):
151 errprint('Error: no new commit has been made. Did you forget to run '
152 '`git am --continue` or `git cherry-pick --continue`?')
153 errprint('Please create a new commit and restart the shell job (or kill'
154 ' it if you aborted the conflict).')
155 os.kill(os.getpid(), signal.SIGTSTP)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800156
Brian Norris9f8a2be2018-06-01 11:14:08 -0700157def _get_pw_url(project):
158 """Retrieve the patchwork server URL from .pwclientrc.
159
Mike Frysingerf80ca212018-07-13 15:02:52 -0400160 Args:
161 project: patchwork project name; if None, we retrieve the default
162 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -0700163 """
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800164 config = configparser.ConfigParser()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700165 config.read([_PWCLIENTRC])
166
167 if project is None:
168 try:
169 project = config.get('options', 'default')
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800170 except (configparser.NoSectionError, configparser.NoOptionError) as e:
171 errprint('Error: no default patchwork project found in %s. (%r)'
172 % (_PWCLIENTRC, e))
Brian Norris9f8a2be2018-06-01 11:14:08 -0700173 sys.exit(1)
174
175 if not config.has_option(project, 'url'):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800176 errprint("Error: patchwork URL not found for project '%s'" % project)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700177 sys.exit(1)
178
179 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700180 # Strip trailing 'xmlrpc' and/or trailing slash.
181 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700182
Harry Cuttsae372f32019-02-12 18:01:14 -0800183def _wrap_commit_line(prefix, content):
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800184 line = prefix + content
185 indent = ' ' * len(prefix)
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800186
187 ret = textwrap.fill(line, COMMIT_MESSAGE_WIDTH, subsequent_indent=indent)
Tzung-Bi Shih2d061112020-08-17 10:27:24 +0800188 return ret[len(prefix):]
Harry Cuttsae372f32019-02-12 18:01:14 -0800189
Stephen Boydb68c17a2019-09-26 15:08:02 -0700190def _pick_patchwork(url, patch_id, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800191 if args['tag'] is None:
192 args['tag'] = 'FROMLIST: '
193
Brian Norris8553f032020-03-18 11:59:02 -0700194 try:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800195 opener = urllib.request.urlopen('%s/patch/%s/mbox' % (url, patch_id))
Brian Norris8553f032020-03-18 11:59:02 -0700196 except urllib.error.HTTPError as e:
197 errprint('Error: could not download patch: %s' % e)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800198 sys.exit(1)
199 patch_contents = opener.read()
200
201 if not patch_contents:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800202 errprint('Error: No patch content found')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800203 sys.exit(1)
204
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700205 message_id = mailbox.Message(patch_contents)['Message-Id']
206 message_id = re.sub('^<|>$', '', message_id.strip())
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800207 if args['source_line'] is None:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800208 args['source_line'] = '(am from %s/patch/%s/)' % (url, patch_id)
Brian Norris8553f032020-03-18 11:59:02 -0700209 for url_template in [
Brian Norris655b5ce2020-05-08 11:37:38 -0700210 'https://lore.kernel.org/r/%s',
Brian Norris8553f032020-03-18 11:59:02 -0700211 # hostap project (and others) are here, but not kernel.org.
212 'https://marc.info/?i=%s',
213 # public-inbox comes last as a "default"; it has a nice error page
214 # pointing to other redirectors, even if it doesn't have what
215 # you're looking for directly.
216 'https://public-inbox.org/git/%s',
217 ]:
218 alt_url = url_template % message_id
219 if args['debug']:
220 print('Probing archive for message at: %s' % alt_url)
221 try:
222 urllib.request.urlopen(alt_url)
223 except urllib.error.HTTPError as e:
224 # Skip all HTTP errors. We can expect 404 for archives that
225 # don't have this MessageId, or 300 for public-inbox ("not
226 # found, but try these other redirects"). It's less clear what
227 # to do with transitory (or is it permanent?) server failures.
228 if args['debug']:
229 print('Skipping URL %s, error: %s' % (alt_url, e))
230 continue
231 # Success!
232 if args['debug']:
233 print('Found at %s' % alt_url)
234 break
235 else:
236 errprint(
237 "WARNING: couldn't find working MessageId URL; "
238 'defaulting to "%s"' % alt_url)
239 args['source_line'] += '\n(also found at %s)' % alt_url
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800240
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700241 # Auto-snarf the Change-Id if it was encoded into the Message-Id.
242 mo = re.match(r'.*(I[a-f0-9]{40})@changeid$', message_id)
243 if mo and args['changeid'] is None:
244 args['changeid'] = mo.group(1)
245
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800246 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800247 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800248
Douglas Andersona2e91c42020-08-21 08:46:09 -0700249 return _git_returncode(['am', '-3'], stdin=patch_contents, encoding=None)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800250
Stephen Boydb68c17a2019-09-26 15:08:02 -0700251def _match_patchwork(match, args):
252 """Match location: pw://### or pw://PROJECT/###."""
253 pw_project = match.group(2)
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800254 patch_id = match.group(3)
Stephen Boydb68c17a2019-09-26 15:08:02 -0700255
256 if args['debug']:
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800257 print('_match_patchwork: pw_project=%s, patch_id=%s' %
Stephen Boydb68c17a2019-09-26 15:08:02 -0700258 (pw_project, patch_id))
259
260 url = _get_pw_url(pw_project)
261 return _pick_patchwork(url, patch_id, args)
262
263def _match_msgid(match, args):
264 """Match location: msgid://MSGID."""
265 msgid = match.group(1)
266
267 if args['debug']:
268 print('_match_msgid: message_id=%s' % (msgid))
269
270 # Patchwork requires the brackets so force it
271 msgid = '<' + msgid + '>'
272 url = None
273 for url in PATCHWORK_URLS:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800274 rpc = xmlrpc.client.ServerProxy(url + '/xmlrpc/')
Douglas Anderson297a3062020-09-09 12:47:09 -0700275 try:
276 res = rpc.patch_list({'msgid': msgid})
277 except ssl.SSLCertVerificationError:
278 errprint('Error: server "%s" gave an SSL error, skipping' % url)
279 continue
Douglas Anderson3ef68772021-01-25 08:48:05 -0800280 except socket.gaierror as e:
281 errprint('Error: server "%s" gave socket error "%s", skipping' % (url, e))
Stephen Boydb68c17a2019-09-26 15:08:02 -0700282 if res:
283 patch_id = res[0]['id']
284 break
285 else:
286 errprint('Error: could not find patch based on message id')
287 sys.exit(1)
288
289 return _pick_patchwork(url, patch_id, args)
290
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700291def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800292 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700293 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800294
Brian Norris8043cfd2020-03-19 11:46:16 -0700295 # Confirm an upstream remote is setup.
296 remote = _find_upstream_remote(urls)
297 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800298 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800299 sys.exit(1)
300
Douglas Andersoncebcefd2020-09-24 10:37:36 -0700301 branches = ['main', 'master']
302 for branch in branches:
303 remote_ref = '%s/%s' % (remote, branch)
304 try:
305 _git(['merge-base', '--is-ancestor', commit, remote_ref],
306 no_stderr=True)
307 except subprocess.CalledProcessError:
308 continue
309 break
310 else:
311 errprint('Error: Commit not in %s, branches: %s' % (
312 remote, ', '.join(branches)))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800313 sys.exit(1)
314
315 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800316 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800317 args['source_line'] = ('(cherry picked from commit %s)' %
318 (commit))
319 if args['tag'] is None:
320 args['tag'] = 'UPSTREAM: '
321
322 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800323 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800324
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800325 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800326
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700327def _match_upstream(match, args):
328 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700329 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700330 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700331
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800332def _match_fromgit(match, args):
333 """Match location: git://remote/branch/HASH."""
334 remote = match.group(2)
335 branch = match.group(3)
336 commit = match.group(4)
337
338 if args['debug']:
339 print('_match_fromgit: remote=%s branch=%s commit=%s' %
340 (remote, branch, commit))
341
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800342 try:
343 _git(['merge-base', '--is-ancestor', commit,
344 '%s/%s' % (remote, branch)])
345 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800346 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800347 sys.exit(1)
348
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800349 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800350
351 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800352 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800353 args['source_line'] = (
354 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800355 if args['tag'] is None:
356 args['tag'] = 'FROMGIT: '
357
358 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800359 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800360
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800361 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800362
363def _match_gitfetch(match, args):
364 """Match location: (git|https)://repoURL#branch/HASH."""
365 remote = match.group(1)
366 branch = match.group(3)
367 commit = match.group(4)
368
369 if args['debug']:
370 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
371 (remote, branch, commit))
372
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800373 try:
374 _git(['fetch', remote, branch])
375 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800376 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800377 sys.exit(1)
378
379 url = remote
380
381 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800382 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800383 args['source_line'] = (
384 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800385 if args['tag'] is None:
386 args['tag'] = 'FROMGIT: '
387
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800388 if args['replace']:
389 _git(['reset', '--hard', 'HEAD~1'])
390
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800391 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800392
Stephen Boyd96396032020-02-25 10:12:59 -0800393def _match_gitweb(match, args):
394 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
395 remote = match.group(1)
396 branch = match.group(2)
397 commit = match.group(3)
398
399 if args['debug']:
400 print('_match_gitweb: remote=%s branch=%s commit=%s' %
401 (remote, branch, commit))
402
403 try:
404 _git(['fetch', remote, branch])
405 except subprocess.CalledProcessError:
406 errprint('Error: Branch not in %s' % remote)
407 sys.exit(1)
408
409 url = remote
410
411 if args['source_line'] is None:
412 commit = _git(['rev-parse', commit])
413 args['source_line'] = (
414 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
415 if args['tag'] is None:
416 args['tag'] = 'FROMGIT: '
417
418 if args['replace']:
419 _git(['reset', '--hard', 'HEAD~1'])
420
421 return _git_returncode(['cherry-pick', commit])
422
Ricardo Ribaldad1aaede2021-01-15 13:00:50 +0100423def _remove_dup_bugs(bugs):
424 """Remove the duplicated bugs from a string keeping the original order."""
425
426 # Standardize all the spacing around bugs
427 bugs = re.sub(r'\s*,\s*', ', ', bugs)
428
429 # Create a list of bugs
430 bugs = bugs.split(', ')
431
432 # Remove duplicates keeping order
433 bugs = list(OrderedDict.fromkeys(bugs).keys())
434
435 # Convert into a string again
436 bugs = ', '.join(bugs)
437
438 return bugs
439
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800440def main(args):
441 """This is the main entrypoint for fromupstream.
442
443 Args:
444 args: sys.argv[1:]
445
446 Returns:
447 An int return code.
448 """
449 parser = argparse.ArgumentParser()
450
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000451 parser.add_argument('--bug', '-b', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700452 type=str, help='BUG= line')
Brian Norris6bcfa392020-08-20 10:38:05 -0700453 parser.add_argument('--test', '-t', action='append', default=[],
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700454 type=str, help='TEST= line')
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000455 parser.add_argument('--crbug', action='append', default=[],
Stephen Boyd24b309b2018-11-06 22:11:00 -0800456 type=int, help='BUG=chromium: line')
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000457 parser.add_argument('--buganizer', action='append', default=[],
Stephen Boyd24b309b2018-11-06 22:11:00 -0800458 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800459 parser.add_argument('--changeid', '-c',
460 help='Overrides the gerrit generated Change-Id line')
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800461 parser.add_argument('--cqdepend',
462 type=str, help='Cq-Depend: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800463
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800464 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800465 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800466 help='Replaces the HEAD commit with this one, taking '
467 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800468 'updating commits.')
469 parser.add_argument('--nosignoff',
470 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800471 parser.add_argument('--debug', '-d', action='store_true',
472 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800473
474 parser.add_argument('--tag',
475 help='Overrides the tag from the title')
476 parser.add_argument('--source', '-s',
477 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800478 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800479 '(am from http://....)')
480 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700481 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800482 help='Patchwork ID (pw://### or pw://PROJECT/###, '
483 'where PROJECT is defined in ~/.pwclientrc; if no '
484 'PROJECT is specified, the default is retrieved from '
485 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700486 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700487 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700488 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800489 'git reference like git://remote/branch/HASH or '
490 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800491 'https://repoURL#branch/HASH or '
492 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800493
494 args = vars(parser.parse_args(args))
495
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800496 cq_depends = [args['cqdepend']] if args['cqdepend'] else []
497
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000498 bugs = args['bug']
499 bugs += ['b:%d' % x for x in args['buganizer']]
500 bugs += ['chromium:%d' % x for x in args['crbug']]
501 bugs = ', '.join(bugs)
Ricardo Ribaldad1aaede2021-01-15 13:00:50 +0100502 bugs = _remove_dup_bugs(bugs)
Ricardo Ribaldab7ed04a2021-01-14 17:12:59 +0000503 bug_lines = [x.strip(' ,') for x in
504 _wrap_commit_line('BUG=', bugs).split('\n')]
Stephen Boyd24b309b2018-11-06 22:11:00 -0800505
Brian Norris6bcfa392020-08-20 10:38:05 -0700506 test_lines = [_wrap_commit_line('TEST=', x) for x in args['test']]
Tzung-Bi Shihc4cfabb2020-08-10 12:57:23 +0800507
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800508 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800509 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800510
511 # It is possible that multiple Change-Ids are in the commit message
512 # (due to cherry picking). We only want to pull out the first one.
513 changeid_match = re.search('^Change-Id: (.*)$',
514 old_commit_message, re.MULTILINE)
Tzung-Bi Shih5fd0fd52020-08-13 11:06:33 +0800515 if args['changeid'] is None and changeid_match:
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800516 args['changeid'] = changeid_match.group(1)
517
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800518 if not cq_depends:
519 cq_depends = re.findall(r'^Cq-Depend:\s+(.*)$',
520 old_commit_message, re.MULTILINE)
Tzung-Bi Shihdfe82002020-08-13 11:00:56 +0800521
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800522 if not bug_lines:
523 bug_lines = re.findall(r'^BUG=(.*)$',
524 old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800525
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800526 if not test_lines:
527 # Note: use (?=...) to avoid to consume the source string
528 test_lines = re.findall(r"""
529 ^TEST=(.*?) # Match start from TEST= until
530 \n # (to remove the tailing newlines)
531 (?=^$| # a blank line
532 ^Cq-Depend:| # or Cq-Depend:
533 ^Change-Id:| # or Change-Id:
534 ^BUG=| # or following BUG=
535 ^TEST=) # or another TEST=
536 """,
537 old_commit_message, re.MULTILINE | re.DOTALL | re.VERBOSE)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800538
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800539 if not bug_lines or not test_lines:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800540 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800541 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700542
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800543 if args['debug']:
544 pprint.pprint(args)
545
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800546 re_matches = (
Pi-Hsun Shih3a083842020-11-16 18:32:29 +0800547 (re.compile(r'^pw://(([^/]+)/)?(.+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700548 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700549 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
550 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800551 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800552 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800553 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800554 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800555 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800556
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100557 # Backup user provided parameters
558 user_source_line = args['source_line']
559 user_tag = args['tag']
560 user_changeid = args['changeid']
561
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800562 for location in args['locations']:
Ricardo Ribaldaf1348682020-11-03 13:51:07 +0100563 # Restore user parameters
564 args['source_line'] = user_source_line
565 args['tag'] = user_tag
566 args['changeid'] = user_changeid
567
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800568 if args['debug']:
569 print('location=%s' % location)
570
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800571 for reg, handler in re_matches:
572 match = reg.match(location)
573 if match:
574 ret = handler(match, args)
575 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800576 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800577 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800578 sys.exit(1)
579
580 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700581 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700582 if args['tag'] == 'UPSTREAM: ':
583 args['tag'] = 'BACKPORT: '
584 else:
585 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700586 _pause_for_merge(conflicts)
587 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700588 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800589
590 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800591 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800592
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700593 # Remove stray Change-Id, most likely from merge resolution
594 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
595
Brian Norris7a41b982018-06-01 10:28:29 -0700596 # Note the source location before tagging anything else
597 commit_message += '\n' + args['source_line']
598
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800599 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
600 # next commands know where to work on
601 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700602 commit_message += conflicts
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800603 commit_message += '\n'
604 commit_message += '\n'.join('BUG=%s' % bug for bug in bug_lines)
605 commit_message += '\n'
606 commit_message += '\n'.join('TEST=%s' % t for t in test_lines)
Brian Norris674209e2020-04-22 15:33:53 -0700607
608 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800609 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700610 signoff = 'Signed-off-by: %s <%s>' % (
611 _git(['config', 'user.name']),
612 _git(['config', 'user.email']))
613 if not signoff in commit_message.splitlines():
614 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800615 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800616
617 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800618 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800619
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700620 # If we see a "Link: " that seems to point to a Message-Id with an
621 # automatic Change-Id we'll snarf it out.
622 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
623 re.MULTILINE)
624 if mo and args['changeid'] is None:
625 args['changeid'] = mo.group(1)
626
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800627 # replace changeid if needed
628 if args['changeid'] is not None:
629 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
630 args['changeid'], commit_message)
631 args['changeid'] = None
632
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800633 if cq_depends:
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800634 commit_message = re.sub(
Tzung-Bi Shih621fed02020-08-14 22:58:55 +0800635 r'(Change-Id: \w+)',
636 r'%s\n\1' % '\n'.join('Cq-Depend: %s' % c for c in cq_depends),
Tzung-Bi Shih1a262c02020-08-13 10:49:55 +0800637 commit_message)
638
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800639 # decorate it that it's from outside
640 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800641
642 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800643 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800644
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900645 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800646
647if __name__ == '__main__':
648 sys.exit(main(sys.argv[1:]))