blob: 5b335831faf6e427665fb231d169e93362bc81b3 [file] [log] [blame]
Tarek Ziade1231a4e2011-05-19 13:07:25 +02001"""Main command line parser. Implements the pysetup script."""
2
3import os
4import re
5import sys
6import getopt
7import logging
8
9from packaging import logger
10from packaging.dist import Distribution
Tarek Ziade721ccd02011-06-02 12:00:44 +020011from packaging.util import _is_archive_file, generate_setup_py
Tarek Ziade1231a4e2011-05-19 13:07:25 +020012from packaging.command import get_command_class, STANDARD_COMMANDS
13from packaging.install import install, install_local_project, remove
14from packaging.database import get_distribution, get_distributions
15from packaging.depgraph import generate_graph
16from packaging.fancy_getopt import FancyGetopt
17from packaging.errors import (PackagingArgError, PackagingError,
18 PackagingModuleError, PackagingClassError,
19 CCompilerError)
20
21
22command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
23
24common_usage = """\
25Actions:
26%(actions)s
27
28To get more help on an action, use:
29
30 pysetup action --help
31"""
32
33create_usage = """\
34Usage: pysetup create
35 or: pysetup create --help
36
Éric Araujo18efecf2011-06-04 22:33:59 +020037Create a new Python project.
Tarek Ziade1231a4e2011-05-19 13:07:25 +020038"""
39
Tarek Ziade721ccd02011-06-02 12:00:44 +020040generate_usage = """\
41Usage: pysetup generate-setup
42 or: pysetup generate-setup --help
43
Éric Araujo18efecf2011-06-04 22:33:59 +020044Generate a setup.py script for backward-compatibility purposes.
Tarek Ziade721ccd02011-06-02 12:00:44 +020045"""
46
47
Tarek Ziade1231a4e2011-05-19 13:07:25 +020048graph_usage = """\
49Usage: pysetup graph dist
50 or: pysetup graph --help
51
52Print dependency graph for the distribution.
53
54positional arguments:
55 dist installed distribution name
56"""
57
58install_usage = """\
59Usage: pysetup install [dist]
60 or: pysetup install [archive]
61 or: pysetup install [src_dir]
62 or: pysetup install --help
63
64Install a Python distribution from the indexes, source directory, or sdist.
65
66positional arguments:
67 archive path to source distribution (zip, tar.gz)
68 dist distribution name to install from the indexes
69 scr_dir path to source directory
70
71"""
72
73metadata_usage = """\
Éric Araujofb639292011-08-29 22:03:46 +020074Usage: pysetup metadata [dist]
75 or: pysetup metadata [dist] [-f field ...]
Tarek Ziade1231a4e2011-05-19 13:07:25 +020076 or: pysetup metadata --help
77
78Print metadata for the distribution.
79
80positional arguments:
81 dist installed distribution name
82
83optional arguments:
Éric Araujofb639292011-08-29 22:03:46 +020084 -f metadata field to print; omit to get all fields
Tarek Ziade1231a4e2011-05-19 13:07:25 +020085"""
86
87remove_usage = """\
88Usage: pysetup remove dist [-y]
89 or: pysetup remove --help
90
91Uninstall a Python distribution.
92
93positional arguments:
94 dist installed distribution name
95
96optional arguments:
Éric Araujo18efecf2011-06-04 22:33:59 +020097 -y auto confirm distribution removal
Tarek Ziade1231a4e2011-05-19 13:07:25 +020098"""
99
100run_usage = """\
101Usage: pysetup run [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
102 or: pysetup run --help
103 or: pysetup run --list-commands
104 or: pysetup run cmd --help
105"""
106
107list_usage = """\
108Usage: pysetup list dist [dist ...]
109 or: pysetup list --help
110 or: pysetup list --all
111
112Print name, version and location for the matching installed distributions.
113
114positional arguments:
115 dist installed distribution name
116
117optional arguments:
118 --all list all installed distributions
119"""
120
121search_usage = """\
122Usage: pysetup search [project] [--simple [url]] [--xmlrpc [url] [--fieldname value ...] --operator or|and]
123 or: pysetup search --help
124
125Search the indexes for the matching projects.
126
127positional arguments:
128 project the project pattern to search for
129
130optional arguments:
131 --xmlrpc [url] wether to use the xmlrpc index or not. If an url is
132 specified, it will be used rather than the default one.
133
134 --simple [url] wether to use the simple index or not. If an url is
135 specified, it will be used rather than the default one.
136
137 --fieldname value Make a search on this field. Can only be used if
138 --xmlrpc has been selected or is the default index.
139
140 --operator or|and Defines what is the operator to use when doing xmlrpc
141 searchs with multiple fieldnames. Can only be used if
142 --xmlrpc has been selected or is the default index.
143"""
144
145global_options = [
146 # The fourth entry for verbose means that it can be repeated.
147 ('verbose', 'v', "run verbosely (default)", True),
148 ('quiet', 'q', "run quietly (turns verbosity off)"),
149 ('dry-run', 'n', "don't actually do anything"),
150 ('help', 'h', "show detailed help message"),
151 ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
152 ('version', None, 'Display the version'),
153]
154
155negative_opt = {'quiet': 'verbose'}
156
157display_options = [
158 ('help-commands', None, "list all available commands"),
159]
160
161display_option_names = [x[0].replace('-', '_') for x in display_options]
162
163
164def _parse_args(args, options, long_options):
165 """Transform sys.argv input into a dict.
166
167 :param args: the args to parse (i.e sys.argv)
168 :param options: the list of options to pass to getopt
169 :param long_options: the list of string with the names of the long options
170 to be passed to getopt.
171
172 The function returns a dict with options/long_options as keys and matching
173 values as values.
174 """
175 optlist, args = getopt.gnu_getopt(args, options, long_options)
176 optdict = {}
177 optdict['args'] = args
178 for k, v in optlist:
179 k = k.lstrip('-')
180 if k not in optdict:
181 optdict[k] = []
182 if v:
183 optdict[k].append(v)
184 else:
185 optdict[k].append(v)
186 return optdict
187
188
189class action_help:
190 """Prints a help message when the standard help flags: -h and --help
191 are used on the commandline.
192 """
193
194 def __init__(self, help_msg):
195 self.help_msg = help_msg
196
197 def __call__(self, f):
198 def wrapper(*args, **kwargs):
199 f_args = args[1]
200 if '--help' in f_args or '-h' in f_args:
201 print(self.help_msg)
202 return
203 return f(*args, **kwargs)
204 return wrapper
205
206
207@action_help(create_usage)
208def _create(distpatcher, args, **kw):
209 from packaging.create import main
210 return main()
211
212
Tarek Ziade721ccd02011-06-02 12:00:44 +0200213@action_help(generate_usage)
214def _generate(distpatcher, args, **kw):
215 generate_setup_py()
Éric Araujo943006b2011-07-29 02:31:39 +0200216 logger.info('The setup.py was generated')
Tarek Ziade721ccd02011-06-02 12:00:44 +0200217
218
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200219@action_help(graph_usage)
220def _graph(dispatcher, args, **kw):
221 name = args[1]
222 dist = get_distribution(name, use_egg_info=True)
223 if dist is None:
Éric Araujo943006b2011-07-29 02:31:39 +0200224 logger.warning('Distribution not found.')
225 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200226 else:
227 dists = get_distributions(use_egg_info=True)
228 graph = generate_graph(dists)
229 print(graph.repr_node(dist))
230
231
232@action_help(install_usage)
233def _install(dispatcher, args, **kw):
234 # first check if we are in a source directory
235 if len(args) < 2:
236 # are we inside a project dir?
Éric Araujo943006b2011-07-29 02:31:39 +0200237 if os.path.isfile('setup.cfg') or os.path.isfile('setup.py'):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200238 args.insert(1, os.getcwd())
239 else:
Tarek Ziade5a5ce382011-05-31 12:09:34 +0200240 logger.warning('No project to install.')
241 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200242
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200243 target = args[1]
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200244 # installing from a source dir or archive file?
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200245 if os.path.isdir(target) or _is_archive_file(target):
Éric Araujo943006b2011-07-29 02:31:39 +0200246 return not install_local_project(target)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200247 else:
248 # download from PyPI
Éric Araujo943006b2011-07-29 02:31:39 +0200249 return not install(target)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200250
251
252@action_help(metadata_usage)
253def _metadata(dispatcher, args, **kw):
Éric Araujofb639292011-08-29 22:03:46 +0200254 opts = _parse_args(args[1:], 'f:', [])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200255 if opts['args']:
256 name = opts['args'][0]
257 dist = get_distribution(name, use_egg_info=True)
258 if dist is None:
Éric Araujo943006b2011-07-29 02:31:39 +0200259 logger.warning('%r not installed', name)
260 return 1
261 elif os.path.isfile('setup.cfg'):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200262 logger.info('searching local dir for metadata')
Éric Araujo943006b2011-07-29 02:31:39 +0200263 dist = Distribution() # XXX use config module
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200264 dist.parse_config_files()
Éric Araujo943006b2011-07-29 02:31:39 +0200265 else:
266 logger.warning('no argument given and no local setup.cfg found')
267 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200268
269 metadata = dist.metadata
270
Éric Araujofb639292011-08-29 22:03:46 +0200271 if 'f' in opts:
272 keys = (k for k in opts['f'] if k in metadata)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200273 else:
Éric Araujofb639292011-08-29 22:03:46 +0200274 keys = metadata.keys()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200275
276 for key in keys:
277 if key in metadata:
278 print(metadata._convert_name(key) + ':')
279 value = metadata[key]
280 if isinstance(value, list):
281 for v in value:
Éric Araujo3cab2f12011-06-08 04:10:57 +0200282 print(' ', v)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200283 else:
Éric Araujo3cab2f12011-06-08 04:10:57 +0200284 print(' ', value.replace('\n', '\n '))
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200285
286
287@action_help(remove_usage)
288def _remove(distpatcher, args, **kw):
289 opts = _parse_args(args[1:], 'y', [])
290 if 'y' in opts:
291 auto_confirm = True
292 else:
293 auto_confirm = False
294
Éric Araujo943006b2011-07-29 02:31:39 +0200295 retcode = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200296 for dist in set(opts['args']):
297 try:
298 remove(dist, auto_confirm=auto_confirm)
299 except PackagingError:
Éric Araujo943006b2011-07-29 02:31:39 +0200300 logger.warning('%r not installed', dist)
301 retcode = 1
302
303 return retcode
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200304
305
306@action_help(run_usage)
307def _run(dispatcher, args, **kw):
308 parser = dispatcher.parser
309 args = args[1:]
310
311 commands = STANDARD_COMMANDS # + extra commands
312
313 if args == ['--list-commands']:
314 print('List of available commands:')
315 cmds = sorted(commands)
316
317 for cmd in cmds:
318 cls = dispatcher.cmdclass.get(cmd) or get_command_class(cmd)
319 desc = getattr(cls, 'description',
320 '(no description available)')
321 print(' %s: %s' % (cmd, desc))
322 return
323
324 while args:
325 args = dispatcher._parse_command_opts(parser, args)
326 if args is None:
327 return
328
329 # create the Distribution class
330 # need to feed setup.cfg here !
331 dist = Distribution()
332
333 # Find and parse the config file(s): they will override options from
334 # the setup script, but be overridden by the command line.
335
336 # XXX still need to be extracted from Distribution
337 dist.parse_config_files()
338
Éric Araujo943006b2011-07-29 02:31:39 +0200339 for cmd in dispatcher.commands:
340 dist.run_command(cmd, dispatcher.command_options[cmd])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200341
342 # XXX this is crappy
343 return dist
344
345
346@action_help(list_usage)
347def _list(dispatcher, args, **kw):
348 opts = _parse_args(args[1:], '', ['all'])
349 dists = get_distributions(use_egg_info=True)
Tarek Ziade441531f2011-05-31 09:18:24 +0200350 if 'all' in opts or opts['args'] == []:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200351 results = dists
Éric Araujo73c175f2011-07-29 02:20:39 +0200352 listall = True
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200353 else:
Éric Araujo943006b2011-07-29 02:31:39 +0200354 results = (d for d in dists if d.name.lower() in opts['args'])
Éric Araujo73c175f2011-07-29 02:20:39 +0200355 listall = False
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200356
Tarek Ziade441531f2011-05-31 09:18:24 +0200357 number = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200358 for dist in results:
Éric Araujo943006b2011-07-29 02:31:39 +0200359 print('%r %s (from %r)' % (dist.name, dist.version, dist.path))
Tarek Ziadee2655972011-05-31 12:15:42 +0200360 number += 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200361
Tarek Ziade441531f2011-05-31 09:18:24 +0200362 if number == 0:
Éric Araujo73c175f2011-07-29 02:20:39 +0200363 if listall:
Éric Araujo943006b2011-07-29 02:31:39 +0200364 logger.info('Nothing seems to be installed.')
Éric Araujo73c175f2011-07-29 02:20:39 +0200365 else:
Éric Araujo943006b2011-07-29 02:31:39 +0200366 logger.warning('No matching distribution found.')
Éric Araujo73c175f2011-07-29 02:20:39 +0200367 return 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200368 else:
Éric Araujo943006b2011-07-29 02:31:39 +0200369 logger.info('Found %d projects installed.', number)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200370
371
372@action_help(search_usage)
373def _search(dispatcher, args, **kw):
374 """The search action.
375
376 It is able to search for a specific index (specified with --index), using
377 the simple or xmlrpc index types (with --type xmlrpc / --type simple)
378 """
Tarek Ziadee2655972011-05-31 12:15:42 +0200379 #opts = _parse_args(args[1:], '', ['simple', 'xmlrpc'])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200380 # 1. what kind of index is requested ? (xmlrpc / simple)
Éric Araujo943006b2011-07-29 02:31:39 +0200381 logger.error('not implemented')
382 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200383
384
385actions = [
386 ('run', 'Run one or several commands', _run),
387 ('metadata', 'Display the metadata of a project', _metadata),
388 ('install', 'Install a project', _install),
389 ('remove', 'Remove a project', _remove),
390 ('search', 'Search for a project in the indexes', _search),
Éric Araujo18efecf2011-06-04 22:33:59 +0200391 ('list', 'List installed releases', _list),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200392 ('graph', 'Display a graph', _graph),
Éric Araujo18efecf2011-06-04 22:33:59 +0200393 ('create', 'Create a project', _create),
394 ('generate-setup', 'Generate a backward-comptatible setup.py', _generate),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200395]
396
397
398class Dispatcher:
399 """Reads the command-line options
400 """
401 def __init__(self, args=None):
402 self.verbose = 1
403 self.dry_run = False
404 self.help = False
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200405 self.cmdclass = {}
406 self.commands = []
407 self.command_options = {}
408
409 for attr in display_option_names:
410 setattr(self, attr, False)
411
412 self.parser = FancyGetopt(global_options + display_options)
413 self.parser.set_negative_aliases(negative_opt)
414 # FIXME this parses everything, including command options (e.g. "run
415 # build -i" errors with "option -i not recognized")
416 args = self.parser.getopt(args=args, object=self)
417
418 # if first arg is "run", we have some commands
419 if len(args) == 0:
420 self.action = None
421 else:
422 self.action = args[0]
423
424 allowed = [action[0] for action in actions] + [None]
425 if self.action not in allowed:
426 msg = 'Unrecognized action "%s"' % self.action
427 raise PackagingArgError(msg)
428
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200429 self._set_logger()
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200430 self.args = args
431
Tarek Ziadee2655972011-05-31 12:15:42 +0200432 # for display options we return immediately
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200433 if self.help or self.action is None:
434 self._show_help(self.parser, display_options_=False)
435
436 def _set_logger(self):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200437 # setting up the logging level from the command-line options
438 # -q gets warning, error and critical
439 if self.verbose == 0:
440 level = logging.WARNING
441 # default level or -v gets info too
442 # XXX there's a bug somewhere: the help text says that -v is default
443 # (and verbose is set to 1 above), but when the user explicitly gives
444 # -v on the command line, self.verbose is incremented to 2! Here we
445 # compensate for that (I tested manually). On a related note, I think
446 # it's a good thing to use -q/nothing/-v/-vv on the command line
447 # instead of logging constants; it will be easy to add support for
448 # logging configuration in setup.cfg for advanced users. --merwok
449 elif self.verbose in (1, 2):
450 level = logging.INFO
451 else: # -vv and more for debug
452 level = logging.DEBUG
453
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200454 # setting up the stream handler
455 handler = logging.StreamHandler(sys.stderr)
456 handler.setLevel(level)
457 logger.addHandler(handler)
458 logger.setLevel(level)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200459
460 def _parse_command_opts(self, parser, args):
461 # Pull the current command from the head of the command line
462 command = args[0]
463 if not command_re.match(command):
464 raise SystemExit("invalid command name %r" % (command,))
465 self.commands.append(command)
466
467 # Dig up the command class that implements this command, so we
468 # 1) know that it's a valid command, and 2) know which options
469 # it takes.
470 try:
471 cmd_class = get_command_class(command)
472 except PackagingModuleError as msg:
473 raise PackagingArgError(msg)
474
475 # XXX We want to push this in packaging.command
476 #
477 # Require that the command class be derived from Command -- want
478 # to be sure that the basic "command" interface is implemented.
479 for meth in ('initialize_options', 'finalize_options', 'run'):
480 if hasattr(cmd_class, meth):
481 continue
482 raise PackagingClassError(
483 'command %r must implement %r' % (cmd_class, meth))
484
485 # Also make sure that the command object provides a list of its
486 # known options.
487 if not (hasattr(cmd_class, 'user_options') and
488 isinstance(cmd_class.user_options, list)):
489 raise PackagingClassError(
490 "command class %s must provide "
491 "'user_options' attribute (a list of tuples)" % cmd_class)
492
493 # If the command class has a list of negative alias options,
494 # merge it in with the global negative aliases.
495 _negative_opt = negative_opt.copy()
496
497 if hasattr(cmd_class, 'negative_opt'):
498 _negative_opt.update(cmd_class.negative_opt)
499
500 # Check for help_options in command class. They have a different
501 # format (tuple of four) so we need to preprocess them here.
502 if (hasattr(cmd_class, 'help_options') and
503 isinstance(cmd_class.help_options, list)):
504 help_options = cmd_class.help_options[:]
505 else:
506 help_options = []
507
508 # All commands support the global options too, just by adding
509 # in 'global_options'.
510 parser.set_option_table(global_options +
511 cmd_class.user_options +
512 help_options)
513 parser.set_negative_aliases(_negative_opt)
514 args, opts = parser.getopt(args[1:])
515
516 if hasattr(opts, 'help') and opts.help:
517 self._show_command_help(cmd_class)
518 return
519
520 if (hasattr(cmd_class, 'help_options') and
521 isinstance(cmd_class.help_options, list)):
522 help_option_found = False
523 for help_option, short, desc, func in cmd_class.help_options:
524 if hasattr(opts, help_option.replace('-', '_')):
525 help_option_found = True
526 if hasattr(func, '__call__'):
527 func()
528 else:
529 raise PackagingClassError(
530 "invalid help function %r for help option %r: "
531 "must be a callable object (function, etc.)"
532 % (func, help_option))
533
534 if help_option_found:
535 return
536
537 # Put the options from the command line into their official
538 # holding pen, the 'command_options' dictionary.
539 opt_dict = self.get_option_dict(command)
540 for name, value in vars(opts).items():
541 opt_dict[name] = ("command line", value)
542
543 return args
544
545 def get_option_dict(self, command):
546 """Get the option dictionary for a given command. If that
547 command's option dictionary hasn't been created yet, then create it
548 and return the new dictionary; otherwise, return the existing
549 option dictionary.
550 """
551 d = self.command_options.get(command)
552 if d is None:
553 d = self.command_options[command] = {}
554 return d
555
556 def show_help(self):
557 self._show_help(self.parser)
558
559 def print_usage(self, parser):
560 parser.set_option_table(global_options)
561
562 actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions]
563 usage = common_usage % {'actions': '\n'.join(actions_)}
564
565 parser.print_help(usage + "\nGlobal options:")
566
567 def _show_help(self, parser, global_options_=True, display_options_=True,
568 commands=[]):
569 # late import because of mutual dependence between these modules
570 from packaging.command.cmd import Command
571
572 print('Usage: pysetup [options] action [action_options]')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200573 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200574 if global_options_:
575 self.print_usage(self.parser)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200576 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200577
578 if display_options_:
579 parser.set_option_table(display_options)
580 parser.print_help(
581 "Information display options (just display " +
582 "information, ignore any commands)")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200583 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200584
585 for command in commands:
586 if isinstance(command, type) and issubclass(command, Command):
587 cls = command
588 else:
589 cls = get_command_class(command)
590 if (hasattr(cls, 'help_options') and
591 isinstance(cls.help_options, list)):
592 parser.set_option_table(cls.user_options + cls.help_options)
593 else:
594 parser.set_option_table(cls.user_options)
595
596 parser.print_help("Options for %r command:" % cls.__name__)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200597 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200598
599 def _show_command_help(self, command):
600 if isinstance(command, str):
601 command = get_command_class(command)
602
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200603 desc = getattr(command, 'description', '(no description available)')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200604 print('Description:', desc)
605 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200606
607 if (hasattr(command, 'help_options') and
608 isinstance(command.help_options, list)):
609 self.parser.set_option_table(command.user_options +
610 command.help_options)
611 else:
612 self.parser.set_option_table(command.user_options)
613
614 self.parser.print_help("Options:")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200615 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200616
617 def _get_command_groups(self):
618 """Helper function to retrieve all the command class names divided
619 into standard commands (listed in
620 packaging.command.STANDARD_COMMANDS) and extra commands (given in
621 self.cmdclass and not standard commands).
622 """
623 extra_commands = [cmd for cmd in self.cmdclass
624 if cmd not in STANDARD_COMMANDS]
625 return STANDARD_COMMANDS, extra_commands
626
627 def print_commands(self):
628 """Print out a help message listing all available commands with a
629 description of each. The list is divided into standard commands
630 (listed in packaging.command.STANDARD_COMMANDS) and extra commands
631 (given in self.cmdclass and not standard commands). The
632 descriptions come from the command class attribute
633 'description'.
634 """
635 std_commands, extra_commands = self._get_command_groups()
636 max_length = max(len(command)
637 for commands in (std_commands, extra_commands)
638 for command in commands)
639
640 self.print_command_list(std_commands, "Standard commands", max_length)
641 if extra_commands:
642 print()
643 self.print_command_list(extra_commands, "Extra commands",
644 max_length)
645
646 def print_command_list(self, commands, header, max_length):
647 """Print a subset of the list of all commands -- used by
648 'print_commands()'.
649 """
650 print(header + ":")
651
652 for cmd in commands:
653 cls = self.cmdclass.get(cmd) or get_command_class(cmd)
654 description = getattr(cls, 'description',
655 '(no description available)')
656
657 print(" %-*s %s" % (max_length, cmd, description))
658
659 def __call__(self):
660 if self.action is None:
661 return
Éric Araujo943006b2011-07-29 02:31:39 +0200662
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200663 for action, desc, func in actions:
664 if action == self.action:
665 return func(self, self.args)
666 return -1
667
668
669def main(args=None):
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200670 old_level = logger.level
Éric Araujo088025f2011-06-04 18:45:40 +0200671 old_handlers = list(logger.handlers)
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200672 try:
673 dispatcher = Dispatcher(args)
674 if dispatcher.action is None:
675 return
676 return dispatcher()
Éric Araujo943006b2011-07-29 02:31:39 +0200677 except KeyboardInterrupt:
678 logger.info('interrupted')
679 return 1
680 except (IOError, os.error, PackagingError, CCompilerError) as exc:
681 logger.exception(exc)
682 return 1
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200683 finally:
684 logger.setLevel(old_level)
685 logger.handlers[:] = old_handlers
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200686
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200687
688if __name__ == '__main__':
689 sys.exit(main())