blob: 5affb17974ff262318048ad76eb53f0f7a2c3b74 [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
Tarek Ziade1231a4e2011-05-19 13:07:25 +020033global_options = [
34 # The fourth entry for verbose means that it can be repeated.
35 ('verbose', 'v', "run verbosely (default)", True),
36 ('quiet', 'q', "run quietly (turns verbosity off)"),
37 ('dry-run', 'n', "don't actually do anything"),
38 ('help', 'h', "show detailed help message"),
39 ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
40 ('version', None, 'Display the version'),
41]
42
43negative_opt = {'quiet': 'verbose'}
44
45display_options = [
46 ('help-commands', None, "list all available commands"),
47]
48
49display_option_names = [x[0].replace('-', '_') for x in display_options]
50
51
52def _parse_args(args, options, long_options):
53 """Transform sys.argv input into a dict.
54
55 :param args: the args to parse (i.e sys.argv)
56 :param options: the list of options to pass to getopt
57 :param long_options: the list of string with the names of the long options
58 to be passed to getopt.
59
60 The function returns a dict with options/long_options as keys and matching
61 values as values.
62 """
63 optlist, args = getopt.gnu_getopt(args, options, long_options)
64 optdict = {}
65 optdict['args'] = args
66 for k, v in optlist:
67 k = k.lstrip('-')
68 if k not in optdict:
69 optdict[k] = []
70 if v:
71 optdict[k].append(v)
72 else:
73 optdict[k].append(v)
74 return optdict
75
76
77class action_help:
78 """Prints a help message when the standard help flags: -h and --help
79 are used on the commandline.
80 """
81
82 def __init__(self, help_msg):
83 self.help_msg = help_msg
84
85 def __call__(self, f):
86 def wrapper(*args, **kwargs):
87 f_args = args[1]
88 if '--help' in f_args or '-h' in f_args:
89 print(self.help_msg)
90 return
91 return f(*args, **kwargs)
92 return wrapper
93
94
Éric Araujo3f184f52011-08-30 22:23:52 +020095@action_help("""\
96Usage: pysetup create
97 or: pysetup create --help
98
99Create a new Python project.
100""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200101def _create(distpatcher, args, **kw):
102 from packaging.create import main
103 return main()
104
105
Éric Araujo3f184f52011-08-30 22:23:52 +0200106@action_help("""\
107Usage: pysetup generate-setup
108 or: pysetup generate-setup --help
109
110Generate a setup.py script for backward-compatibility purposes.
111""")
Tarek Ziade721ccd02011-06-02 12:00:44 +0200112def _generate(distpatcher, args, **kw):
113 generate_setup_py()
Éric Araujo943006bf2011-07-29 02:31:39 +0200114 logger.info('The setup.py was generated')
Tarek Ziade721ccd02011-06-02 12:00:44 +0200115
116
Éric Araujo3f184f52011-08-30 22:23:52 +0200117@action_help("""\
118Usage: pysetup graph dist
119 or: pysetup graph --help
120
121Print dependency graph for the distribution.
122
123positional arguments:
124 dist installed distribution name
125""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200126def _graph(dispatcher, args, **kw):
127 name = args[1]
128 dist = get_distribution(name, use_egg_info=True)
129 if dist is None:
Éric Araujo943006bf2011-07-29 02:31:39 +0200130 logger.warning('Distribution not found.')
131 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200132 else:
133 dists = get_distributions(use_egg_info=True)
134 graph = generate_graph(dists)
135 print(graph.repr_node(dist))
136
137
Éric Araujo3f184f52011-08-30 22:23:52 +0200138@action_help("""\
139Usage: pysetup install [dist]
140 or: pysetup install [archive]
141 or: pysetup install [src_dir]
142 or: pysetup install --help
143
144Install a Python distribution from the indexes, source directory, or sdist.
145
146positional arguments:
147 archive path to source distribution (zip, tar.gz)
148 dist distribution name to install from the indexes
149 scr_dir path to source directory
150""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200151def _install(dispatcher, args, **kw):
152 # first check if we are in a source directory
153 if len(args) < 2:
154 # are we inside a project dir?
Éric Araujo943006bf2011-07-29 02:31:39 +0200155 if os.path.isfile('setup.cfg') or os.path.isfile('setup.py'):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200156 args.insert(1, os.getcwd())
157 else:
Tarek Ziade5a5ce382011-05-31 12:09:34 +0200158 logger.warning('No project to install.')
159 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200160
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200161 target = args[1]
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200162 # installing from a source dir or archive file?
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200163 if os.path.isdir(target) or _is_archive_file(target):
Éric Araujo943006bf2011-07-29 02:31:39 +0200164 return not install_local_project(target)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200165 else:
166 # download from PyPI
Éric Araujo943006bf2011-07-29 02:31:39 +0200167 return not install(target)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200168
169
Éric Araujo3f184f52011-08-30 22:23:52 +0200170@action_help("""\
171Usage: pysetup metadata [dist]
172 or: pysetup metadata [dist] [-f field ...]
173 or: pysetup metadata --help
174
175Print metadata for the distribution.
176
177positional arguments:
178 dist installed distribution name
179
180optional arguments:
181 -f metadata field to print; omit to get all fields
182""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200183def _metadata(dispatcher, args, **kw):
Éric Araujofb639292011-08-29 22:03:46 +0200184 opts = _parse_args(args[1:], 'f:', [])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200185 if opts['args']:
186 name = opts['args'][0]
187 dist = get_distribution(name, use_egg_info=True)
188 if dist is None:
Éric Araujo943006bf2011-07-29 02:31:39 +0200189 logger.warning('%r not installed', name)
190 return 1
191 elif os.path.isfile('setup.cfg'):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200192 logger.info('searching local dir for metadata')
Éric Araujo943006bf2011-07-29 02:31:39 +0200193 dist = Distribution() # XXX use config module
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200194 dist.parse_config_files()
Éric Araujo943006bf2011-07-29 02:31:39 +0200195 else:
196 logger.warning('no argument given and no local setup.cfg found')
197 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200198
199 metadata = dist.metadata
200
Éric Araujofb639292011-08-29 22:03:46 +0200201 if 'f' in opts:
202 keys = (k for k in opts['f'] if k in metadata)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200203 else:
Éric Araujofb639292011-08-29 22:03:46 +0200204 keys = metadata.keys()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200205
206 for key in keys:
207 if key in metadata:
208 print(metadata._convert_name(key) + ':')
209 value = metadata[key]
210 if isinstance(value, list):
211 for v in value:
Éric Araujo3cab2f12011-06-08 04:10:57 +0200212 print(' ', v)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200213 else:
Éric Araujo3cab2f12011-06-08 04:10:57 +0200214 print(' ', value.replace('\n', '\n '))
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200215
216
Éric Araujo3f184f52011-08-30 22:23:52 +0200217@action_help("""\
218Usage: pysetup remove dist [-y]
219 or: pysetup remove --help
220
221Uninstall a Python distribution.
222
223positional arguments:
224 dist installed distribution name
225
226optional arguments:
227 -y auto confirm distribution removal
228""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200229def _remove(distpatcher, args, **kw):
230 opts = _parse_args(args[1:], 'y', [])
231 if 'y' in opts:
232 auto_confirm = True
233 else:
234 auto_confirm = False
235
Éric Araujo943006bf2011-07-29 02:31:39 +0200236 retcode = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200237 for dist in set(opts['args']):
238 try:
239 remove(dist, auto_confirm=auto_confirm)
240 except PackagingError:
Éric Araujo943006bf2011-07-29 02:31:39 +0200241 logger.warning('%r not installed', dist)
242 retcode = 1
243
244 return retcode
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200245
246
Éric Araujo3f184f52011-08-30 22:23:52 +0200247@action_help("""\
248Usage: pysetup run [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
249 or: pysetup run --help
250 or: pysetup run --list-commands
251 or: pysetup run cmd --help
252""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200253def _run(dispatcher, args, **kw):
254 parser = dispatcher.parser
255 args = args[1:]
256
257 commands = STANDARD_COMMANDS # + extra commands
258
259 if args == ['--list-commands']:
260 print('List of available commands:')
261 cmds = sorted(commands)
262
263 for cmd in cmds:
264 cls = dispatcher.cmdclass.get(cmd) or get_command_class(cmd)
265 desc = getattr(cls, 'description',
266 '(no description available)')
267 print(' %s: %s' % (cmd, desc))
268 return
269
270 while args:
271 args = dispatcher._parse_command_opts(parser, args)
272 if args is None:
273 return
274
275 # create the Distribution class
276 # need to feed setup.cfg here !
277 dist = Distribution()
278
279 # Find and parse the config file(s): they will override options from
280 # the setup script, but be overridden by the command line.
281
282 # XXX still need to be extracted from Distribution
283 dist.parse_config_files()
284
Éric Araujo943006bf2011-07-29 02:31:39 +0200285 for cmd in dispatcher.commands:
286 dist.run_command(cmd, dispatcher.command_options[cmd])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200287
288 # XXX this is crappy
289 return dist
290
291
Éric Araujo3f184f52011-08-30 22:23:52 +0200292@action_help("""\
Éric Araujocde65762011-09-12 16:45:38 +0200293Usage: pysetup list [dist ...]
Éric Araujo3f184f52011-08-30 22:23:52 +0200294 or: pysetup list --help
Éric Araujo3f184f52011-08-30 22:23:52 +0200295
296Print name, version and location for the matching installed distributions.
297
298positional arguments:
Éric Araujocde65762011-09-12 16:45:38 +0200299 dist installed distribution name; omit to get all distributions
Éric Araujo3f184f52011-08-30 22:23:52 +0200300""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200301def _list(dispatcher, args, **kw):
Éric Araujocde65762011-09-12 16:45:38 +0200302 opts = _parse_args(args[1:], '', [])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200303 dists = get_distributions(use_egg_info=True)
Éric Araujocde65762011-09-12 16:45:38 +0200304 if opts['args']:
Éric Araujo943006bf2011-07-29 02:31:39 +0200305 results = (d for d in dists if d.name.lower() in opts['args'])
Éric Araujo73c175f2011-07-29 02:20:39 +0200306 listall = False
Éric Araujocde65762011-09-12 16:45:38 +0200307 else:
308 results = dists
309 listall = True
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200310
Tarek Ziade441531f2011-05-31 09:18:24 +0200311 number = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200312 for dist in results:
Éric Araujo943006bf2011-07-29 02:31:39 +0200313 print('%r %s (from %r)' % (dist.name, dist.version, dist.path))
Tarek Ziadee2655972011-05-31 12:15:42 +0200314 number += 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200315
Tarek Ziade441531f2011-05-31 09:18:24 +0200316 if number == 0:
Éric Araujo73c175f2011-07-29 02:20:39 +0200317 if listall:
Éric Araujo943006bf2011-07-29 02:31:39 +0200318 logger.info('Nothing seems to be installed.')
Éric Araujo73c175f2011-07-29 02:20:39 +0200319 else:
Éric Araujo943006bf2011-07-29 02:31:39 +0200320 logger.warning('No matching distribution found.')
Éric Araujo73c175f2011-07-29 02:20:39 +0200321 return 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200322 else:
Éric Araujo943006bf2011-07-29 02:31:39 +0200323 logger.info('Found %d projects installed.', number)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200324
325
Éric Araujo3f184f52011-08-30 22:23:52 +0200326@action_help("""\
327Usage: pysetup search [project] [--simple [url]] [--xmlrpc [url] [--fieldname value ...] --operator or|and]
328 or: pysetup search --help
329
330Search the indexes for the matching projects.
331
332positional arguments:
333 project the project pattern to search for
334
335optional arguments:
336 --xmlrpc [url] whether to use the xmlrpc index or not. If an url is
337 specified, it will be used rather than the default one.
338
339 --simple [url] whether to use the simple index or not. If an url is
340 specified, it will be used rather than the default one.
341
342 --fieldname value Make a search on this field. Can only be used if
343 --xmlrpc has been selected or is the default index.
344
345 --operator or|and Defines what is the operator to use when doing xmlrpc
346 searchs with multiple fieldnames. Can only be used if
347 --xmlrpc has been selected or is the default index.
348""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200349def _search(dispatcher, args, **kw):
350 """The search action.
351
352 It is able to search for a specific index (specified with --index), using
353 the simple or xmlrpc index types (with --type xmlrpc / --type simple)
354 """
Tarek Ziadee2655972011-05-31 12:15:42 +0200355 #opts = _parse_args(args[1:], '', ['simple', 'xmlrpc'])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200356 # 1. what kind of index is requested ? (xmlrpc / simple)
Éric Araujo943006bf2011-07-29 02:31:39 +0200357 logger.error('not implemented')
358 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200359
360
361actions = [
362 ('run', 'Run one or several commands', _run),
363 ('metadata', 'Display the metadata of a project', _metadata),
364 ('install', 'Install a project', _install),
365 ('remove', 'Remove a project', _remove),
366 ('search', 'Search for a project in the indexes', _search),
Éric Araujocde65762011-09-12 16:45:38 +0200367 ('list', 'List installed projects', _list),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200368 ('graph', 'Display a graph', _graph),
Éric Araujo18efecf2011-06-04 22:33:59 +0200369 ('create', 'Create a project', _create),
370 ('generate-setup', 'Generate a backward-comptatible setup.py', _generate),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200371]
372
373
374class Dispatcher:
375 """Reads the command-line options
376 """
377 def __init__(self, args=None):
378 self.verbose = 1
379 self.dry_run = False
380 self.help = False
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200381 self.cmdclass = {}
382 self.commands = []
383 self.command_options = {}
384
385 for attr in display_option_names:
386 setattr(self, attr, False)
387
388 self.parser = FancyGetopt(global_options + display_options)
389 self.parser.set_negative_aliases(negative_opt)
390 # FIXME this parses everything, including command options (e.g. "run
391 # build -i" errors with "option -i not recognized")
392 args = self.parser.getopt(args=args, object=self)
393
394 # if first arg is "run", we have some commands
395 if len(args) == 0:
396 self.action = None
397 else:
398 self.action = args[0]
399
400 allowed = [action[0] for action in actions] + [None]
401 if self.action not in allowed:
402 msg = 'Unrecognized action "%s"' % self.action
403 raise PackagingArgError(msg)
404
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200405 self._set_logger()
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200406 self.args = args
407
Tarek Ziadee2655972011-05-31 12:15:42 +0200408 # for display options we return immediately
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200409 if self.help or self.action is None:
410 self._show_help(self.parser, display_options_=False)
411
412 def _set_logger(self):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200413 # setting up the logging level from the command-line options
414 # -q gets warning, error and critical
415 if self.verbose == 0:
416 level = logging.WARNING
417 # default level or -v gets info too
418 # XXX there's a bug somewhere: the help text says that -v is default
419 # (and verbose is set to 1 above), but when the user explicitly gives
420 # -v on the command line, self.verbose is incremented to 2! Here we
421 # compensate for that (I tested manually). On a related note, I think
422 # it's a good thing to use -q/nothing/-v/-vv on the command line
423 # instead of logging constants; it will be easy to add support for
424 # logging configuration in setup.cfg for advanced users. --merwok
425 elif self.verbose in (1, 2):
426 level = logging.INFO
427 else: # -vv and more for debug
428 level = logging.DEBUG
429
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200430 # setting up the stream handler
431 handler = logging.StreamHandler(sys.stderr)
432 handler.setLevel(level)
433 logger.addHandler(handler)
434 logger.setLevel(level)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200435
436 def _parse_command_opts(self, parser, args):
437 # Pull the current command from the head of the command line
438 command = args[0]
439 if not command_re.match(command):
440 raise SystemExit("invalid command name %r" % (command,))
441 self.commands.append(command)
442
443 # Dig up the command class that implements this command, so we
444 # 1) know that it's a valid command, and 2) know which options
445 # it takes.
446 try:
447 cmd_class = get_command_class(command)
448 except PackagingModuleError as msg:
449 raise PackagingArgError(msg)
450
451 # XXX We want to push this in packaging.command
452 #
453 # Require that the command class be derived from Command -- want
454 # to be sure that the basic "command" interface is implemented.
455 for meth in ('initialize_options', 'finalize_options', 'run'):
456 if hasattr(cmd_class, meth):
457 continue
458 raise PackagingClassError(
459 'command %r must implement %r' % (cmd_class, meth))
460
461 # Also make sure that the command object provides a list of its
462 # known options.
463 if not (hasattr(cmd_class, 'user_options') and
464 isinstance(cmd_class.user_options, list)):
465 raise PackagingClassError(
466 "command class %s must provide "
467 "'user_options' attribute (a list of tuples)" % cmd_class)
468
469 # If the command class has a list of negative alias options,
470 # merge it in with the global negative aliases.
471 _negative_opt = negative_opt.copy()
472
473 if hasattr(cmd_class, 'negative_opt'):
474 _negative_opt.update(cmd_class.negative_opt)
475
476 # Check for help_options in command class. They have a different
477 # format (tuple of four) so we need to preprocess them here.
478 if (hasattr(cmd_class, 'help_options') and
479 isinstance(cmd_class.help_options, list)):
480 help_options = cmd_class.help_options[:]
481 else:
482 help_options = []
483
484 # All commands support the global options too, just by adding
485 # in 'global_options'.
486 parser.set_option_table(global_options +
487 cmd_class.user_options +
488 help_options)
489 parser.set_negative_aliases(_negative_opt)
490 args, opts = parser.getopt(args[1:])
491
492 if hasattr(opts, 'help') and opts.help:
493 self._show_command_help(cmd_class)
494 return
495
496 if (hasattr(cmd_class, 'help_options') and
497 isinstance(cmd_class.help_options, list)):
498 help_option_found = False
499 for help_option, short, desc, func in cmd_class.help_options:
500 if hasattr(opts, help_option.replace('-', '_')):
501 help_option_found = True
502 if hasattr(func, '__call__'):
503 func()
504 else:
505 raise PackagingClassError(
506 "invalid help function %r for help option %r: "
507 "must be a callable object (function, etc.)"
508 % (func, help_option))
509
510 if help_option_found:
511 return
512
513 # Put the options from the command line into their official
514 # holding pen, the 'command_options' dictionary.
515 opt_dict = self.get_option_dict(command)
516 for name, value in vars(opts).items():
517 opt_dict[name] = ("command line", value)
518
519 return args
520
521 def get_option_dict(self, command):
522 """Get the option dictionary for a given command. If that
523 command's option dictionary hasn't been created yet, then create it
524 and return the new dictionary; otherwise, return the existing
525 option dictionary.
526 """
527 d = self.command_options.get(command)
528 if d is None:
529 d = self.command_options[command] = {}
530 return d
531
532 def show_help(self):
533 self._show_help(self.parser)
534
535 def print_usage(self, parser):
536 parser.set_option_table(global_options)
537
538 actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions]
539 usage = common_usage % {'actions': '\n'.join(actions_)}
540
541 parser.print_help(usage + "\nGlobal options:")
542
543 def _show_help(self, parser, global_options_=True, display_options_=True,
544 commands=[]):
545 # late import because of mutual dependence between these modules
546 from packaging.command.cmd import Command
547
548 print('Usage: pysetup [options] action [action_options]')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200549 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200550 if global_options_:
551 self.print_usage(self.parser)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200552 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200553
554 if display_options_:
555 parser.set_option_table(display_options)
556 parser.print_help(
557 "Information display options (just display " +
558 "information, ignore any commands)")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200559 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200560
561 for command in commands:
562 if isinstance(command, type) and issubclass(command, Command):
563 cls = command
564 else:
565 cls = get_command_class(command)
566 if (hasattr(cls, 'help_options') and
567 isinstance(cls.help_options, list)):
568 parser.set_option_table(cls.user_options + cls.help_options)
569 else:
570 parser.set_option_table(cls.user_options)
571
572 parser.print_help("Options for %r command:" % cls.__name__)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200573 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200574
575 def _show_command_help(self, command):
576 if isinstance(command, str):
577 command = get_command_class(command)
578
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200579 desc = getattr(command, 'description', '(no description available)')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200580 print('Description:', desc)
581 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200582
583 if (hasattr(command, 'help_options') and
584 isinstance(command.help_options, list)):
585 self.parser.set_option_table(command.user_options +
586 command.help_options)
587 else:
588 self.parser.set_option_table(command.user_options)
589
590 self.parser.print_help("Options:")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200591 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200592
593 def _get_command_groups(self):
594 """Helper function to retrieve all the command class names divided
595 into standard commands (listed in
596 packaging.command.STANDARD_COMMANDS) and extra commands (given in
597 self.cmdclass and not standard commands).
598 """
599 extra_commands = [cmd for cmd in self.cmdclass
600 if cmd not in STANDARD_COMMANDS]
601 return STANDARD_COMMANDS, extra_commands
602
603 def print_commands(self):
604 """Print out a help message listing all available commands with a
605 description of each. The list is divided into standard commands
606 (listed in packaging.command.STANDARD_COMMANDS) and extra commands
607 (given in self.cmdclass and not standard commands). The
608 descriptions come from the command class attribute
609 'description'.
610 """
611 std_commands, extra_commands = self._get_command_groups()
612 max_length = max(len(command)
613 for commands in (std_commands, extra_commands)
614 for command in commands)
615
616 self.print_command_list(std_commands, "Standard commands", max_length)
617 if extra_commands:
618 print()
619 self.print_command_list(extra_commands, "Extra commands",
620 max_length)
621
622 def print_command_list(self, commands, header, max_length):
623 """Print a subset of the list of all commands -- used by
624 'print_commands()'.
625 """
626 print(header + ":")
627
628 for cmd in commands:
629 cls = self.cmdclass.get(cmd) or get_command_class(cmd)
630 description = getattr(cls, 'description',
631 '(no description available)')
632
633 print(" %-*s %s" % (max_length, cmd, description))
634
635 def __call__(self):
636 if self.action is None:
637 return
Éric Araujo943006bf2011-07-29 02:31:39 +0200638
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200639 for action, desc, func in actions:
640 if action == self.action:
641 return func(self, self.args)
642 return -1
643
644
645def main(args=None):
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200646 old_level = logger.level
Éric Araujo088025f2011-06-04 18:45:40 +0200647 old_handlers = list(logger.handlers)
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200648 try:
649 dispatcher = Dispatcher(args)
650 if dispatcher.action is None:
651 return
652 return dispatcher()
Éric Araujo943006bf2011-07-29 02:31:39 +0200653 except KeyboardInterrupt:
654 logger.info('interrupted')
655 return 1
656 except (IOError, os.error, PackagingError, CCompilerError) as exc:
657 logger.exception(exc)
658 return 1
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200659 finally:
660 logger.setLevel(old_level)
661 logger.handlers[:] = old_handlers
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200662
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200663
664if __name__ == '__main__':
665 sys.exit(main())