blob: c3600a70483100788f583b3aba693a6c8f36b9a6 [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
Éric Araujo5c69b662012-02-09 14:29:11 +0100257 commands = STANDARD_COMMANDS # FIXME display extra commands
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200258
259 if args == ['--list-commands']:
260 print('List of available commands:')
Éric Araujo5c69b662012-02-09 14:29:11 +0100261 for cmd in commands:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200262 cls = dispatcher.cmdclass.get(cmd) or get_command_class(cmd)
Éric Araujo5c69b662012-02-09 14:29:11 +0100263 desc = getattr(cls, 'description', '(no description available)')
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200264 print(' %s: %s' % (cmd, desc))
265 return
266
267 while args:
268 args = dispatcher._parse_command_opts(parser, args)
269 if args is None:
270 return
271
272 # create the Distribution class
273 # need to feed setup.cfg here !
274 dist = Distribution()
275
276 # Find and parse the config file(s): they will override options from
277 # the setup script, but be overridden by the command line.
278
279 # XXX still need to be extracted from Distribution
280 dist.parse_config_files()
281
Éric Araujo943006bf2011-07-29 02:31:39 +0200282 for cmd in dispatcher.commands:
Éric Araujo6fd287e2011-10-06 05:28:56 +0200283 # FIXME need to catch MetadataMissingError here (from the check command
284 # e.g.)--or catch any exception, print an error message and exit with 1
Éric Araujo943006bf2011-07-29 02:31:39 +0200285 dist.run_command(cmd, dispatcher.command_options[cmd])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200286
Éric Araujo6fd287e2011-10-06 05:28:56 +0200287 return 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200288
289
Éric Araujo3f184f52011-08-30 22:23:52 +0200290@action_help("""\
Éric Araujocde65762011-09-12 16:45:38 +0200291Usage: pysetup list [dist ...]
Éric Araujo3f184f52011-08-30 22:23:52 +0200292 or: pysetup list --help
Éric Araujo3f184f52011-08-30 22:23:52 +0200293
294Print name, version and location for the matching installed distributions.
295
296positional arguments:
Éric Araujocde65762011-09-12 16:45:38 +0200297 dist installed distribution name; omit to get all distributions
Éric Araujo3f184f52011-08-30 22:23:52 +0200298""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200299def _list(dispatcher, args, **kw):
Éric Araujocde65762011-09-12 16:45:38 +0200300 opts = _parse_args(args[1:], '', [])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200301 dists = get_distributions(use_egg_info=True)
Éric Araujocde65762011-09-12 16:45:38 +0200302 if opts['args']:
Éric Araujo943006bf2011-07-29 02:31:39 +0200303 results = (d for d in dists if d.name.lower() in opts['args'])
Éric Araujo73c175f2011-07-29 02:20:39 +0200304 listall = False
Éric Araujocde65762011-09-12 16:45:38 +0200305 else:
306 results = dists
307 listall = True
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200308
Tarek Ziade441531f2011-05-31 09:18:24 +0200309 number = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200310 for dist in results:
Éric Araujo943006bf2011-07-29 02:31:39 +0200311 print('%r %s (from %r)' % (dist.name, dist.version, dist.path))
Tarek Ziadee2655972011-05-31 12:15:42 +0200312 number += 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200313
Tarek Ziade441531f2011-05-31 09:18:24 +0200314 if number == 0:
Éric Araujo73c175f2011-07-29 02:20:39 +0200315 if listall:
Éric Araujo943006bf2011-07-29 02:31:39 +0200316 logger.info('Nothing seems to be installed.')
Éric Araujo73c175f2011-07-29 02:20:39 +0200317 else:
Éric Araujo943006bf2011-07-29 02:31:39 +0200318 logger.warning('No matching distribution found.')
Éric Araujo73c175f2011-07-29 02:20:39 +0200319 return 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200320 else:
Éric Araujo943006bf2011-07-29 02:31:39 +0200321 logger.info('Found %d projects installed.', number)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200322
323
Éric Araujo3f184f52011-08-30 22:23:52 +0200324@action_help("""\
325Usage: pysetup search [project] [--simple [url]] [--xmlrpc [url] [--fieldname value ...] --operator or|and]
326 or: pysetup search --help
327
328Search the indexes for the matching projects.
329
330positional arguments:
331 project the project pattern to search for
332
333optional arguments:
334 --xmlrpc [url] whether to use the xmlrpc index or not. If an url is
335 specified, it will be used rather than the default one.
336
337 --simple [url] whether to use the simple index or not. If an url is
338 specified, it will be used rather than the default one.
339
340 --fieldname value Make a search on this field. Can only be used if
341 --xmlrpc has been selected or is the default index.
342
343 --operator or|and Defines what is the operator to use when doing xmlrpc
344 searchs with multiple fieldnames. Can only be used if
345 --xmlrpc has been selected or is the default index.
346""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200347def _search(dispatcher, args, **kw):
348 """The search action.
349
350 It is able to search for a specific index (specified with --index), using
351 the simple or xmlrpc index types (with --type xmlrpc / --type simple)
352 """
Tarek Ziadee2655972011-05-31 12:15:42 +0200353 #opts = _parse_args(args[1:], '', ['simple', 'xmlrpc'])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200354 # 1. what kind of index is requested ? (xmlrpc / simple)
Éric Araujo943006bf2011-07-29 02:31:39 +0200355 logger.error('not implemented')
356 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200357
358
359actions = [
360 ('run', 'Run one or several commands', _run),
361 ('metadata', 'Display the metadata of a project', _metadata),
362 ('install', 'Install a project', _install),
363 ('remove', 'Remove a project', _remove),
364 ('search', 'Search for a project in the indexes', _search),
Éric Araujocde65762011-09-12 16:45:38 +0200365 ('list', 'List installed projects', _list),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200366 ('graph', 'Display a graph', _graph),
Éric Araujo18efecf2011-06-04 22:33:59 +0200367 ('create', 'Create a project', _create),
Éric Araujobfc97292011-11-14 18:18:15 +0100368 ('generate-setup', 'Generate a backward-compatible setup.py', _generate),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200369]
370
371
372class Dispatcher:
373 """Reads the command-line options
374 """
375 def __init__(self, args=None):
376 self.verbose = 1
377 self.dry_run = False
378 self.help = False
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200379 self.cmdclass = {}
380 self.commands = []
381 self.command_options = {}
382
383 for attr in display_option_names:
384 setattr(self, attr, False)
385
386 self.parser = FancyGetopt(global_options + display_options)
387 self.parser.set_negative_aliases(negative_opt)
388 # FIXME this parses everything, including command options (e.g. "run
389 # build -i" errors with "option -i not recognized")
390 args = self.parser.getopt(args=args, object=self)
391
392 # if first arg is "run", we have some commands
393 if len(args) == 0:
394 self.action = None
395 else:
396 self.action = args[0]
397
398 allowed = [action[0] for action in actions] + [None]
399 if self.action not in allowed:
400 msg = 'Unrecognized action "%s"' % self.action
401 raise PackagingArgError(msg)
402
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200403 self._set_logger()
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200404 self.args = args
405
Tarek Ziadee2655972011-05-31 12:15:42 +0200406 # for display options we return immediately
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200407 if self.help or self.action is None:
408 self._show_help(self.parser, display_options_=False)
409
410 def _set_logger(self):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200411 # setting up the logging level from the command-line options
412 # -q gets warning, error and critical
413 if self.verbose == 0:
414 level = logging.WARNING
415 # default level or -v gets info too
416 # XXX there's a bug somewhere: the help text says that -v is default
417 # (and verbose is set to 1 above), but when the user explicitly gives
418 # -v on the command line, self.verbose is incremented to 2! Here we
419 # compensate for that (I tested manually). On a related note, I think
420 # it's a good thing to use -q/nothing/-v/-vv on the command line
421 # instead of logging constants; it will be easy to add support for
422 # logging configuration in setup.cfg for advanced users. --merwok
423 elif self.verbose in (1, 2):
424 level = logging.INFO
425 else: # -vv and more for debug
426 level = logging.DEBUG
427
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200428 # setting up the stream handler
429 handler = logging.StreamHandler(sys.stderr)
430 handler.setLevel(level)
431 logger.addHandler(handler)
432 logger.setLevel(level)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200433
434 def _parse_command_opts(self, parser, args):
435 # Pull the current command from the head of the command line
436 command = args[0]
437 if not command_re.match(command):
438 raise SystemExit("invalid command name %r" % (command,))
439 self.commands.append(command)
440
441 # Dig up the command class that implements this command, so we
442 # 1) know that it's a valid command, and 2) know which options
443 # it takes.
444 try:
445 cmd_class = get_command_class(command)
446 except PackagingModuleError as msg:
447 raise PackagingArgError(msg)
448
449 # XXX We want to push this in packaging.command
450 #
451 # Require that the command class be derived from Command -- want
452 # to be sure that the basic "command" interface is implemented.
453 for meth in ('initialize_options', 'finalize_options', 'run'):
454 if hasattr(cmd_class, meth):
455 continue
456 raise PackagingClassError(
457 'command %r must implement %r' % (cmd_class, meth))
458
459 # Also make sure that the command object provides a list of its
460 # known options.
461 if not (hasattr(cmd_class, 'user_options') and
462 isinstance(cmd_class.user_options, list)):
463 raise PackagingClassError(
464 "command class %s must provide "
465 "'user_options' attribute (a list of tuples)" % cmd_class)
466
467 # If the command class has a list of negative alias options,
468 # merge it in with the global negative aliases.
469 _negative_opt = negative_opt.copy()
470
471 if hasattr(cmd_class, 'negative_opt'):
472 _negative_opt.update(cmd_class.negative_opt)
473
474 # Check for help_options in command class. They have a different
475 # format (tuple of four) so we need to preprocess them here.
476 if (hasattr(cmd_class, 'help_options') and
477 isinstance(cmd_class.help_options, list)):
478 help_options = cmd_class.help_options[:]
479 else:
480 help_options = []
481
482 # All commands support the global options too, just by adding
483 # in 'global_options'.
484 parser.set_option_table(global_options +
485 cmd_class.user_options +
486 help_options)
487 parser.set_negative_aliases(_negative_opt)
488 args, opts = parser.getopt(args[1:])
489
490 if hasattr(opts, 'help') and opts.help:
491 self._show_command_help(cmd_class)
492 return
493
494 if (hasattr(cmd_class, 'help_options') and
495 isinstance(cmd_class.help_options, list)):
496 help_option_found = False
497 for help_option, short, desc, func in cmd_class.help_options:
498 if hasattr(opts, help_option.replace('-', '_')):
499 help_option_found = True
Florent Xiclunaaabbda52011-10-28 14:52:29 +0200500 if callable(func):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200501 func()
502 else:
503 raise PackagingClassError(
504 "invalid help function %r for help option %r: "
505 "must be a callable object (function, etc.)"
506 % (func, help_option))
507
508 if help_option_found:
509 return
510
511 # Put the options from the command line into their official
512 # holding pen, the 'command_options' dictionary.
513 opt_dict = self.get_option_dict(command)
514 for name, value in vars(opts).items():
515 opt_dict[name] = ("command line", value)
516
517 return args
518
519 def get_option_dict(self, command):
520 """Get the option dictionary for a given command. If that
521 command's option dictionary hasn't been created yet, then create it
522 and return the new dictionary; otherwise, return the existing
523 option dictionary.
524 """
525 d = self.command_options.get(command)
526 if d is None:
527 d = self.command_options[command] = {}
528 return d
529
530 def show_help(self):
531 self._show_help(self.parser)
532
533 def print_usage(self, parser):
534 parser.set_option_table(global_options)
535
536 actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions]
537 usage = common_usage % {'actions': '\n'.join(actions_)}
538
539 parser.print_help(usage + "\nGlobal options:")
540
541 def _show_help(self, parser, global_options_=True, display_options_=True,
542 commands=[]):
543 # late import because of mutual dependence between these modules
544 from packaging.command.cmd import Command
545
546 print('Usage: pysetup [options] action [action_options]')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200547 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200548 if global_options_:
549 self.print_usage(self.parser)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200550 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200551
552 if display_options_:
553 parser.set_option_table(display_options)
554 parser.print_help(
555 "Information display options (just display " +
556 "information, ignore any commands)")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200557 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200558
559 for command in commands:
560 if isinstance(command, type) and issubclass(command, Command):
561 cls = command
562 else:
563 cls = get_command_class(command)
564 if (hasattr(cls, 'help_options') and
565 isinstance(cls.help_options, list)):
566 parser.set_option_table(cls.user_options + cls.help_options)
567 else:
568 parser.set_option_table(cls.user_options)
569
570 parser.print_help("Options for %r command:" % cls.__name__)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200571 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200572
573 def _show_command_help(self, command):
574 if isinstance(command, str):
575 command = get_command_class(command)
576
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200577 desc = getattr(command, 'description', '(no description available)')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200578 print('Description:', desc)
579 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200580
581 if (hasattr(command, 'help_options') and
582 isinstance(command.help_options, list)):
583 self.parser.set_option_table(command.user_options +
584 command.help_options)
585 else:
586 self.parser.set_option_table(command.user_options)
587
588 self.parser.print_help("Options:")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200589 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200590
591 def _get_command_groups(self):
592 """Helper function to retrieve all the command class names divided
593 into standard commands (listed in
594 packaging.command.STANDARD_COMMANDS) and extra commands (given in
595 self.cmdclass and not standard commands).
596 """
597 extra_commands = [cmd for cmd in self.cmdclass
598 if cmd not in STANDARD_COMMANDS]
599 return STANDARD_COMMANDS, extra_commands
600
601 def print_commands(self):
602 """Print out a help message listing all available commands with a
603 description of each. The list is divided into standard commands
604 (listed in packaging.command.STANDARD_COMMANDS) and extra commands
605 (given in self.cmdclass and not standard commands). The
606 descriptions come from the command class attribute
607 'description'.
608 """
609 std_commands, extra_commands = self._get_command_groups()
610 max_length = max(len(command)
611 for commands in (std_commands, extra_commands)
612 for command in commands)
613
614 self.print_command_list(std_commands, "Standard commands", max_length)
615 if extra_commands:
616 print()
617 self.print_command_list(extra_commands, "Extra commands",
618 max_length)
619
620 def print_command_list(self, commands, header, max_length):
621 """Print a subset of the list of all commands -- used by
622 'print_commands()'.
623 """
624 print(header + ":")
625
626 for cmd in commands:
627 cls = self.cmdclass.get(cmd) or get_command_class(cmd)
628 description = getattr(cls, 'description',
629 '(no description available)')
630
631 print(" %-*s %s" % (max_length, cmd, description))
632
633 def __call__(self):
634 if self.action is None:
635 return
Éric Araujo943006bf2011-07-29 02:31:39 +0200636
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200637 for action, desc, func in actions:
638 if action == self.action:
639 return func(self, self.args)
640 return -1
641
642
643def main(args=None):
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200644 old_level = logger.level
Éric Araujo088025f2011-06-04 18:45:40 +0200645 old_handlers = list(logger.handlers)
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200646 try:
647 dispatcher = Dispatcher(args)
648 if dispatcher.action is None:
649 return
650 return dispatcher()
Éric Araujo943006bf2011-07-29 02:31:39 +0200651 except KeyboardInterrupt:
652 logger.info('interrupted')
653 return 1
654 except (IOError, os.error, PackagingError, CCompilerError) as exc:
655 logger.exception(exc)
656 return 1
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200657 finally:
658 logger.setLevel(old_level)
659 logger.handlers[:] = old_handlers
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200660
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200661
662if __name__ == '__main__':
663 sys.exit(main())