blob: 408d0345d4590ee21bc087c5148e58553d5719b8 [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
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -080026LINUX_URLS = (
27 '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',
30)
31
Brian Norris8043cfd2020-03-19 11:46:16 -070032HOSTAP_URLS = (
33 'git://w1.fi/srv/git/hostap.git',
34)
35
Stephen Boydb68c17a2019-09-26 15:08:02 -070036PATCHWORK_URLS = (
37 'https://lore.kernel.org/patchwork',
38 'https://patchwork.kernel.org',
39 'https://patchwork.ozlabs.org',
40 'https://patchwork.freedesktop.org',
41 'https://patchwork.linux-mips.org',
42)
43
Harry Cuttsae372f32019-02-12 18:01:14 -080044COMMIT_MESSAGE_WIDTH = 75
45
Brian Norris9f8a2be2018-06-01 11:14:08 -070046_PWCLIENTRC = os.path.expanduser('~/.pwclientrc')
47
Alexandru M Stan725c71f2019-12-11 16:53:33 -080048def _git(args, stdin=None, encoding='utf-8'):
49 """Calls a git subcommand.
50
51 Similar to subprocess.check_output.
52
53 Args:
Brian Norris6baeb2e2020-03-18 12:13:30 -070054 args: subcommand + args passed to 'git'.
Alexandru M Stan725c71f2019-12-11 16:53:33 -080055 stdin: a string or bytes (depending on encoding) that will be passed
56 to the git subcommand.
57 encoding: either 'utf-8' (default) or None. Override it to None if
58 you want both stdin and stdout to be raw bytes.
59
60 Returns:
61 the stdout of the git subcommand, same type as stdin. The output is
62 also run through strip to make sure there's no extra whitespace.
63
64 Raises:
65 subprocess.CalledProcessError: when return code is not zero.
66 The exception has a .returncode attribute.
67 """
68 return subprocess.run(
69 ['git'] + args,
70 encoding=encoding,
71 input=stdin,
72 stdout=subprocess.PIPE,
73 check=True,
74 ).stdout.strip()
75
76def _git_returncode(*args, **kwargs):
77 """Same as _git, but return returncode instead of stdout.
78
79 Similar to subprocess.call.
80
81 Never raises subprocess.CalledProcessError.
82 """
83 try:
84 _git(*args, **kwargs)
85 return 0
86 except subprocess.CalledProcessError as e:
87 return e.returncode
88
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070089def _get_conflicts():
90 """Report conflicting files."""
91 resolutions = ('DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU')
92 conflicts = []
Alexandru M Stan725c71f2019-12-11 16:53:33 -080093 output = _git(['status', '--porcelain', '--untracked-files=no'])
94 for line in output.splitlines():
Douglas Anderson46287f92018-04-30 09:58:24 -070095 if not line:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070096 continue
Douglas Anderson46287f92018-04-30 09:58:24 -070097 resolution, name = line.split(None, 1)
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -070098 if resolution in resolutions:
99 conflicts.append(' ' + name)
100 if not conflicts:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700101 return ''
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700102 return '\nConflicts:\n%s\n' % '\n'.join(conflicts)
103
Brian Norris8043cfd2020-03-19 11:46:16 -0700104def _find_upstream_remote(urls):
105 """Find a remote pointing to an upstream repository."""
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800106 for remote in _git(['remote']).splitlines():
107 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700108 if _git(['remote', 'get-url', remote]) in urls:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800109 return remote
110 except subprocess.CalledProcessError:
111 # Kinda weird, get-url failing on an item that git just gave us.
112 continue
Guenter Roeckd66daa72018-04-19 10:31:25 -0700113 return None
114
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700115def _pause_for_merge(conflicts):
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800116 """Pause and go in the background till user resolves the conflicts."""
117
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800118 git_root = _git(['rev-parse', '--show-toplevel'])
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800119 previous_head_hash = _git(['rev-parse', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800120
121 paths = (
122 os.path.join(git_root, '.git', 'rebase-apply'),
123 os.path.join(git_root, '.git', 'CHERRY_PICK_HEAD'),
124 )
125 for path in paths:
126 if os.path.exists(path):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800127 errprint('Found "%s".' % path)
128 errprint(conflicts)
129 errprint('Please resolve the conflicts and restart the '
130 'shell job when done. Kill this job if you '
131 'aborted the conflict.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800132 os.kill(os.getpid(), signal.SIGTSTP)
Harry Cutts2bcd9af2020-02-20 16:27:50 -0800133
134 # Check the conflicts actually got resolved. Otherwise we'll end up
135 # modifying the wrong commit message and probably confusing people.
136 while previous_head_hash == _git(['rev-parse', 'HEAD']):
137 errprint('Error: no new commit has been made. Did you forget to run '
138 '`git am --continue` or `git cherry-pick --continue`?')
139 errprint('Please create a new commit and restart the shell job (or kill'
140 ' it if you aborted the conflict).')
141 os.kill(os.getpid(), signal.SIGTSTP)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800142
Brian Norris9f8a2be2018-06-01 11:14:08 -0700143def _get_pw_url(project):
144 """Retrieve the patchwork server URL from .pwclientrc.
145
Mike Frysingerf80ca212018-07-13 15:02:52 -0400146 Args:
147 project: patchwork project name; if None, we retrieve the default
148 from pwclientrc
Brian Norris9f8a2be2018-06-01 11:14:08 -0700149 """
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800150 config = configparser.ConfigParser()
Brian Norris9f8a2be2018-06-01 11:14:08 -0700151 config.read([_PWCLIENTRC])
152
153 if project is None:
154 try:
155 project = config.get('options', 'default')
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800156 except (configparser.NoSectionError, configparser.NoOptionError) as e:
157 errprint('Error: no default patchwork project found in %s. (%r)'
158 % (_PWCLIENTRC, e))
Brian Norris9f8a2be2018-06-01 11:14:08 -0700159 sys.exit(1)
160
161 if not config.has_option(project, 'url'):
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800162 errprint("Error: patchwork URL not found for project '%s'" % project)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700163 sys.exit(1)
164
165 url = config.get(project, 'url')
Brian Norris2d4e9762018-08-15 13:11:47 -0700166 # Strip trailing 'xmlrpc' and/or trailing slash.
167 return re.sub('/(xmlrpc/)?$', '', url)
Brian Norris9f8a2be2018-06-01 11:14:08 -0700168
Harry Cuttsae372f32019-02-12 18:01:14 -0800169def _wrap_commit_line(prefix, content):
170 line = prefix + '=' + content
171 indent = ' ' * (len(prefix) + 1)
172 return textwrap.fill(line, COMMIT_MESSAGE_WIDTH, subsequent_indent=indent)
173
Stephen Boydb68c17a2019-09-26 15:08:02 -0700174def _pick_patchwork(url, patch_id, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800175 if args['tag'] is None:
176 args['tag'] = 'FROMLIST: '
177
Brian Norris8553f032020-03-18 11:59:02 -0700178 try:
179 opener = urllib.request.urlopen('%s/patch/%d/mbox' % (url, patch_id))
180 except urllib.error.HTTPError as e:
181 errprint('Error: could not download patch: %s' % e)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800182 sys.exit(1)
183 patch_contents = opener.read()
184
185 if not patch_contents:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800186 errprint('Error: No patch content found')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800187 sys.exit(1)
188
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700189 message_id = mailbox.Message(patch_contents)['Message-Id']
190 message_id = re.sub('^<|>$', '', message_id.strip())
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800191 if args['source_line'] is None:
192 args['source_line'] = '(am from %s/patch/%d/)' % (url, patch_id)
Brian Norris8553f032020-03-18 11:59:02 -0700193 for url_template in [
Brian Norris655b5ce2020-05-08 11:37:38 -0700194 'https://lore.kernel.org/r/%s',
Brian Norris8553f032020-03-18 11:59:02 -0700195 # hostap project (and others) are here, but not kernel.org.
196 'https://marc.info/?i=%s',
197 # public-inbox comes last as a "default"; it has a nice error page
198 # pointing to other redirectors, even if it doesn't have what
199 # you're looking for directly.
200 'https://public-inbox.org/git/%s',
201 ]:
202 alt_url = url_template % message_id
203 if args['debug']:
204 print('Probing archive for message at: %s' % alt_url)
205 try:
206 urllib.request.urlopen(alt_url)
207 except urllib.error.HTTPError as e:
208 # Skip all HTTP errors. We can expect 404 for archives that
209 # don't have this MessageId, or 300 for public-inbox ("not
210 # found, but try these other redirects"). It's less clear what
211 # to do with transitory (or is it permanent?) server failures.
212 if args['debug']:
213 print('Skipping URL %s, error: %s' % (alt_url, e))
214 continue
215 # Success!
216 if args['debug']:
217 print('Found at %s' % alt_url)
218 break
219 else:
220 errprint(
221 "WARNING: couldn't find working MessageId URL; "
222 'defaulting to "%s"' % alt_url)
223 args['source_line'] += '\n(also found at %s)' % alt_url
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800224
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700225 # Auto-snarf the Change-Id if it was encoded into the Message-Id.
226 mo = re.match(r'.*(I[a-f0-9]{40})@changeid$', message_id)
227 if mo and args['changeid'] is None:
228 args['changeid'] = mo.group(1)
229
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800230 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800231 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800232
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800233 return _git_returncode(['am', '-3'], stdin=patch_contents, encoding=None)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800234
Stephen Boydb68c17a2019-09-26 15:08:02 -0700235def _match_patchwork(match, args):
236 """Match location: pw://### or pw://PROJECT/###."""
237 pw_project = match.group(2)
238 patch_id = int(match.group(3))
239
240 if args['debug']:
241 print('_match_patchwork: pw_project=%s, patch_id=%d' %
242 (pw_project, patch_id))
243
244 url = _get_pw_url(pw_project)
245 return _pick_patchwork(url, patch_id, args)
246
247def _match_msgid(match, args):
248 """Match location: msgid://MSGID."""
249 msgid = match.group(1)
250
251 if args['debug']:
252 print('_match_msgid: message_id=%s' % (msgid))
253
254 # Patchwork requires the brackets so force it
255 msgid = '<' + msgid + '>'
256 url = None
257 for url in PATCHWORK_URLS:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800258 rpc = xmlrpc.client.ServerProxy(url + '/xmlrpc/')
Stephen Boydb68c17a2019-09-26 15:08:02 -0700259 res = rpc.patch_list({'msgid': msgid})
260 if res:
261 patch_id = res[0]['id']
262 break
263 else:
264 errprint('Error: could not find patch based on message id')
265 sys.exit(1)
266
267 return _pick_patchwork(url, patch_id, args)
268
Brian Norris8043cfd2020-03-19 11:46:16 -0700269def _match_upstream(commit, urls, args):
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800270 if args['debug']:
Brian Norris8043cfd2020-03-19 11:46:16 -0700271 print('_match_upstream: commit=%s' % commit)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800272
Brian Norris8043cfd2020-03-19 11:46:16 -0700273 # Confirm an upstream remote is setup.
274 remote = _find_upstream_remote(urls)
275 if not remote:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800276 errprint('Error: need a valid upstream remote')
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800277 sys.exit(1)
278
Brian Norris8043cfd2020-03-19 11:46:16 -0700279 remote_ref = '%s/master' % remote
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800280 try:
Brian Norris8043cfd2020-03-19 11:46:16 -0700281 _git(['merge-base', '--is-ancestor', commit, remote_ref])
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800282 except subprocess.CalledProcessError:
Brian Norris8043cfd2020-03-19 11:46:16 -0700283 errprint('Error: Commit not in %s' % remote_ref)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800284 sys.exit(1)
285
286 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800287 commit = _git(['rev-parse', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800288 args['source_line'] = ('(cherry picked from commit %s)' %
289 (commit))
290 if args['tag'] is None:
291 args['tag'] = 'UPSTREAM: '
292
293 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800294 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800295
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800296 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800297
Brian Norris8043cfd2020-03-19 11:46:16 -0700298def _match_linux(match, args):
299 """Match location: linux://HASH."""
300 commit = match.group(1)
301 return _match_upstream(commit, urls=LINUX_URLS, args=args)
302
303def _match_hostap(match, args):
304 """Match location: hostap://HASH."""
305 commit = match.group(1)
306 return _match_upstream(commit, urls=HOSTAP_URLS, args=args)
307
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800308def _match_fromgit(match, args):
309 """Match location: git://remote/branch/HASH."""
310 remote = match.group(2)
311 branch = match.group(3)
312 commit = match.group(4)
313
314 if args['debug']:
315 print('_match_fromgit: remote=%s branch=%s commit=%s' %
316 (remote, branch, commit))
317
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800318 try:
319 _git(['merge-base', '--is-ancestor', commit,
320 '%s/%s' % (remote, branch)])
321 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800322 errprint('Error: Commit not in %s/%s' % (remote, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800323 sys.exit(1)
324
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800325 url = _git(['remote', 'get-url', remote])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800326
327 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800328 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800329 args['source_line'] = (
330 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800331 if args['tag'] is None:
332 args['tag'] = 'FROMGIT: '
333
334 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800335 _git(['reset', '--hard', 'HEAD~1'])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800336
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800337 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800338
339def _match_gitfetch(match, args):
340 """Match location: (git|https)://repoURL#branch/HASH."""
341 remote = match.group(1)
342 branch = match.group(3)
343 commit = match.group(4)
344
345 if args['debug']:
346 print('_match_gitfetch: remote=%s branch=%s commit=%s' %
347 (remote, branch, commit))
348
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800349 try:
350 _git(['fetch', remote, branch])
351 except subprocess.CalledProcessError:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800352 errprint('Error: Branch not in %s' % remote)
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800353 sys.exit(1)
354
355 url = remote
356
357 if args['source_line'] is None:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800358 commit = _git(['rev-parse', commit])
Tzung-Bi Shiha8f310d2019-09-04 19:10:10 +0800359 args['source_line'] = (
360 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800361 if args['tag'] is None:
362 args['tag'] = 'FROMGIT: '
363
Stephen Boyd4b3869a2020-01-24 15:35:37 -0800364 if args['replace']:
365 _git(['reset', '--hard', 'HEAD~1'])
366
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800367 return _git_returncode(['cherry-pick', commit])
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800368
Stephen Boyd96396032020-02-25 10:12:59 -0800369def _match_gitweb(match, args):
370 """Match location: https://repoURL/commit/?h=branch&id=HASH."""
371 remote = match.group(1)
372 branch = match.group(2)
373 commit = match.group(3)
374
375 if args['debug']:
376 print('_match_gitweb: remote=%s branch=%s commit=%s' %
377 (remote, branch, commit))
378
379 try:
380 _git(['fetch', remote, branch])
381 except subprocess.CalledProcessError:
382 errprint('Error: Branch not in %s' % remote)
383 sys.exit(1)
384
385 url = remote
386
387 if args['source_line'] is None:
388 commit = _git(['rev-parse', commit])
389 args['source_line'] = (
390 '(cherry picked from commit %s\n %s %s)' % (commit, url, branch))
391 if args['tag'] is None:
392 args['tag'] = 'FROMGIT: '
393
394 if args['replace']:
395 _git(['reset', '--hard', 'HEAD~1'])
396
397 return _git_returncode(['cherry-pick', commit])
398
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800399def main(args):
400 """This is the main entrypoint for fromupstream.
401
402 Args:
403 args: sys.argv[1:]
404
405 Returns:
406 An int return code.
407 """
408 parser = argparse.ArgumentParser()
409
410 parser.add_argument('--bug', '-b',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700411 type=str, help='BUG= line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800412 parser.add_argument('--test', '-t',
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700413 type=str, help='TEST= line')
Stephen Boyd24b309b2018-11-06 22:11:00 -0800414 parser.add_argument('--crbug', action='append',
415 type=int, help='BUG=chromium: line')
416 parser.add_argument('--buganizer', action='append',
417 type=int, help='BUG=b: line')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800418 parser.add_argument('--changeid', '-c',
419 help='Overrides the gerrit generated Change-Id line')
420
Tzung-Bi Shihf5d25a82019-09-02 11:40:09 +0800421 parser.add_argument('--replace', '-r',
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800422 action='store_true',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800423 help='Replaces the HEAD commit with this one, taking '
424 'its properties(BUG, TEST, Change-Id). Useful for '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800425 'updating commits.')
426 parser.add_argument('--nosignoff',
427 dest='signoff', action='store_false')
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800428 parser.add_argument('--debug', '-d', action='store_true',
429 help='Prints more verbose logs.')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800430
431 parser.add_argument('--tag',
432 help='Overrides the tag from the title')
433 parser.add_argument('--source', '-s',
434 dest='source_line', type=str,
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800435 help='Overrides the source line, last line, ex: '
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800436 '(am from http://....)')
437 parser.add_argument('locations',
Douglas Andersonc77a8b82018-05-04 17:02:03 -0700438 nargs='+',
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800439 help='Patchwork ID (pw://### or pw://PROJECT/###, '
440 'where PROJECT is defined in ~/.pwclientrc; if no '
441 'PROJECT is specified, the default is retrieved from '
442 '~/.pwclientrc), '
Stephen Boydb68c17a2019-09-26 15:08:02 -0700443 'Message-ID (msgid://MSGID), '
Brian Norris8043cfd2020-03-19 11:46:16 -0700444 'linux commit like linux://HASH, '
445 'hostap commit like hostap://HASH, or '
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800446 'git reference like git://remote/branch/HASH or '
447 'git://repoURL#branch/HASH or '
Stephen Boyd96396032020-02-25 10:12:59 -0800448 'https://repoURL#branch/HASH or '
449 'https://repoURL/commit/?h=branch&id=HASH')
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800450
451 args = vars(parser.parse_args(args))
452
Stephen Boyd24b309b2018-11-06 22:11:00 -0800453 buglist = [args['bug']] if args['bug'] else []
454 if args['buganizer']:
455 buglist += ['b:{0}'.format(x) for x in args['buganizer']]
456 if args['crbug']:
457 buglist += ['chromium:{0}'.format(x) for x in args['crbug']]
Brian Norris667a0cb2018-12-07 09:28:46 -0800458 if buglist:
459 args['bug'] = ', '.join(buglist)
Stephen Boyd24b309b2018-11-06 22:11:00 -0800460
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800461 if args['replace']:
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800462 old_commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Tzung-Bi Shih231fada2019-09-02 00:54:59 +0800463
464 # It is possible that multiple Change-Ids are in the commit message
465 # (due to cherry picking). We only want to pull out the first one.
466 changeid_match = re.search('^Change-Id: (.*)$',
467 old_commit_message, re.MULTILINE)
468 if changeid_match:
469 args['changeid'] = changeid_match.group(1)
470
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800471 bugs = re.findall('^BUG=(.*)$', old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800472 if args['bug'] is None and bugs:
473 args['bug'] = '\nBUG='.join(bugs)
474
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800475 tests = re.findall('^TEST=(.*)$', old_commit_message, re.MULTILINE)
Tzung-Bi Shih04345302019-09-02 12:04:01 +0800476 if args['test'] is None and tests:
477 args['test'] = '\nTEST='.join(tests)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800478 # TODO: deal with multiline BUG/TEST better
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800479
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700480 if args['bug'] is None or args['test'] is None:
Tzung-Bi Shih196d31e2019-09-01 18:16:28 +0800481 parser.error('BUG=/TEST= lines are required; --replace can help '
Stephen Boyde6fdf912018-11-09 10:30:57 -0800482 'automate, or set via --bug/--test')
Guenter Roeckf47a50c2018-07-25 12:41:36 -0700483
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800484 if args['debug']:
485 pprint.pprint(args)
486
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800487 re_matches = (
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800488 (re.compile(r'^pw://(([^/]+)/)?(\d+)'), _match_patchwork),
Stephen Boydb68c17a2019-09-26 15:08:02 -0700489 (re.compile(r'^msgid://<?([^>]*)>?'), _match_msgid),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800490 (re.compile(r'^linux://([0-9a-f]+)'), _match_linux),
Brian Norris8043cfd2020-03-19 11:46:16 -0700491 (re.compile(r'^hostap://([0-9a-f]+)'), _match_hostap),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800492 (re.compile(r'^(from)?git://([^/\#]+)/([^#]+)/([0-9a-f]+)$'),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800493 _match_fromgit),
Tzung-Bi Shihe1e0e7d2019-09-02 15:04:38 +0800494 (re.compile(r'^((git|https)://.+)#(.+)/([0-9a-f]+)$'), _match_gitfetch),
Stephen Boyd96396032020-02-25 10:12:59 -0800495 (re.compile(r'^(https://.+)/commit/\?h=(.+)\&id=([0-9a-f]+)$'), _match_gitweb),
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800496 )
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800497
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800498 for location in args['locations']:
Tzung-Bi Shih5100c742019-09-02 10:28:32 +0800499 if args['debug']:
500 print('location=%s' % location)
501
Tzung-Bi Shih886c9092019-09-02 12:46:16 +0800502 for reg, handler in re_matches:
503 match = reg.match(location)
504 if match:
505 ret = handler(match, args)
506 break
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800507 else:
Tzung-Bi Shih436fdba2019-09-04 19:05:00 +0800508 errprint('Don\'t know what "%s" means.' % location)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800509 sys.exit(1)
510
511 if ret != 0:
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700512 conflicts = _get_conflicts()
Douglas Anderson2108e532018-04-30 09:50:42 -0700513 if args['tag'] == 'UPSTREAM: ':
514 args['tag'] = 'BACKPORT: '
515 else:
516 args['tag'] = 'BACKPORT: ' + args['tag']
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700517 _pause_for_merge(conflicts)
518 else:
Douglas Andersonb6a10fe2019-08-12 13:53:30 -0700519 conflicts = ''
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800520
521 # extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800522 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800523
Guenter Roeck2e4f2512018-04-24 09:20:51 -0700524 # Remove stray Change-Id, most likely from merge resolution
525 commit_message = re.sub(r'Change-Id:.*\n?', '', commit_message)
526
Brian Norris7a41b982018-06-01 10:28:29 -0700527 # Note the source location before tagging anything else
528 commit_message += '\n' + args['source_line']
529
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800530 # add automatic Change ID, BUG, and TEST (and maybe signoff too) so
531 # next commands know where to work on
532 commit_message += '\n'
Guenter Roeckbdbb9cc2018-04-19 10:05:08 -0700533 commit_message += conflicts
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800534 commit_message += '\n' + 'BUG=' + args['bug']
Harry Cuttsae372f32019-02-12 18:01:14 -0800535 commit_message += '\n' + _wrap_commit_line('TEST', args['test'])
Brian Norris674209e2020-04-22 15:33:53 -0700536
537 extra = []
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800538 if args['signoff']:
Brian Norris674209e2020-04-22 15:33:53 -0700539 signoff = 'Signed-off-by: %s <%s>' % (
540 _git(['config', 'user.name']),
541 _git(['config', 'user.email']))
542 if not signoff in commit_message.splitlines():
543 extra += ['-s']
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800544 _git(['commit'] + extra + ['--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800545
546 # re-extract commit message
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800547 commit_message = _git(['show', '-s', '--format=%B', 'HEAD'])
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800548
Douglas Andersonbecd4e62019-09-25 13:40:55 -0700549 # If we see a "Link: " that seems to point to a Message-Id with an
550 # automatic Change-Id we'll snarf it out.
551 mo = re.search(r'^Link:.*(I[a-f0-9]{40})@changeid', commit_message,
552 re.MULTILINE)
553 if mo and args['changeid'] is None:
554 args['changeid'] = mo.group(1)
555
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800556 # replace changeid if needed
557 if args['changeid'] is not None:
558 commit_message = re.sub(r'(Change-Id: )(\w+)', r'\1%s' %
559 args['changeid'], commit_message)
560 args['changeid'] = None
561
562 # decorate it that it's from outside
563 commit_message = args['tag'] + commit_message
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800564
565 # commit everything
Alexandru M Stan725c71f2019-12-11 16:53:33 -0800566 _git(['commit', '--amend', '-F', '-'], stdin=commit_message)
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800567
Chirantan Ekbote4b08e712019-06-12 15:35:41 +0900568 return 0
Alexandru M Stanfb5b5ee2014-12-04 13:32:55 -0800569
570if __name__ == '__main__':
571 sys.exit(main(sys.argv[1:]))