blob: 671a4bfb17b57717be2f4fd3686f40deb614f16e [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:
Éric Araujo6fd287e2011-10-06 05:28:56 +0200286 # FIXME need to catch MetadataMissingError here (from the check command
287 # e.g.)--or catch any exception, print an error message and exit with 1
Éric Araujo943006bf2011-07-29 02:31:39 +0200288 dist.run_command(cmd, dispatcher.command_options[cmd])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200289
Éric Araujo6fd287e2011-10-06 05:28:56 +0200290 return 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200291
292
Éric Araujo3f184f52011-08-30 22:23:52 +0200293@action_help("""\
Éric Araujocde65762011-09-12 16:45:38 +0200294Usage: pysetup list [dist ...]
Éric Araujo3f184f52011-08-30 22:23:52 +0200295 or: pysetup list --help
Éric Araujo3f184f52011-08-30 22:23:52 +0200296
297Print name, version and location for the matching installed distributions.
298
299positional arguments:
Éric Araujocde65762011-09-12 16:45:38 +0200300 dist installed distribution name; omit to get all distributions
Éric Araujo3f184f52011-08-30 22:23:52 +0200301""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200302def _list(dispatcher, args, **kw):
Éric Araujocde65762011-09-12 16:45:38 +0200303 opts = _parse_args(args[1:], '', [])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200304 dists = get_distributions(use_egg_info=True)
Éric Araujocde65762011-09-12 16:45:38 +0200305 if opts['args']:
Éric Araujo943006bf2011-07-29 02:31:39 +0200306 results = (d for d in dists if d.name.lower() in opts['args'])
Éric Araujo73c175f2011-07-29 02:20:39 +0200307 listall = False
Éric Araujocde65762011-09-12 16:45:38 +0200308 else:
309 results = dists
310 listall = True
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200311
Tarek Ziade441531f2011-05-31 09:18:24 +0200312 number = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200313 for dist in results:
Éric Araujo943006bf2011-07-29 02:31:39 +0200314 print('%r %s (from %r)' % (dist.name, dist.version, dist.path))
Tarek Ziadee2655972011-05-31 12:15:42 +0200315 number += 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200316
Tarek Ziade441531f2011-05-31 09:18:24 +0200317 if number == 0:
Éric Araujo73c175f2011-07-29 02:20:39 +0200318 if listall:
Éric Araujo943006bf2011-07-29 02:31:39 +0200319 logger.info('Nothing seems to be installed.')
Éric Araujo73c175f2011-07-29 02:20:39 +0200320 else:
Éric Araujo943006bf2011-07-29 02:31:39 +0200321 logger.warning('No matching distribution found.')
Éric Araujo73c175f2011-07-29 02:20:39 +0200322 return 1
Tarek Ziade441531f2011-05-31 09:18:24 +0200323 else:
Éric Araujo943006bf2011-07-29 02:31:39 +0200324 logger.info('Found %d projects installed.', number)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200325
326
Éric Araujo3f184f52011-08-30 22:23:52 +0200327@action_help("""\
328Usage: pysetup search [project] [--simple [url]] [--xmlrpc [url] [--fieldname value ...] --operator or|and]
329 or: pysetup search --help
330
331Search the indexes for the matching projects.
332
333positional arguments:
334 project the project pattern to search for
335
336optional arguments:
337 --xmlrpc [url] whether to use the xmlrpc index or not. If an url is
338 specified, it will be used rather than the default one.
339
340 --simple [url] whether to use the simple index or not. If an url is
341 specified, it will be used rather than the default one.
342
343 --fieldname value Make a search on this field. Can only be used if
344 --xmlrpc has been selected or is the default index.
345
346 --operator or|and Defines what is the operator to use when doing xmlrpc
347 searchs with multiple fieldnames. Can only be used if
348 --xmlrpc has been selected or is the default index.
349""")
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200350def _search(dispatcher, args, **kw):
351 """The search action.
352
353 It is able to search for a specific index (specified with --index), using
354 the simple or xmlrpc index types (with --type xmlrpc / --type simple)
355 """
Tarek Ziadee2655972011-05-31 12:15:42 +0200356 #opts = _parse_args(args[1:], '', ['simple', 'xmlrpc'])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200357 # 1. what kind of index is requested ? (xmlrpc / simple)
Éric Araujo943006bf2011-07-29 02:31:39 +0200358 logger.error('not implemented')
359 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200360
361
362actions = [
363 ('run', 'Run one or several commands', _run),
364 ('metadata', 'Display the metadata of a project', _metadata),
365 ('install', 'Install a project', _install),
366 ('remove', 'Remove a project', _remove),
367 ('search', 'Search for a project in the indexes', _search),
Éric Araujocde65762011-09-12 16:45:38 +0200368 ('list', 'List installed projects', _list),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200369 ('graph', 'Display a graph', _graph),
Éric Araujo18efecf2011-06-04 22:33:59 +0200370 ('create', 'Create a project', _create),
371 ('generate-setup', 'Generate a backward-comptatible setup.py', _generate),
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200372]
373
374
375class Dispatcher:
376 """Reads the command-line options
377 """
378 def __init__(self, args=None):
379 self.verbose = 1
380 self.dry_run = False
381 self.help = False
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200382 self.cmdclass = {}
383 self.commands = []
384 self.command_options = {}
385
386 for attr in display_option_names:
387 setattr(self, attr, False)
388
389 self.parser = FancyGetopt(global_options + display_options)
390 self.parser.set_negative_aliases(negative_opt)
391 # FIXME this parses everything, including command options (e.g. "run
392 # build -i" errors with "option -i not recognized")
393 args = self.parser.getopt(args=args, object=self)
394
395 # if first arg is "run", we have some commands
396 if len(args) == 0:
397 self.action = None
398 else:
399 self.action = args[0]
400
401 allowed = [action[0] for action in actions] + [None]
402 if self.action not in allowed:
403 msg = 'Unrecognized action "%s"' % self.action
404 raise PackagingArgError(msg)
405
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200406 self._set_logger()
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200407 self.args = args
408
Tarek Ziadee2655972011-05-31 12:15:42 +0200409 # for display options we return immediately
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200410 if self.help or self.action is None:
411 self._show_help(self.parser, display_options_=False)
412
413 def _set_logger(self):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200414 # setting up the logging level from the command-line options
415 # -q gets warning, error and critical
416 if self.verbose == 0:
417 level = logging.WARNING
418 # default level or -v gets info too
419 # XXX there's a bug somewhere: the help text says that -v is default
420 # (and verbose is set to 1 above), but when the user explicitly gives
421 # -v on the command line, self.verbose is incremented to 2! Here we
422 # compensate for that (I tested manually). On a related note, I think
423 # it's a good thing to use -q/nothing/-v/-vv on the command line
424 # instead of logging constants; it will be easy to add support for
425 # logging configuration in setup.cfg for advanced users. --merwok
426 elif self.verbose in (1, 2):
427 level = logging.INFO
428 else: # -vv and more for debug
429 level = logging.DEBUG
430
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200431 # setting up the stream handler
432 handler = logging.StreamHandler(sys.stderr)
433 handler.setLevel(level)
434 logger.addHandler(handler)
435 logger.setLevel(level)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200436
437 def _parse_command_opts(self, parser, args):
438 # Pull the current command from the head of the command line
439 command = args[0]
440 if not command_re.match(command):
441 raise SystemExit("invalid command name %r" % (command,))
442 self.commands.append(command)
443
444 # Dig up the command class that implements this command, so we
445 # 1) know that it's a valid command, and 2) know which options
446 # it takes.
447 try:
448 cmd_class = get_command_class(command)
449 except PackagingModuleError as msg:
450 raise PackagingArgError(msg)
451
452 # XXX We want to push this in packaging.command
453 #
454 # Require that the command class be derived from Command -- want
455 # to be sure that the basic "command" interface is implemented.
456 for meth in ('initialize_options', 'finalize_options', 'run'):
457 if hasattr(cmd_class, meth):
458 continue
459 raise PackagingClassError(
460 'command %r must implement %r' % (cmd_class, meth))
461
462 # Also make sure that the command object provides a list of its
463 # known options.
464 if not (hasattr(cmd_class, 'user_options') and
465 isinstance(cmd_class.user_options, list)):
466 raise PackagingClassError(
467 "command class %s must provide "
468 "'user_options' attribute (a list of tuples)" % cmd_class)
469
470 # If the command class has a list of negative alias options,
471 # merge it in with the global negative aliases.
472 _negative_opt = negative_opt.copy()
473
474 if hasattr(cmd_class, 'negative_opt'):
475 _negative_opt.update(cmd_class.negative_opt)
476
477 # Check for help_options in command class. They have a different
478 # format (tuple of four) so we need to preprocess them here.
479 if (hasattr(cmd_class, 'help_options') and
480 isinstance(cmd_class.help_options, list)):
481 help_options = cmd_class.help_options[:]
482 else:
483 help_options = []
484
485 # All commands support the global options too, just by adding
486 # in 'global_options'.
487 parser.set_option_table(global_options +
488 cmd_class.user_options +
489 help_options)
490 parser.set_negative_aliases(_negative_opt)
491 args, opts = parser.getopt(args[1:])
492
493 if hasattr(opts, 'help') and opts.help:
494 self._show_command_help(cmd_class)
495 return
496
497 if (hasattr(cmd_class, 'help_options') and
498 isinstance(cmd_class.help_options, list)):
499 help_option_found = False
500 for help_option, short, desc, func in cmd_class.help_options:
501 if hasattr(opts, help_option.replace('-', '_')):
502 help_option_found = True
Florent Xiclunaaabbda52011-10-28 14:52:29 +0200503 if callable(func):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200504 func()
505 else:
506 raise PackagingClassError(
507 "invalid help function %r for help option %r: "
508 "must be a callable object (function, etc.)"
509 % (func, help_option))
510
511 if help_option_found:
512 return
513
514 # Put the options from the command line into their official
515 # holding pen, the 'command_options' dictionary.
516 opt_dict = self.get_option_dict(command)
517 for name, value in vars(opts).items():
518 opt_dict[name] = ("command line", value)
519
520 return args
521
522 def get_option_dict(self, command):
523 """Get the option dictionary for a given command. If that
524 command's option dictionary hasn't been created yet, then create it
525 and return the new dictionary; otherwise, return the existing
526 option dictionary.
527 """
528 d = self.command_options.get(command)
529 if d is None:
530 d = self.command_options[command] = {}
531 return d
532
533 def show_help(self):
534 self._show_help(self.parser)
535
536 def print_usage(self, parser):
537 parser.set_option_table(global_options)
538
539 actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions]
540 usage = common_usage % {'actions': '\n'.join(actions_)}
541
542 parser.print_help(usage + "\nGlobal options:")
543
544 def _show_help(self, parser, global_options_=True, display_options_=True,
545 commands=[]):
546 # late import because of mutual dependence between these modules
547 from packaging.command.cmd import Command
548
549 print('Usage: pysetup [options] action [action_options]')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200550 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200551 if global_options_:
552 self.print_usage(self.parser)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200553 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200554
555 if display_options_:
556 parser.set_option_table(display_options)
557 parser.print_help(
558 "Information display options (just display " +
559 "information, ignore any commands)")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200560 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200561
562 for command in commands:
563 if isinstance(command, type) and issubclass(command, Command):
564 cls = command
565 else:
566 cls = get_command_class(command)
567 if (hasattr(cls, 'help_options') and
568 isinstance(cls.help_options, list)):
569 parser.set_option_table(cls.user_options + cls.help_options)
570 else:
571 parser.set_option_table(cls.user_options)
572
573 parser.print_help("Options for %r command:" % cls.__name__)
Éric Araujo3cab2f12011-06-08 04:10:57 +0200574 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200575
576 def _show_command_help(self, command):
577 if isinstance(command, str):
578 command = get_command_class(command)
579
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200580 desc = getattr(command, 'description', '(no description available)')
Éric Araujo3cab2f12011-06-08 04:10:57 +0200581 print('Description:', desc)
582 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200583
584 if (hasattr(command, 'help_options') and
585 isinstance(command.help_options, list)):
586 self.parser.set_option_table(command.user_options +
587 command.help_options)
588 else:
589 self.parser.set_option_table(command.user_options)
590
591 self.parser.print_help("Options:")
Éric Araujo3cab2f12011-06-08 04:10:57 +0200592 print()
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200593
594 def _get_command_groups(self):
595 """Helper function to retrieve all the command class names divided
596 into standard commands (listed in
597 packaging.command.STANDARD_COMMANDS) and extra commands (given in
598 self.cmdclass and not standard commands).
599 """
600 extra_commands = [cmd for cmd in self.cmdclass
601 if cmd not in STANDARD_COMMANDS]
602 return STANDARD_COMMANDS, extra_commands
603
604 def print_commands(self):
605 """Print out a help message listing all available commands with a
606 description of each. The list is divided into standard commands
607 (listed in packaging.command.STANDARD_COMMANDS) and extra commands
608 (given in self.cmdclass and not standard commands). The
609 descriptions come from the command class attribute
610 'description'.
611 """
612 std_commands, extra_commands = self._get_command_groups()
613 max_length = max(len(command)
614 for commands in (std_commands, extra_commands)
615 for command in commands)
616
617 self.print_command_list(std_commands, "Standard commands", max_length)
618 if extra_commands:
619 print()
620 self.print_command_list(extra_commands, "Extra commands",
621 max_length)
622
623 def print_command_list(self, commands, header, max_length):
624 """Print a subset of the list of all commands -- used by
625 'print_commands()'.
626 """
627 print(header + ":")
628
629 for cmd in commands:
630 cls = self.cmdclass.get(cmd) or get_command_class(cmd)
631 description = getattr(cls, 'description',
632 '(no description available)')
633
634 print(" %-*s %s" % (max_length, cmd, description))
635
636 def __call__(self):
637 if self.action is None:
638 return
Éric Araujo943006bf2011-07-29 02:31:39 +0200639
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200640 for action, desc, func in actions:
641 if action == self.action:
642 return func(self, self.args)
643 return -1
644
645
646def main(args=None):
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200647 old_level = logger.level
Éric Araujo088025f2011-06-04 18:45:40 +0200648 old_handlers = list(logger.handlers)
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200649 try:
650 dispatcher = Dispatcher(args)
651 if dispatcher.action is None:
652 return
653 return dispatcher()
Éric Araujo943006bf2011-07-29 02:31:39 +0200654 except KeyboardInterrupt:
655 logger.info('interrupted')
656 return 1
657 except (IOError, os.error, PackagingError, CCompilerError) as exc:
658 logger.exception(exc)
659 return 1
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200660 finally:
661 logger.setLevel(old_level)
662 logger.handlers[:] = old_handlers
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200663
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200664
665if __name__ == '__main__':
666 sys.exit(main())