blob: f8fd372f9dcbc1ae852dbfe1205ff62de1d2b685 [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
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800231 return _git_returncode(['am', '-3'], stdin=patch_contents, encoding=None)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800232
Stephen Boydb68c17a2019-09-26 15:08:02 -0700233def _match_patchwork(match, args):
234 """Match location: pw://### or pw://PROJECT/###."""
235 pw_project = match.group(2)
236 patch_id = int(match.group(3))
237
238 if args['debug']:
239 print('_match_patchwork: pw_project=%s, patch_id=%d' %
240 (pw_project, patch_id))
241
242 url = _get_pw_url(pw_project)
243 return _pick_patchwork(url, patch_id, args)
244
245def _match_msgid(match, args):
246 """Match location: msgid://MSGID."""
247 msgid = match.group(1)
248
249 if args['debug']:
250 print('_match_msgid: message_id=%s' % (msgid))
251
252 # Patchwork requires the brackets so force it
253 msgid = '<' + msgid + '>'
254 url = None
255 for url in PATCHWORK_URLS:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800256 rpc = xmlrpc.client.ServerProxy(url + '/xmlrpc/')
Stephen Boydb68c17a2019-09-26 15:08:02 -0700257 res = rpc.patch_list({'msgid': msgid})
258 if res:
259 patch_id = res[0]['id']
260 break
261 else:
262 errprint('Error: could not find patch based on message id')
263 sys.exit(1)
264
265 return _pick_patchwork(url, patch_id, args)
266
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700267def _upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800268 if args['debug']:
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700269 print('_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800270
Brian Norris8043cfd2020-03-19 11:46:16 -0700271 # Confirm an upstream remote is setup.
272 remote = _find_upstream_remote(urls)
273 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800274 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800275 sys.exit(1)
276
Brian Norris8043cfd2020-03-19 11:46:16 -0700277 remote_ref = '%s/master' % remote
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800278 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700279 _git(['merge-base', '--is-ancestor', commit, remote_ref])
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800280 except subprocess.CalledProcessError:
Brian Norris8043cfd2020-03-19 11:46:16 -0700281 errprint('Error: Commit not in %s' % remote_ref)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800282 sys.exit(1)
283
284 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800285 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800286 args['source_line'] = ('(cherry picked from commit %s)' %
287 (commit))
288 if args['tag'] is None:
289 args['tag'] = 'UPSTREAM: '
290
291 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800292 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800293
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800294 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800295
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700296def _match_upstream(match, args):
297 """Match location: linux://HASH and upstream://HASH."""
Brian Norris8043cfd2020-03-19 11:46:16 -0700298 commit = match.group(1)
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700299 return _upstream(commit, urls=UPSTREAM_URLS, args=args)
Brian Norris8043cfd2020-03-19 11:46:16 -0700300
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800301def _match_fromgit(match, args):
302 """Match location: git://remote/branch/HASH."""
303 remote = match.group(2)
304 branch = match.group(3)
305 commit = match.group(4)
306
307 if args['debug']:
308 print('_match_fromgit: remote=%s branch=%s commit=%s' %
309 (remote, branch, commit))
310
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800311 try:
312 _git(['merge-base', '--is-ancestor', commit,
313 '%s/%s' % (remote, branch)])
314 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800315 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800316 sys.exit(1)
317
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800318 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800319
320 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800321 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800322 args['source_line'] = (
323 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800324 if args['tag'] is None:
325 args['tag'] = 'FROMGIT: '
326
327 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800328 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800329
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800330 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800331
332def _match_gitfetch(match, args):
333 """Match location: (git|https)://repoURL#branch/HASH."""
334 remote = match.group(1)
335 branch = match.group(3)
336 commit = match.group(4)
337
338 if args['debug']:
339 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
340 (remote, branch, commit))
341
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800342 try:
343 _git(['fetch', remote, branch])
344 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800345 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800346 sys.exit(1)
347
348 url = remote
349
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
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800357 if args['replace']:
358 _git(['reset', '--hard', 'HEAD~1'])
359
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800360 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800361
Stephen Boyd96396032020-02-25 10:12:59 -0800362def _match_gitweb(match, args):
363 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
364 remote = match.group(1)
365 branch = match.group(2)
366 commit = match.group(3)
367
368 if args['debug']:
369 print('_match_gitweb: remote=%s branch=%s commit=%s' %
370 (remote, branch, commit))
371
372 try:
373 _git(['fetch', remote, branch])
374 except subprocess.CalledProcessError:
375 errprint('Error: Branch not in %s' % remote)
376 sys.exit(1)
377
378 url = remote
379
380 if args['source_line'] is None:
381 commit = _git(['rev-parse', commit])
382 args['source_line'] = (
383 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
384 if args['tag'] is None:
385 args['tag'] = 'FROMGIT: '
386
387 if args['replace']:
388 _git(['reset', '--hard', 'HEAD~1'])
389
390 return _git_returncode(['cherry-pick', commit])
391
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800392def main(args):
393 """This is the main entrypoint for fromupstream.
394
395 Args:
396 args: sys.argv[1:]
397
398 Returns:
399 An int return code.
400 """
401 parser = argparse.ArgumentParser()
402
403 parser.add_argument('--bug', '-b',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700404 type=str, help='BUG= line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800405 parser.add_argument('--test', '-t',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700406 type=str, help='TEST= line')
Stephen Boyd24b309b2018-11-06 22:11:00 -0800407 parser.add_argument('--crbug', action='append',
408 type=int, help='BUG=chromium: line')
409 parser.add_argument('--buganizer', action='append',
410 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800411 parser.add_argument('--changeid', '-c',
412 help='Overrides the gerrit generated Change-Id line')
413
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800414 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800415 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800416 help='Replaces the HEAD commit with this one, taking '
417 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800418 'updating commits.')
419 parser.add_argument('--nosignoff',
420 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800421 parser.add_argument('--debug', '-d', action='store_true',
422 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800423
424 parser.add_argument('--tag',
425 help='Overrides the tag from the title')
426 parser.add_argument('--source', '-s',
427 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800428 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800429 '(am from http://....)')
430 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700431 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800432 help='Patchwork ID (pw://### or pw://PROJECT/###, '
433 'where PROJECT is defined in ~/.pwclientrc; if no '
434 'PROJECT is specified, the default is retrieved from '
435 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700436 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700437 'linux commit like linux://HASH, '
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700438 'upstream commit like upstream://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800439 'git reference like git://remote/branch/HASH or '
440 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800441 'https://repoURL#branch/HASH or '
442 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800443
444 args = vars(parser.parse_args(args))
445
Stephen Boyd24b309b2018-11-06 22:11:00 -0800446 buglist = [args['bug']] if args['bug'] else []
447 if args['buganizer']:
448 buglist += ['b:{0}'.format(x) for x in args['buganizer']]
449 if args['crbug']:
450 buglist += ['chromium:{0}'.format(x) for x in args['crbug']]
Brian Norris667a0cb2018-12-07 09:28:46 -0800451 if buglist:
452 args['bug'] = ', '.join(buglist)
Stephen Boyd24b309b2018-11-06 22:11:00 -0800453
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800454 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800455 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800456
457 # It is possible that multiple Change-Ids are in the commit message
458 # (due to cherry picking). We only want to pull out the first one.
459 changeid_match = re.search('^Change-Id: (.*)$',
460 old_commit_message, re.MULTILINE)
461 if changeid_match:
462 args['changeid'] = changeid_match.group(1)
463
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800464 bugs = re.findall('^BUG=(.*)$', old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800465 if args['bug'] is None and bugs:
466 args['bug'] = '\nBUG='.join(bugs)
467
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800468 tests = re.findall('^TEST=(.*)$', old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800469 if args['test'] is None and tests:
470 args['test'] = '\nTEST='.join(tests)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800471 # TODO: deal with multiline BUG/TEST better
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800472
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700473 if args['bug'] is None or args['test'] is None:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800474 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800475 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700476
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800477 if args['debug']:
478 pprint.pprint(args)
479
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800480 re_matches = (
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800481 (re.compile(r'^pw://(([^/]+)/)?(\d+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700482 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Abhishek Pandit-Subediaea8c502020-07-09 21:56:12 -0700483 (re.compile(r'^linux://([0-9a-f]+)'), _match_upstream),
484 (re.compile(r'^upstream://([0-9a-f]+)'), _match_upstream),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800485 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800486 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800487 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800488 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800489 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800490
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800491 for location in args['locations']:
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800492 if args['debug']:
493 print('location=%s' % location)
494
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800495 for reg, handler in re_matches:
496 match = reg.match(location)
497 if match:
498 ret = handler(match, args)
499 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800500 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800501 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800502 sys.exit(1)
503
504 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700505 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700506 if args['tag'] == 'UPSTREAM: ':
507 args['tag'] = 'BACKPORT: '
508 else:
509 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700510 _pause_for_merge(conflicts)
511 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700512 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800513
514 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800515 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800516
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700517 # Remove stray Change-Id, most likely from merge resolution
518 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
519
Brian Norris7a41b982018-06-01 10:28:29 -0700520 # Note the source location before tagging anything else
521 commit_message += '\n' + args['source_line']
522
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800523 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
524 # next commands know where to work on
525 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700526 commit_message += conflicts
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800527 commit_message += '\n' + 'BUG=' + args['bug']
Harry Cuttsae372f32019-02-12 18:01:14 -0800528 commit_message += '\n' + _wrap_commit_line('TEST', args['test'])
Brian Norris674209e2020-04-22 15:33:53 -0700529
530 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800531 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700532 signoff = 'Signed-off-by: %s <%s>' % (
533 _git(['config', 'user.name']),
534 _git(['config', 'user.email']))
535 if not signoff in commit_message.splitlines():
536 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800537 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800538
539 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800540 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800541
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700542 # If we see a "Link: " that seems to point to a Message-Id with an
543 # automatic Change-Id we'll snarf it out.
544 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
545 re.MULTILINE)
546 if mo and args['changeid'] is None:
547 args['changeid'] = mo.group(1)
548
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800549 # replace changeid if needed
550 if args['changeid'] is not None:
551 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
552 args['changeid'], commit_message)
553 args['changeid'] = None
554
555 # decorate it that it's from outside
556 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800557
558 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800559 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800560
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900561 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800562
563if __name__ == '__main__':
564 sys.exit(main(sys.argv[1:]))