blob: 03b80c6a05c6e39591a90b0f26a7d990252a39c6 [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
Tarek Ziadeb1b6e132011-05-30 12:07:49 +02008from copy import copy
Tarek Ziade1231a4e2011-05-19 13:07:25 +02009
10from packaging import logger
11from packaging.dist import Distribution
12from packaging.util import _is_archive_file
13from packaging.command import get_command_class, STANDARD_COMMANDS
14from packaging.install import install, install_local_project, remove
15from packaging.database import get_distribution, get_distributions
16from packaging.depgraph import generate_graph
17from packaging.fancy_getopt import FancyGetopt
18from packaging.errors import (PackagingArgError, PackagingError,
19 PackagingModuleError, PackagingClassError,
20 CCompilerError)
21
22
23command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')
24
25common_usage = """\
26Actions:
27%(actions)s
28
29To get more help on an action, use:
30
31 pysetup action --help
32"""
33
34create_usage = """\
35Usage: pysetup create
36 or: pysetup create --help
37
38Create a new Python package.
39"""
40
41graph_usage = """\
42Usage: pysetup graph dist
43 or: pysetup graph --help
44
45Print dependency graph for the distribution.
46
47positional arguments:
48 dist installed distribution name
49"""
50
51install_usage = """\
52Usage: pysetup install [dist]
53 or: pysetup install [archive]
54 or: pysetup install [src_dir]
55 or: pysetup install --help
56
57Install a Python distribution from the indexes, source directory, or sdist.
58
59positional arguments:
60 archive path to source distribution (zip, tar.gz)
61 dist distribution name to install from the indexes
62 scr_dir path to source directory
63
64"""
65
66metadata_usage = """\
67Usage: pysetup metadata [dist] [-f field ...]
68 or: pysetup metadata [dist] [--all]
69 or: pysetup metadata --help
70
71Print metadata for the distribution.
72
73positional arguments:
74 dist installed distribution name
75
76optional arguments:
77 -f metadata field to print
78 --all print all metadata fields
79"""
80
81remove_usage = """\
82Usage: pysetup remove dist [-y]
83 or: pysetup remove --help
84
85Uninstall a Python distribution.
86
87positional arguments:
88 dist installed distribution name
89
90optional arguments:
91 -y auto confirm package removal
92"""
93
94run_usage = """\
95Usage: pysetup run [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
96 or: pysetup run --help
97 or: pysetup run --list-commands
98 or: pysetup run cmd --help
99"""
100
101list_usage = """\
102Usage: pysetup list dist [dist ...]
103 or: pysetup list --help
104 or: pysetup list --all
105
106Print name, version and location for the matching installed distributions.
107
108positional arguments:
109 dist installed distribution name
110
111optional arguments:
112 --all list all installed distributions
113"""
114
115search_usage = """\
116Usage: pysetup search [project] [--simple [url]] [--xmlrpc [url] [--fieldname value ...] --operator or|and]
117 or: pysetup search --help
118
119Search the indexes for the matching projects.
120
121positional arguments:
122 project the project pattern to search for
123
124optional arguments:
125 --xmlrpc [url] wether to use the xmlrpc index or not. If an url is
126 specified, it will be used rather than the default one.
127
128 --simple [url] wether to use the simple index or not. If an url is
129 specified, it will be used rather than the default one.
130
131 --fieldname value Make a search on this field. Can only be used if
132 --xmlrpc has been selected or is the default index.
133
134 --operator or|and Defines what is the operator to use when doing xmlrpc
135 searchs with multiple fieldnames. Can only be used if
136 --xmlrpc has been selected or is the default index.
137"""
138
139global_options = [
140 # The fourth entry for verbose means that it can be repeated.
141 ('verbose', 'v', "run verbosely (default)", True),
142 ('quiet', 'q', "run quietly (turns verbosity off)"),
143 ('dry-run', 'n', "don't actually do anything"),
144 ('help', 'h', "show detailed help message"),
145 ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),
146 ('version', None, 'Display the version'),
147]
148
149negative_opt = {'quiet': 'verbose'}
150
151display_options = [
152 ('help-commands', None, "list all available commands"),
153]
154
155display_option_names = [x[0].replace('-', '_') for x in display_options]
156
157
158def _parse_args(args, options, long_options):
159 """Transform sys.argv input into a dict.
160
161 :param args: the args to parse (i.e sys.argv)
162 :param options: the list of options to pass to getopt
163 :param long_options: the list of string with the names of the long options
164 to be passed to getopt.
165
166 The function returns a dict with options/long_options as keys and matching
167 values as values.
168 """
169 optlist, args = getopt.gnu_getopt(args, options, long_options)
170 optdict = {}
171 optdict['args'] = args
172 for k, v in optlist:
173 k = k.lstrip('-')
174 if k not in optdict:
175 optdict[k] = []
176 if v:
177 optdict[k].append(v)
178 else:
179 optdict[k].append(v)
180 return optdict
181
182
183class action_help:
184 """Prints a help message when the standard help flags: -h and --help
185 are used on the commandline.
186 """
187
188 def __init__(self, help_msg):
189 self.help_msg = help_msg
190
191 def __call__(self, f):
192 def wrapper(*args, **kwargs):
193 f_args = args[1]
194 if '--help' in f_args or '-h' in f_args:
195 print(self.help_msg)
196 return
197 return f(*args, **kwargs)
198 return wrapper
199
200
201@action_help(create_usage)
202def _create(distpatcher, args, **kw):
203 from packaging.create import main
204 return main()
205
206
207@action_help(graph_usage)
208def _graph(dispatcher, args, **kw):
209 name = args[1]
210 dist = get_distribution(name, use_egg_info=True)
211 if dist is None:
212 print('Distribution not found.')
213 else:
214 dists = get_distributions(use_egg_info=True)
215 graph = generate_graph(dists)
216 print(graph.repr_node(dist))
217
218
219@action_help(install_usage)
220def _install(dispatcher, args, **kw):
221 # first check if we are in a source directory
222 if len(args) < 2:
223 # are we inside a project dir?
224 listing = os.listdir(os.getcwd())
225 if 'setup.py' in listing or 'setup.cfg' in listing:
226 args.insert(1, os.getcwd())
227 else:
228 logger.warning('no project to install')
229 return
230
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200231 target = args[1]
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200232 # installing from a source dir or archive file?
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200233 if os.path.isdir(target) or _is_archive_file(target):
234 install_local_project(target)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200235 else:
236 # download from PyPI
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200237 install(target)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200238
239
240@action_help(metadata_usage)
241def _metadata(dispatcher, args, **kw):
242 opts = _parse_args(args[1:], 'f:', ['all'])
243 if opts['args']:
244 name = opts['args'][0]
245 dist = get_distribution(name, use_egg_info=True)
246 if dist is None:
247 logger.warning('%s not installed', name)
248 return
249 else:
250 logger.info('searching local dir for metadata')
251 dist = Distribution()
252 dist.parse_config_files()
253
254 metadata = dist.metadata
255
256 if 'all' in opts:
257 keys = metadata.keys()
258 else:
259 if 'f' in opts:
260 keys = (k for k in opts['f'] if k in metadata)
261 else:
262 keys = ()
263
264 for key in keys:
265 if key in metadata:
266 print(metadata._convert_name(key) + ':')
267 value = metadata[key]
268 if isinstance(value, list):
269 for v in value:
270 print(' ' + v)
271 else:
272 print(' ' + value.replace('\n', '\n '))
273
274
275@action_help(remove_usage)
276def _remove(distpatcher, args, **kw):
277 opts = _parse_args(args[1:], 'y', [])
278 if 'y' in opts:
279 auto_confirm = True
280 else:
281 auto_confirm = False
282
283 for dist in set(opts['args']):
284 try:
285 remove(dist, auto_confirm=auto_confirm)
286 except PackagingError:
287 logger.warning('%s not installed', dist)
288
289
290@action_help(run_usage)
291def _run(dispatcher, args, **kw):
292 parser = dispatcher.parser
293 args = args[1:]
294
295 commands = STANDARD_COMMANDS # + extra commands
296
297 if args == ['--list-commands']:
298 print('List of available commands:')
299 cmds = sorted(commands)
300
301 for cmd in cmds:
302 cls = dispatcher.cmdclass.get(cmd) or get_command_class(cmd)
303 desc = getattr(cls, 'description',
304 '(no description available)')
305 print(' %s: %s' % (cmd, desc))
306 return
307
308 while args:
309 args = dispatcher._parse_command_opts(parser, args)
310 if args is None:
311 return
312
313 # create the Distribution class
314 # need to feed setup.cfg here !
315 dist = Distribution()
316
317 # Find and parse the config file(s): they will override options from
318 # the setup script, but be overridden by the command line.
319
320 # XXX still need to be extracted from Distribution
321 dist.parse_config_files()
322
323 try:
324 for cmd in dispatcher.commands:
325 dist.run_command(cmd, dispatcher.command_options[cmd])
326
327 except KeyboardInterrupt:
328 raise SystemExit("interrupted")
329 except (IOError, os.error, PackagingError, CCompilerError) as msg:
330 raise SystemExit("error: " + str(msg))
331
332 # XXX this is crappy
333 return dist
334
335
336@action_help(list_usage)
337def _list(dispatcher, args, **kw):
338 opts = _parse_args(args[1:], '', ['all'])
339 dists = get_distributions(use_egg_info=True)
340 if 'all' in opts:
341 results = dists
342 else:
343 results = [d for d in dists if d.name.lower() in opts['args']]
344
345 for dist in results:
346 print('%s %s at %s' % (dist.name, dist.metadata['version'], dist.path))
347
348
349@action_help(search_usage)
350def _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 """
356 opts = _parse_args(args[1:], '', ['simple', 'xmlrpc'])
357 # 1. what kind of index is requested ? (xmlrpc / simple)
358
359
360actions = [
361 ('run', 'Run one or several commands', _run),
362 ('metadata', 'Display the metadata of a project', _metadata),
363 ('install', 'Install a project', _install),
364 ('remove', 'Remove a project', _remove),
365 ('search', 'Search for a project in the indexes', _search),
366 ('list', 'Search for local projects', _list),
367 ('graph', 'Display a graph', _graph),
368 ('create', 'Create a Project', _create),
369]
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
379 self.script_name = 'pysetup'
380 self.cmdclass = {}
381 self.commands = []
382 self.command_options = {}
383
384 for attr in display_option_names:
385 setattr(self, attr, False)
386
387 self.parser = FancyGetopt(global_options + display_options)
388 self.parser.set_negative_aliases(negative_opt)
389 # FIXME this parses everything, including command options (e.g. "run
390 # build -i" errors with "option -i not recognized")
391 args = self.parser.getopt(args=args, object=self)
392
393 # if first arg is "run", we have some commands
394 if len(args) == 0:
395 self.action = None
396 else:
397 self.action = args[0]
398
399 allowed = [action[0] for action in actions] + [None]
400 if self.action not in allowed:
401 msg = 'Unrecognized action "%s"' % self.action
402 raise PackagingArgError(msg)
403
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200404 self._set_logger()
405
406 # for display options we return immediately
407 option_order = self.parser.get_option_order()
408
409 self.args = args
410
411 if self.help or self.action is None:
412 self._show_help(self.parser, display_options_=False)
413
414 def _set_logger(self):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200415 # setting up the logging level from the command-line options
416 # -q gets warning, error and critical
417 if self.verbose == 0:
418 level = logging.WARNING
419 # default level or -v gets info too
420 # XXX there's a bug somewhere: the help text says that -v is default
421 # (and verbose is set to 1 above), but when the user explicitly gives
422 # -v on the command line, self.verbose is incremented to 2! Here we
423 # compensate for that (I tested manually). On a related note, I think
424 # it's a good thing to use -q/nothing/-v/-vv on the command line
425 # instead of logging constants; it will be easy to add support for
426 # logging configuration in setup.cfg for advanced users. --merwok
427 elif self.verbose in (1, 2):
428 level = logging.INFO
429 else: # -vv and more for debug
430 level = logging.DEBUG
431
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200432 # setting up the stream handler
433 handler = logging.StreamHandler(sys.stderr)
434 handler.setLevel(level)
435 logger.addHandler(handler)
436 logger.setLevel(level)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200437
438 def _parse_command_opts(self, parser, args):
439 # Pull the current command from the head of the command line
440 command = args[0]
441 if not command_re.match(command):
442 raise SystemExit("invalid command name %r" % (command,))
443 self.commands.append(command)
444
445 # Dig up the command class that implements this command, so we
446 # 1) know that it's a valid command, and 2) know which options
447 # it takes.
448 try:
449 cmd_class = get_command_class(command)
450 except PackagingModuleError as msg:
451 raise PackagingArgError(msg)
452
453 # XXX We want to push this in packaging.command
454 #
455 # Require that the command class be derived from Command -- want
456 # to be sure that the basic "command" interface is implemented.
457 for meth in ('initialize_options', 'finalize_options', 'run'):
458 if hasattr(cmd_class, meth):
459 continue
460 raise PackagingClassError(
461 'command %r must implement %r' % (cmd_class, meth))
462
463 # Also make sure that the command object provides a list of its
464 # known options.
465 if not (hasattr(cmd_class, 'user_options') and
466 isinstance(cmd_class.user_options, list)):
467 raise PackagingClassError(
468 "command class %s must provide "
469 "'user_options' attribute (a list of tuples)" % cmd_class)
470
471 # If the command class has a list of negative alias options,
472 # merge it in with the global negative aliases.
473 _negative_opt = negative_opt.copy()
474
475 if hasattr(cmd_class, 'negative_opt'):
476 _negative_opt.update(cmd_class.negative_opt)
477
478 # Check for help_options in command class. They have a different
479 # format (tuple of four) so we need to preprocess them here.
480 if (hasattr(cmd_class, 'help_options') and
481 isinstance(cmd_class.help_options, list)):
482 help_options = cmd_class.help_options[:]
483 else:
484 help_options = []
485
486 # All commands support the global options too, just by adding
487 # in 'global_options'.
488 parser.set_option_table(global_options +
489 cmd_class.user_options +
490 help_options)
491 parser.set_negative_aliases(_negative_opt)
492 args, opts = parser.getopt(args[1:])
493
494 if hasattr(opts, 'help') and opts.help:
495 self._show_command_help(cmd_class)
496 return
497
498 if (hasattr(cmd_class, 'help_options') and
499 isinstance(cmd_class.help_options, list)):
500 help_option_found = False
501 for help_option, short, desc, func in cmd_class.help_options:
502 if hasattr(opts, help_option.replace('-', '_')):
503 help_option_found = True
504 if hasattr(func, '__call__'):
505 func()
506 else:
507 raise PackagingClassError(
508 "invalid help function %r for help option %r: "
509 "must be a callable object (function, etc.)"
510 % (func, help_option))
511
512 if help_option_found:
513 return
514
515 # Put the options from the command line into their official
516 # holding pen, the 'command_options' dictionary.
517 opt_dict = self.get_option_dict(command)
518 for name, value in vars(opts).items():
519 opt_dict[name] = ("command line", value)
520
521 return args
522
523 def get_option_dict(self, command):
524 """Get the option dictionary for a given command. If that
525 command's option dictionary hasn't been created yet, then create it
526 and return the new dictionary; otherwise, return the existing
527 option dictionary.
528 """
529 d = self.command_options.get(command)
530 if d is None:
531 d = self.command_options[command] = {}
532 return d
533
534 def show_help(self):
535 self._show_help(self.parser)
536
537 def print_usage(self, parser):
538 parser.set_option_table(global_options)
539
540 actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions]
541 usage = common_usage % {'actions': '\n'.join(actions_)}
542
543 parser.print_help(usage + "\nGlobal options:")
544
545 def _show_help(self, parser, global_options_=True, display_options_=True,
546 commands=[]):
547 # late import because of mutual dependence between these modules
548 from packaging.command.cmd import Command
549
550 print('Usage: pysetup [options] action [action_options]')
551 print('')
552 if global_options_:
553 self.print_usage(self.parser)
554 print('')
555
556 if display_options_:
557 parser.set_option_table(display_options)
558 parser.print_help(
559 "Information display options (just display " +
560 "information, ignore any commands)")
561 print('')
562
563 for command in commands:
564 if isinstance(command, type) and issubclass(command, Command):
565 cls = command
566 else:
567 cls = get_command_class(command)
568 if (hasattr(cls, 'help_options') and
569 isinstance(cls.help_options, list)):
570 parser.set_option_table(cls.user_options + cls.help_options)
571 else:
572 parser.set_option_table(cls.user_options)
573
574 parser.print_help("Options for %r command:" % cls.__name__)
575 print('')
576
577 def _show_command_help(self, command):
578 if isinstance(command, str):
579 command = get_command_class(command)
580
581 name = command.get_command_name()
582
583 desc = getattr(command, 'description', '(no description available)')
584 print('Description: %s' % desc)
585 print('')
586
587 if (hasattr(command, 'help_options') and
588 isinstance(command.help_options, list)):
589 self.parser.set_option_table(command.user_options +
590 command.help_options)
591 else:
592 self.parser.set_option_table(command.user_options)
593
594 self.parser.print_help("Options:")
595 print('')
596
597 def _get_command_groups(self):
598 """Helper function to retrieve all the command class names divided
599 into standard commands (listed in
600 packaging.command.STANDARD_COMMANDS) and extra commands (given in
601 self.cmdclass and not standard commands).
602 """
603 extra_commands = [cmd for cmd in self.cmdclass
604 if cmd not in STANDARD_COMMANDS]
605 return STANDARD_COMMANDS, extra_commands
606
607 def print_commands(self):
608 """Print out a help message listing all available commands with a
609 description of each. The list is divided into standard commands
610 (listed in packaging.command.STANDARD_COMMANDS) and extra commands
611 (given in self.cmdclass and not standard commands). The
612 descriptions come from the command class attribute
613 'description'.
614 """
615 std_commands, extra_commands = self._get_command_groups()
616 max_length = max(len(command)
617 for commands in (std_commands, extra_commands)
618 for command in commands)
619
620 self.print_command_list(std_commands, "Standard commands", max_length)
621 if extra_commands:
622 print()
623 self.print_command_list(extra_commands, "Extra commands",
624 max_length)
625
626 def print_command_list(self, commands, header, max_length):
627 """Print a subset of the list of all commands -- used by
628 'print_commands()'.
629 """
630 print(header + ":")
631
632 for cmd in commands:
633 cls = self.cmdclass.get(cmd) or get_command_class(cmd)
634 description = getattr(cls, 'description',
635 '(no description available)')
636
637 print(" %-*s %s" % (max_length, cmd, description))
638
639 def __call__(self):
640 if self.action is None:
641 return
642 for action, desc, func in actions:
643 if action == self.action:
644 return func(self, self.args)
645 return -1
646
647
648def main(args=None):
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200649 old_level = logger.level
650 old_handlers = copy(logger.handlers)
651 try:
652 dispatcher = Dispatcher(args)
653 if dispatcher.action is None:
654 return
655 return dispatcher()
656 finally:
657 logger.setLevel(old_level)
658 logger.handlers[:] = old_handlers
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200659
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200660
661if __name__ == '__main__':
662 sys.exit(main())