blob: ca35a6b79ee01934241aa16d261920130caf7773 [file] [log] [blame]
Alexandru M Stan725c71f2019-12-11 16:53:33 -08001#!/usr/bin/env python3
Brian Norris6baeb2e2020-03-18 12:13:30 -07002# -*- coding: utf-8 -*-
3#
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -08004# Copyright 2017 The Chromium OS Authors. All rights reserved.
5# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
Mike Frysingerf80ca212018-07-13 15:02:52 -04007
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -08008"""This is a tool for picking patches from upstream and applying them."""
9
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080010import argparse
Alexandru M Stan725c71f2019-12-11 16:53:33 -080011import configparser
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +080012import functools
Brian Norrisc3421042018-08-15 14:17:26 -070013import mailbox
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080014import os
Tzung-Bi Shih5100c742019-09-02 10:28:32 +080015import pprint
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080016import re
17import signal
18import subprocess
19import sys
Harry Cuttsae372f32019-02-12 18:01:14 -080020import textwrap
Alexandru M Stan725c71f2019-12-11 16:53:33 -080021import urllib.request
22import xmlrpc.client
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080023
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +080024errprint = functools.partial(print, file=sys.stderr)
25
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070026UPSTREAM_URLS = (
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080027 'git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
28 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git',
29 'https://kernel.googlesource.com/pub/scm/linux/kernel/git/torvalds/linux.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070030 'git://w1.fi/srv/git/hostap.git',
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -070031 'git://git.kernel.org/pub/scm/bluetooth/bluez.git',
Brian Norris8043cfd2020-03-19 11:46:16 -070032)
33
Stephen Boydb68c17a2019-09-26 15:08:02 -070034PATCHWORK_URLS = (
35 'https://lore.kernel.org/patchwork',
36 'https://patchwork.kernel.org',
37 'https://patchwork.ozlabs.org',
38 'https://patchwork.freedesktop.org',
39 'https://patchwork.linux-mips.org',
40)
41
Harry Cuttsae372f32019-02-12 18:01:14 -080042COMMIT_MESSAGE_WIDTH = 75
43
Brian Norris9f8a2be2018-06-01 11:14:08 -070044_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
45
Alexandru M Stan725c71f2019-12-11 16:53:33 -080046def _git(args, stdin=None, encoding='utf-8'):
47 """Calls a git subcommand.
48
49 Similar to subprocess.check_output.
50
51 Args:
Brian Norris6baeb2e2020-03-18 12:13:30 -070052 args: subcommand + args passed to 'git'.
Alexandru M Stan725c71f2019-12-11 16:53:33 -080053 stdin: a string or bytes (depending on encoding) that will be passed
54 to the git subcommand.
55 encoding: either 'utf-8' (default) or None. Override it to None if
56 you want both stdin and stdout to be raw bytes.
57
58 Returns:
59 the stdout of the git subcommand, same type as stdin. The output is
60 also run through strip to make sure there's no extra whitespace.
61
62 Raises:
63 subprocess.CalledProcessError: when return code is not zero.
64 The exception has a .returncode attribute.
65 """
66 return subprocess.run(
67 ['git'] + args,
68 encoding=encoding,
69 input=stdin,
70 stdout=subprocess.PIPE,
71 check=True,
72 ).stdout.strip()
73
74def _git_returncode(*args, **kwargs):
75 """Same as _git, but return returncode instead of stdout.
76
77 Similar to subprocess.call.
78
79 Never raises subprocess.CalledProcessError.
80 """
81 try:
82 _git(*args, **kwargs)
83 return 0
84 except subprocess.CalledProcessError as e:
85 return e.returncode
86
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070087def _get_conflicts():
88 """Report conflicting files."""
89 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
90 conflicts = []
Alexandru M Stan725c71f2019-12-11 16:53:33 -080091 output = _git(['status', '--porcelain', '--untracked-files=no'])
92 for line in output.splitlines():
Douglas Anderson46287f92018-04-30 09:58:24 -070093 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070094 continue
Douglas Anderson46287f92018-04-30 09:58:24 -070095 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070096 if resolution in resolutions:
97 conflicts.append(' ' + name)
98 if not conflicts:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -070099 return ''
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700100 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
101
Brian Norris8043cfd2020-03-19 11:46:16 -0700102def _find_upstream_remote(urls):
103 """Find a remote pointing to an upstream repository."""
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800104 for remote in _git(['remote']).splitlines():
105 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700106 if _git(['remote', 'get-url', remote]) in urls:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800107 return remote
108 except subprocess.CalledProcessError:
109 # Kinda weird, get-url failing on an item that git just gave us.
110 continue
Guenter Roeckd66daa72018-04-19 10:31:25 -0700111 return None
112
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700113def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800114 """Pause and go in the background till user resolves the conflicts."""
115
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800116 git_root = _git(['rev-parse', '--show-toplevel'])
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800117 previous_head_hash = _git(['rev-parse', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800118
119 paths = (
120 os.path.join(git_root, '.git', 'rebase-apply'),
121 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
122 )
123 for path in paths:
124 if os.path.exists(path):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800125 errprint('Found "%s".' % path)
126 errprint(conflicts)
127 errprint('Please resolve the conflicts and restart the '
128 'shell job when done. Kill this job if you '
129 'aborted the conflict.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800130 os.kill(os.getpid(), signal.SIGTSTP)
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800131
132 # Check the conflicts actually got resolved. Otherwise we'll end up
133 # modifying the wrong commit message and probably confusing people.
134 while previous_head_hash == _git(['rev-parse', 'HEAD']):
135 errprint('Error: no new commit has been made. Did you forget to run '
136 '`git am --continue` or `git cherry-pick --continue`?')
137 errprint('Please create a new commit and restart the shell job (or kill'
138 ' it if you aborted the conflict).')
139 os.kill(os.getpid(), signal.SIGTSTP)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800140
Brian Norris9f8a2be2018-06-01 11:14:08 -0700141def _get_pw_url(project):
142 """Retrieve the patchwork server URL from .pwclientrc.
143
Mike Frysingerf80ca212018-07-13 15:02:52 -0400144 Args:
145 project: patchwork project name; if None, we retrieve the default
146 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -0700147 """
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800148 config = configparser.ConfigParser()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700149 config.read([_PWCLIENTRC])
150
151 if project is None:
152 try:
153 project = config.get('options', 'default')
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800154 except (configparser.NoSectionError, configparser.NoOptionError) as e:
155 errprint('Error: no default patchwork project found in %s. (%r)'
156 % (_PWCLIENTRC, e))
Brian Norris9f8a2be2018-06-01 11:14:08 -0700157 sys.exit(1)
158
159 if not config.has_option(project, 'url'):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800160 errprint("Error: patchwork URL not found for project '%s'" % project)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700161 sys.exit(1)
162
163 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700164 # Strip trailing 'xmlrpc' and/or trailing slash.
165 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700166
Harry Cuttsae372f32019-02-12 18:01:14 -0800167def _wrap_commit_line(prefix, content):
168 line = prefix + '=' + content
169 indent = ' ' * (len(prefix) + 1)
170 return textwrap.fill(line, COMMIT_MESSAGE_WIDTH, subsequent_indent=indent)
171
Stephen Boydb68c17a2019-09-26 15:08:02 -0700172def _pick_patchwork(url, patch_id, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800173 if args['tag'] is None:
174 args['tag'] = 'FROMLIST: '
175
Brian Norris8553f032020-03-18 11:59:02 -0700176 try:
177 opener = urllib.request.urlopen('%s/patch/%d/mbox' % (url, patch_id))
178 except urllib.error.HTTPError as e:
179 errprint('Error: could not download patch: %s' % e)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800180 sys.exit(1)
181 patch_contents = opener.read()
182
183 if not patch_contents:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800184 errprint('Error: No patch content found')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800185 sys.exit(1)
186
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700187 message_id = mailbox.Message(patch_contents)['Message-Id']
188 message_id = re.sub('^<|>$', '', message_id.strip())
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800189 if args['source_line'] is None:
190 args['source_line'] = '(am from %s/patch/%d/)' % (url, patch_id)
Brian Norris8553f032020-03-18 11:59:02 -0700191 for url_template in [
Brian Norris655b5ce2020-05-08 11:37:38 -0700192 'https://lore.kernel.org/r/%s',
Brian Norris8553f032020-03-18 11:59:02 -0700193 # hostap project (and others) are here, but not kernel.org.
194 'https://marc.info/?i=%s',
195 # public-inbox comes last as a "default"; it has a nice error page
196 # pointing to other redirectors, even if it doesn't have what
197 # you're looking for directly.
198 'https://public-inbox.org/git/%s',
199 ]:
200 alt_url = url_template % message_id
201 if args['debug']:
202 print('Probing archive for message at: %s' % alt_url)
203 try:
204 urllib.request.urlopen(alt_url)
205 except urllib.error.HTTPError as e:
206 # Skip all HTTP errors. We can expect 404 for archives that
207 # don't have this MessageId, or 300 for public-inbox ("not
208 # found, but try these other redirects"). It's less clear what
209 # to do with transitory (or is it permanent?) server failures.
210 if args['debug']:
211 print('Skipping URL %s, error: %s' % (alt_url, e))
212 continue
213 # Success!
214 if args['debug']:
215 print('Found at %s' % alt_url)
216 break
217 else:
218 errprint(
219 "WARNING: couldn't find working MessageId URL; "
220 'defaulting to "%s"' % alt_url)
221 args['source_line'] += '\n(also found at %s)' % alt_url
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800222
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700223 # Auto-snarf the Change-Id if it was encoded into the Message-Id.
224 mo = re.match(r'.*(I[a-f0-9]{40})@changeid$', message_id)
225 if mo and args['changeid'] is None:
226 args['changeid'] = mo.group(1)
227
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800228 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800229 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800230
Tzung-Bi Shih3a4ebda2020-08-10 09:45:19 +0800231 return _git_returncode(['am', '-3', '--reject'], stdin=patch_contents,
232 encoding=None)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800233
Stephen Boydb68c17a2019-09-26 15:08:02 -0700234def _match_patchwork(match, args):
235 """Match location: pw://### or pw://PROJECT/###."""
236 pw_project = match.group(2)
237 patch_id = int(match.group(3))
238
239 if args['debug']:
240 print('_match_patchwork: pw_project=%s, patch_id=%d' %
241 (pw_project, patch_id))
242
243 url = _get_pw_url(pw_project)
244 return _pick_patchwork(url, patch_id, args)
245
246def _match_msgid(match, args):
247 """Match location: msgid://MSGID."""
248 msgid = match.group(1)
249
250 if args['debug']:
251 print('_match_msgid: message_id=%s' % (msgid))
252
253 # Patchwork requires the brackets so force it
254 msgid = '<' + msgid + '>'
255 url = None
256 for url in PATCHWORK_URLS:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800257 rpc = xmlrpc.client.ServerProxy(url + '/xmlrpc/')
Stephen Boydb68c17a2019-09-26 15:08:02 -0700258 res = rpc.patch_list({'msgid': msgid})
259 if res:
260 patch_id = res[0]['id']
261 break
262 else:
263 errprint('Error: could not find patch based on message id')
264 sys.exit(1)
265
266 return _pick_patchwork(url, patch_id, args)
267
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700268def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800269 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700270 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800271
Brian Norris8043cfd2020-03-19 11:46:16 -0700272 # Confirm an upstream remote is setup.
273 remote = _find_upstream_remote(urls)
274 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800275 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800276 sys.exit(1)
277
Brian Norris8043cfd2020-03-19 11:46:16 -0700278 remote_ref = '%s/master' % remote
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800279 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700280 _git(['merge-base', '--is-ancestor', commit, remote_ref])
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800281 except subprocess.CalledProcessError:
Brian Norris8043cfd2020-03-19 11:46:16 -0700282 errprint('Error: Commit not in %s' % remote_ref)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800283 sys.exit(1)
284
285 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800286 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800287 args['source_line'] = ('(cherry picked from commit %s)' %
288 (commit))
289 if args['tag'] is None:
290 args['tag'] = 'UPSTREAM: '
291
292 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800293 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800294
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800295 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800296
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700297def _match_upstream(match, args):
298 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700299 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700300 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700301
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800302def _match_fromgit(match, args):
303 """Match location: git://remote/branch/HASH."""
304 remote = match.group(2)
305 branch = match.group(3)
306 commit = match.group(4)
307
308 if args['debug']:
309 print('_match_fromgit: remote=%s branch=%s commit=%s' %
310 (remote, branch, commit))
311
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800312 try:
313 _git(['merge-base', '--is-ancestor', commit,
314 '%s/%s' % (remote, branch)])
315 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800316 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800317 sys.exit(1)
318
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800319 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800320
321 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800322 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800323 args['source_line'] = (
324 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800325 if args['tag'] is None:
326 args['tag'] = 'FROMGIT: '
327
328 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800329 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800330
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800331 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800332
333def _match_gitfetch(match, args):
334 """Match location: (git|https)://repoURL#branch/HASH."""
335 remote = match.group(1)
336 branch = match.group(3)
337 commit = match.group(4)
338
339 if args['debug']:
340 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
341 (remote, branch, commit))
342
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800343 try:
344 _git(['fetch', remote, branch])
345 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800346 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800347 sys.exit(1)
348
349 url = remote
350
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
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800358 if args['replace']:
359 _git(['reset', '--hard', 'HEAD~1'])
360
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800361 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800362
Stephen Boyd96396032020-02-25 10:12:59 -0800363def _match_gitweb(match, args):
364 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
365 remote = match.group(1)
366 branch = match.group(2)
367 commit = match.group(3)
368
369 if args['debug']:
370 print('_match_gitweb: remote=%s branch=%s commit=%s' %
371 (remote, branch, commit))
372
373 try:
374 _git(['fetch', remote, branch])
375 except subprocess.CalledProcessError:
376 errprint('Error: Branch not in %s' % remote)
377 sys.exit(1)
378
379 url = remote
380
381 if args['source_line'] is None:
382 commit = _git(['rev-parse', commit])
383 args['source_line'] = (
384 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
385 if args['tag'] is None:
386 args['tag'] = 'FROMGIT: '
387
388 if args['replace']:
389 _git(['reset', '--hard', 'HEAD~1'])
390
391 return _git_returncode(['cherry-pick', commit])
392
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800393def main(args):
394 """This is the main entrypoint for fromupstream.
395
396 Args:
397 args: sys.argv[1:]
398
399 Returns:
400 An int return code.
401 """
402 parser = argparse.ArgumentParser()
403
404 parser.add_argument('--bug', '-b',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700405 type=str, help='BUG= line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800406 parser.add_argument('--test', '-t',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700407 type=str, help='TEST= line')
Stephen Boyd24b309b2018-11-06 22:11:00 -0800408 parser.add_argument('--crbug', action='append',
409 type=int, help='BUG=chromium: line')
410 parser.add_argument('--buganizer', action='append',
411 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800412 parser.add_argument('--changeid', '-c',
413 help='Overrides the gerrit generated Change-Id line')
414
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800415 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800416 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800417 help='Replaces the HEAD commit with this one, taking '
418 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800419 'updating commits.')
420 parser.add_argument('--nosignoff',
421 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800422 parser.add_argument('--debug', '-d', action='store_true',
423 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800424
425 parser.add_argument('--tag',
426 help='Overrides the tag from the title')
427 parser.add_argument('--source', '-s',
428 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800429 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800430 '(am from http://....)')
431 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700432 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800433 help='Patchwork ID (pw://### or pw://PROJECT/###, '
434 'where PROJECT is defined in ~/.pwclientrc; if no '
435 'PROJECT is specified, the default is retrieved from '
436 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700437 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700438 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700439 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800440 'git reference like git://remote/branch/HASH or '
441 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800442 'https://repoURL#branch/HASH or '
443 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800444
445 args = vars(parser.parse_args(args))
446
Stephen Boyd24b309b2018-11-06 22:11:00 -0800447 buglist = [args['bug']] if args['bug'] else []
448 if args['buganizer']:
449 buglist += ['b:{0}'.format(x) for x in args['buganizer']]
450 if args['crbug']:
451 buglist += ['chromium:{0}'.format(x) for x in args['crbug']]
Brian Norris667a0cb2018-12-07 09:28:46 -0800452 if buglist:
453 args['bug'] = ', '.join(buglist)
Stephen Boyd24b309b2018-11-06 22:11:00 -0800454
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800455 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800456 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800457
458 # It is possible that multiple Change-Ids are in the commit message
459 # (due to cherry picking). We only want to pull out the first one.
460 changeid_match = re.search('^Change-Id: (.*)$',
461 old_commit_message, re.MULTILINE)
462 if changeid_match:
463 args['changeid'] = changeid_match.group(1)
464
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800465 bugs = re.findall('^BUG=(.*)$', old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800466 if args['bug'] is None and bugs:
467 args['bug'] = '\nBUG='.join(bugs)
468
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800469 tests = re.findall('^TEST=(.*)$', old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800470 if args['test'] is None and tests:
471 args['test'] = '\nTEST='.join(tests)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800472 # TODO: deal with multiline BUG/TEST better
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800473
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700474 if args['bug'] is None or args['test'] is None:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800475 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800476 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700477
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800478 if args['debug']:
479 pprint.pprint(args)
480
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800481 re_matches = (
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800482 (re.compile(r'^pw://(([^/]+)/)?(\d+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700483 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700484 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
485 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800486 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800487 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800488 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800489 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800490 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800491
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800492 for location in args['locations']:
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800493 if args['debug']:
494 print('location=%s' % location)
495
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800496 for reg, handler in re_matches:
497 match = reg.match(location)
498 if match:
499 ret = handler(match, args)
500 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800501 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800502 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800503 sys.exit(1)
504
505 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700506 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700507 if args['tag'] == 'UPSTREAM: ':
508 args['tag'] = 'BACKPORT: '
509 else:
510 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700511 _pause_for_merge(conflicts)
512 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700513 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800514
515 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800516 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800517
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700518 # Remove stray Change-Id, most likely from merge resolution
519 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
520
Brian Norris7a41b982018-06-01 10:28:29 -0700521 # Note the source location before tagging anything else
522 commit_message += '\n' + args['source_line']
523
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800524 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
525 # next commands know where to work on
526 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700527 commit_message += conflicts
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800528 commit_message += '\n' + 'BUG=' + args['bug']
Harry Cuttsae372f32019-02-12 18:01:14 -0800529 commit_message += '\n' + _wrap_commit_line('TEST', args['test'])
Brian Norris674209e2020-04-22 15:33:53 -0700530
531 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800532 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700533 signoff = 'Signed-off-by: %s <%s>' % (
534 _git(['config', 'user.name']),
535 _git(['config', 'user.email']))
536 if not signoff in commit_message.splitlines():
537 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800538 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800539
540 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800541 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800542
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700543 # If we see a "Link: " that seems to point to a Message-Id with an
544 # automatic Change-Id we'll snarf it out.
545 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
546 re.MULTILINE)
547 if mo and args['changeid'] is None:
548 args['changeid'] = mo.group(1)
549
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800550 # replace changeid if needed
551 if args['changeid'] is not None:
552 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
553 args['changeid'], commit_message)
554 args['changeid'] = None
555
556 # decorate it that it's from outside
557 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800558
559 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800560 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800561
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900562 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800563
564if __name__ == '__main__':
565 sys.exit(main(sys.argv[1:]))