blob: 18434af4cb71626c2049e1cc27fcc2cab6c647fd [file] [log] [blame]
Simon Glass22ce6412023-11-04 10:25:20 -06001# SPDX-License-Identifier: GPL-2.0+
2#
3# Copyright 2023 Google LLC
4#
5
6"""Handles parsing of buildman arguments
7
8This creates the argument parser and uses it to parse the arguments passed in
9"""
10
11import argparse
12import os
13import pathlib
14import sys
15
Simon Glassba1b3b92025-02-09 14:26:00 -070016from u_boot_pylib import gitutil
Simon Glass44ecdd42025-05-08 06:21:33 +020017from patman import project
Simon Glass22ce6412023-11-04 10:25:20 -060018from patman import settings
19
20PATMAN_DIR = pathlib.Path(__file__).parent
21HAS_TESTS = os.path.exists(PATMAN_DIR / "func_test.py")
22
Simon Glass55d335f2025-05-10 13:05:13 +020023# Aliases for subcommands
24ALIASES = {
25 'status': ['st'],
26 'patchwork': ['pw'],
27 }
Simon Glass22ce6412023-11-04 10:25:20 -060028
Simon Glassd9ec7472025-05-10 13:05:07 +020029class ErrorCatchingArgumentParser(argparse.ArgumentParser):
30 def __init__(self, **kwargs):
31 self.exit_state = None
32 self.catch_error = False
33 super().__init__(**kwargs)
34
35 def error(self, message):
36 if self.catch_error:
37 self.message = message
38 else:
39 super().error(message)
40
41 def exit(self, status=0, message=None):
42 if self.catch_error:
43 self.exit_state = True
44 else:
45 super().exit(status, message)
46
47
Simon Glass44ecdd42025-05-08 06:21:33 +020048def add_send_args(par):
49 """Add arguments for the 'send' command
Simon Glass22ce6412023-11-04 10:25:20 -060050
Simon Glass44ecdd42025-05-08 06:21:33 +020051 Arguments:
52 par (ArgumentParser): Parser to add to
Simon Glasse55a11c2025-05-08 06:09:46 +020053 """
Simon Glass44ecdd42025-05-08 06:21:33 +020054 par.add_argument(
55 '-c', '--count', dest='count', type=int, default=-1,
56 help='Automatically create patches from top n commits')
57 par.add_argument(
58 '-e', '--end', type=int, default=0,
59 help='Commits to skip at end of patch list')
60 par.add_argument(
Simon Glasse55a11c2025-05-08 06:09:46 +020061 '-i', '--ignore-errors', action='store_true',
62 dest='ignore_errors', default=False,
63 help='Send patches email even if patch errors are found')
Simon Glass44ecdd42025-05-08 06:21:33 +020064 par.add_argument(
Simon Glasse55a11c2025-05-08 06:09:46 +020065 '-l', '--limit-cc', dest='limit', type=int, default=None,
66 help='Limit the cc list to LIMIT entries [default: %(default)s]')
Simon Glass44ecdd42025-05-08 06:21:33 +020067 par.add_argument(
Simon Glasse55a11c2025-05-08 06:09:46 +020068 '-m', '--no-maintainers', action='store_false',
69 dest='add_maintainers', default=True,
70 help="Don't cc the file maintainers automatically")
Simon Glass0e43cad2025-05-10 13:04:55 +020071 default_arg = None
72 top_level = gitutil.get_top_level()
73 if top_level:
74 default_arg = os.path.join(top_level, 'scripts',
75 'get_maintainer.pl') + ' --norolestats'
Simon Glass44ecdd42025-05-08 06:21:33 +020076 par.add_argument(
Simon Glass22ce6412023-11-04 10:25:20 -060077 '--get-maintainer-script', dest='get_maintainer_script', type=str,
78 action='store',
Simon Glass0e43cad2025-05-10 13:04:55 +020079 default=default_arg,
Simon Glass22ce6412023-11-04 10:25:20 -060080 help='File name of the get_maintainer.pl (or compatible) script.')
Simon Glass44ecdd42025-05-08 06:21:33 +020081 par.add_argument(
82 '-r', '--in-reply-to', type=str, action='store',
83 help="Message ID that this series is in reply to")
84 par.add_argument(
85 '-s', '--start', dest='start', type=int, default=0,
86 help='Commit to start creating patches from (0 = HEAD)')
87 par.add_argument(
88 '-t', '--ignore-bad-tags', action='store_true', default=False,
89 help='Ignore bad tags / aliases (default=warn)')
90 par.add_argument(
91 '--no-binary', action='store_true', dest='ignore_binary',
92 default=False,
93 help="Do not output contents of changes in binary files")
94 par.add_argument(
95 '--no-check', action='store_false', dest='check_patch', default=True,
96 help="Don't check for patch compliance")
97 par.add_argument(
Simon Glass22ce6412023-11-04 10:25:20 -060098 '--tree', dest='check_patch_use_tree', default=False,
99 action='store_true',
100 help=("Set `tree` to True. If `tree` is False then we'll pass "
101 "'--no-tree' to checkpatch (default: tree=%(default)s)"))
Simon Glass44ecdd42025-05-08 06:21:33 +0200102 par.add_argument(
103 '--no-tree', dest='check_patch_use_tree', action='store_false',
104 help="Set `tree` to False")
105 par.add_argument(
Simon Glass22ce6412023-11-04 10:25:20 -0600106 '--no-tags', action='store_false', dest='process_tags', default=True,
107 help="Don't process subject tags as aliases")
Simon Glass44ecdd42025-05-08 06:21:33 +0200108 par.add_argument(
109 '--no-signoff', action='store_false', dest='add_signoff',
110 default=True, help="Don't add Signed-off-by to patches")
111 par.add_argument(
112 '--smtp-server', type=str,
113 help="Specify the SMTP server to 'git send-email'")
114 par.add_argument(
115 '--keep-change-id', action='store_true',
116 help='Preserve Change-Id tags in patches to send.')
Simon Glass22ce6412023-11-04 10:25:20 -0600117
Simon Glass44ecdd42025-05-08 06:21:33 +0200118
Simon Glasse9f14cd2025-05-10 13:05:08 +0200119def _add_show_comments(parser):
120 parser.add_argument('-c', '--show-comments', action='store_true',
121 help='Show comments from each patch')
122
123
Simon Glassbe7e6c02025-05-10 13:05:12 +0200124def add_patchwork_subparser(subparsers):
125 """Add the 'patchwork' subparser
126
127 Args:
128 subparsers (argparse action): Subparser parent
129
130 Return:
131 ArgumentParser: patchwork subparser
132 """
133 patchwork = subparsers.add_parser(
Simon Glass55d335f2025-05-10 13:05:13 +0200134 'patchwork', aliases=ALIASES['patchwork'],
Simon Glassbe7e6c02025-05-10 13:05:12 +0200135 help='Manage patchwork connection')
136 patchwork.defaults_cmds = [
137 ['set-project', 'U-Boot'],
138 ]
139 patchwork_subparsers = patchwork.add_subparsers(dest='subcmd')
140 patchwork_subparsers.add_parser('get-project')
141 uset = patchwork_subparsers.add_parser('set-project')
142 uset.add_argument(
143 'project_name', help="Patchwork project name, e.g. 'U-Boot'")
144 return patchwork
145
146
Simon Glass44ecdd42025-05-08 06:21:33 +0200147def add_send_subparser(subparsers):
148 """Add the 'send' subparser
149
150 Args:
151 subparsers (argparse action): Subparser parent
152
153 Return:
154 ArgumentParser: send subparser
155 """
156 send = subparsers.add_parser(
157 'send', help='Format, check and email patches (default command)')
158 send.add_argument(
159 '-b', '--branch', type=str,
160 help="Branch to process (by default, the current branch)")
161 send.add_argument(
162 '-n', '--dry-run', action='store_true', dest='dry_run',
163 default=False, help="Do a dry run (create but don't email patches)")
164 send.add_argument(
165 '--cc-cmd', dest='cc_cmd', type=str, action='store',
166 default=None, help='Output cc list for patch file (used by git)')
167 add_send_args(send)
Simon Glass22ce6412023-11-04 10:25:20 -0600168 send.add_argument('patchfiles', nargs='*')
Simon Glasse55a11c2025-05-08 06:09:46 +0200169 return send
Simon Glass22ce6412023-11-04 10:25:20 -0600170
Simon Glasse55a11c2025-05-08 06:09:46 +0200171
172def add_status_subparser(subparsers):
173 """Add the 'status' subparser
174
175 Args:
176 subparsers (argparse action): Subparser parent
Simon Glass22ce6412023-11-04 10:25:20 -0600177
Simon Glasse55a11c2025-05-08 06:09:46 +0200178 Return:
179 ArgumentParser: status subparser
180 """
Simon Glass55d335f2025-05-10 13:05:13 +0200181 status = subparsers.add_parser('status', aliases=ALIASES['status'],
Simon Glass22ce6412023-11-04 10:25:20 -0600182 help='Check status of patches in patchwork')
Simon Glasse9f14cd2025-05-10 13:05:08 +0200183 _add_show_comments(status)
Simon Glass22ce6412023-11-04 10:25:20 -0600184 status.add_argument(
185 '-d', '--dest-branch', type=str,
186 help='Name of branch to create with collected responses')
187 status.add_argument('-f', '--force', action='store_true',
188 help='Force overwriting an existing branch')
Simon Glass802eeea2025-04-29 07:22:25 -0600189 status.add_argument('-T', '--single-thread', action='store_true',
190 help='Disable multithreading when reading patchwork')
Simon Glasse55a11c2025-05-08 06:09:46 +0200191 return status
192
193
194def setup_parser():
195 """Set up command-line parser
196
197 Returns:
198 argparse.Parser object
199 """
200 epilog = '''Create patches from commits in a branch, check them and email
201 them as specified by tags you place in the commits. Use -n to do a dry
202 run first.'''
203
Simon Glassd9ec7472025-05-10 13:05:07 +0200204 parser = ErrorCatchingArgumentParser(epilog=epilog)
Simon Glass44ecdd42025-05-08 06:21:33 +0200205 parser.add_argument(
206 '-D', '--debug', action='store_true',
Simon Glasse55a11c2025-05-08 06:09:46 +0200207 help='Enabling debugging (provides a full traceback on error)')
208 parser.add_argument(
209 '-N', '--no-capture', action='store_true',
210 help='Disable capturing of console output in tests')
211 parser.add_argument('-p', '--project', default=project.detect_project(),
212 help="Project name; affects default option values and "
213 "aliases [default: %(default)s]")
214 parser.add_argument('-P', '--patchwork-url',
215 default='https://patchwork.ozlabs.org',
216 help='URL of patchwork server [default: %(default)s]')
Simon Glass44ecdd42025-05-08 06:21:33 +0200217 parser.add_argument(
218 '-T', '--thread', action='store_true', dest='thread',
219 default=False, help='Create patches as a single thread')
Simon Glasse55a11c2025-05-08 06:09:46 +0200220 parser.add_argument(
221 '-v', '--verbose', action='store_true', dest='verbose', default=False,
222 help='Verbose output of errors and warnings')
223 parser.add_argument(
224 '-X', '--test-preserve-dirs', action='store_true',
225 help='Preserve and display test-created directories')
226 parser.add_argument(
227 '-H', '--full-help', action='store_true', dest='full_help',
228 default=False, help='Display the README file')
229
230 subparsers = parser.add_subparsers(dest='cmd')
231 add_send_subparser(subparsers)
Simon Glassbe7e6c02025-05-10 13:05:12 +0200232 patchwork = add_patchwork_subparser(subparsers)
Simon Glasse55a11c2025-05-08 06:09:46 +0200233 add_status_subparser(subparsers)
234
235 # Only add the 'test' action if the test data files are available.
236 if HAS_TESTS:
237 test_parser = subparsers.add_parser('test', help='Run tests')
238 test_parser.add_argument('testname', type=str, default=None, nargs='?',
239 help="Specify the test to run")
240
Simon Glass65a45792025-05-10 13:05:09 +0200241 parsers = {
242 'main': parser,
Simon Glassbe7e6c02025-05-10 13:05:12 +0200243 'patchwork': patchwork,
Simon Glass65a45792025-05-10 13:05:09 +0200244 }
245 return parsers
Simon Glass8b521cf2025-05-08 05:58:10 +0200246
247
Simon Glass65a45792025-05-10 13:05:09 +0200248def parse_args(argv=None, config_fname=None, parsers=None):
Simon Glass8b521cf2025-05-08 05:58:10 +0200249 """Parse command line arguments from sys.argv[]
250
251 Args:
252 argv (str or None): Arguments to process, or None to use sys.argv[1:]
253 config_fname (str): Config file to read, or None for default, or False
254 for an empty config
255
256 Returns:
257 tuple containing:
258 options: command line options
259 args: command lin arguments
260 """
Simon Glass65a45792025-05-10 13:05:09 +0200261 if not parsers:
262 parsers = setup_parser()
263 parser = parsers['main']
Simon Glass22ce6412023-11-04 10:25:20 -0600264
265 # Parse options twice: first to get the project and second to handle
266 # defaults properly (which depends on project)
267 # Use parse_known_args() in case 'cmd' is omitted
Simon Glass8b521cf2025-05-08 05:58:10 +0200268 if not argv:
269 argv = sys.argv[1:]
270
Simon Glass22ce6412023-11-04 10:25:20 -0600271 args, rest = parser.parse_known_args(argv)
272 if hasattr(args, 'project'):
Simon Glass8b521cf2025-05-08 05:58:10 +0200273 settings.Setup(parser, args.project, argv, config_fname)
Simon Glass22ce6412023-11-04 10:25:20 -0600274 args, rest = parser.parse_known_args(argv)
275
276 # If we have a command, it is safe to parse all arguments
277 if args.cmd:
278 args = parser.parse_args(argv)
Simon Glassb8a14f92025-05-08 06:30:14 +0200279 elif not args.full_help:
Simon Glass22ce6412023-11-04 10:25:20 -0600280 # No command, so insert it after the known arguments and before the ones
281 # that presumably relate to the 'send' subcommand
282 nargs = len(rest)
283 argv = argv[:-nargs] + ['send'] + rest
284 args = parser.parse_args(argv)
285
Simon Glass55d335f2025-05-10 13:05:13 +0200286 # Resolve aliases
287 for full, aliases in ALIASES.items():
288 if args.cmd in aliases:
289 args.cmd = full
290 if 'subcmd' in args and args.subcmd in aliases:
291 args.subcmd = full
292 if args.cmd in ['series', 'upstream', 'patchwork'] and not args.subcmd:
293 parser.parse_args([args.cmd, '--help'])
294
Simon Glass22ce6412023-11-04 10:25:20 -0600295 return args