blob: 1a246c5656afc83faa313c57e0cd6375d930e76e [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:
Tarek Ziade5a5ce382011-05-31 12:09:34 +0200228 logger.warning('No project to install.')
229 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200230
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):
Tarek Ziade5a5ce382011-05-31 12:09:34 +0200234 if install_local_project(target):
235 return 0
236 else:
237 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200238 else:
239 # download from PyPI
Tarek Ziade5a5ce382011-05-31 12:09:34 +0200240 if install(target):
241 return 0
242 else:
243 return 1
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200244
245
246@action_help(metadata_usage)
247def _metadata(dispatcher, args, **kw):
248 opts = _parse_args(args[1:], 'f:', ['all'])
249 if opts['args']:
250 name = opts['args'][0]
251 dist = get_distribution(name, use_egg_info=True)
252 if dist is None:
253 logger.warning('%s not installed', name)
254 return
255 else:
256 logger.info('searching local dir for metadata')
257 dist = Distribution()
258 dist.parse_config_files()
259
260 metadata = dist.metadata
261
262 if 'all' in opts:
263 keys = metadata.keys()
264 else:
265 if 'f' in opts:
266 keys = (k for k in opts['f'] if k in metadata)
267 else:
268 keys = ()
269
270 for key in keys:
271 if key in metadata:
272 print(metadata._convert_name(key) + ':')
273 value = metadata[key]
274 if isinstance(value, list):
275 for v in value:
276 print(' ' + v)
277 else:
278 print(' ' + value.replace('\n', '\n '))
279
280
281@action_help(remove_usage)
282def _remove(distpatcher, args, **kw):
283 opts = _parse_args(args[1:], 'y', [])
284 if 'y' in opts:
285 auto_confirm = True
286 else:
287 auto_confirm = False
288
289 for dist in set(opts['args']):
290 try:
291 remove(dist, auto_confirm=auto_confirm)
292 except PackagingError:
293 logger.warning('%s not installed', dist)
294
295
296@action_help(run_usage)
297def _run(dispatcher, args, **kw):
298 parser = dispatcher.parser
299 args = args[1:]
300
301 commands = STANDARD_COMMANDS # + extra commands
302
303 if args == ['--list-commands']:
304 print('List of available commands:')
305 cmds = sorted(commands)
306
307 for cmd in cmds:
308 cls = dispatcher.cmdclass.get(cmd) or get_command_class(cmd)
309 desc = getattr(cls, 'description',
310 '(no description available)')
311 print(' %s: %s' % (cmd, desc))
312 return
313
314 while args:
315 args = dispatcher._parse_command_opts(parser, args)
316 if args is None:
317 return
318
319 # create the Distribution class
320 # need to feed setup.cfg here !
321 dist = Distribution()
322
323 # Find and parse the config file(s): they will override options from
324 # the setup script, but be overridden by the command line.
325
326 # XXX still need to be extracted from Distribution
327 dist.parse_config_files()
328
329 try:
330 for cmd in dispatcher.commands:
331 dist.run_command(cmd, dispatcher.command_options[cmd])
332
333 except KeyboardInterrupt:
334 raise SystemExit("interrupted")
335 except (IOError, os.error, PackagingError, CCompilerError) as msg:
336 raise SystemExit("error: " + str(msg))
337
338 # XXX this is crappy
339 return dist
340
341
342@action_help(list_usage)
343def _list(dispatcher, args, **kw):
344 opts = _parse_args(args[1:], '', ['all'])
345 dists = get_distributions(use_egg_info=True)
Tarek Ziade441531f2011-05-31 09:18:24 +0200346 if 'all' in opts or opts['args'] == []:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200347 results = dists
348 else:
349 results = [d for d in dists if d.name.lower() in opts['args']]
350
Tarek Ziade441531f2011-05-31 09:18:24 +0200351 number = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200352 for dist in results:
353 print('%s %s at %s' % (dist.name, dist.metadata['version'], dist.path))
Tarek Ziade441531f2011-05-31 09:18:24 +0200354 number +=1
355
356 print('')
357 if number == 0:
358 print('Nothing seems to be installed.')
359 else:
360 print('Found %d projects installed.' % number)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200361
362
363@action_help(search_usage)
364def _search(dispatcher, args, **kw):
365 """The search action.
366
367 It is able to search for a specific index (specified with --index), using
368 the simple or xmlrpc index types (with --type xmlrpc / --type simple)
369 """
370 opts = _parse_args(args[1:], '', ['simple', 'xmlrpc'])
371 # 1. what kind of index is requested ? (xmlrpc / simple)
372
373
374actions = [
375 ('run', 'Run one or several commands', _run),
376 ('metadata', 'Display the metadata of a project', _metadata),
377 ('install', 'Install a project', _install),
378 ('remove', 'Remove a project', _remove),
379 ('search', 'Search for a project in the indexes', _search),
380 ('list', 'Search for local projects', _list),
381 ('graph', 'Display a graph', _graph),
382 ('create', 'Create a Project', _create),
383]
384
385
386class Dispatcher:
387 """Reads the command-line options
388 """
389 def __init__(self, args=None):
390 self.verbose = 1
391 self.dry_run = False
392 self.help = False
393 self.script_name = 'pysetup'
394 self.cmdclass = {}
395 self.commands = []
396 self.command_options = {}
397
398 for attr in display_option_names:
399 setattr(self, attr, False)
400
401 self.parser = FancyGetopt(global_options + display_options)
402 self.parser.set_negative_aliases(negative_opt)
403 # FIXME this parses everything, including command options (e.g. "run
404 # build -i" errors with "option -i not recognized")
405 args = self.parser.getopt(args=args, object=self)
406
407 # if first arg is "run", we have some commands
408 if len(args) == 0:
409 self.action = None
410 else:
411 self.action = args[0]
412
413 allowed = [action[0] for action in actions] + [None]
414 if self.action not in allowed:
415 msg = 'Unrecognized action "%s"' % self.action
416 raise PackagingArgError(msg)
417
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200418 self._set_logger()
419
420 # for display options we return immediately
421 option_order = self.parser.get_option_order()
422
423 self.args = args
424
425 if self.help or self.action is None:
426 self._show_help(self.parser, display_options_=False)
427
428 def _set_logger(self):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200429 # setting up the logging level from the command-line options
430 # -q gets warning, error and critical
431 if self.verbose == 0:
432 level = logging.WARNING
433 # default level or -v gets info too
434 # XXX there's a bug somewhere: the help text says that -v is default
435 # (and verbose is set to 1 above), but when the user explicitly gives
436 # -v on the command line, self.verbose is incremented to 2! Here we
437 # compensate for that (I tested manually). On a related note, I think
438 # it's a good thing to use -q/nothing/-v/-vv on the command line
439 # instead of logging constants; it will be easy to add support for
440 # logging configuration in setup.cfg for advanced users. --merwok
441 elif self.verbose in (1, 2):
442 level = logging.INFO
443 else: # -vv and more for debug
444 level = logging.DEBUG
445
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200446 # setting up the stream handler
447 handler = logging.StreamHandler(sys.stderr)
448 handler.setLevel(level)
449 logger.addHandler(handler)
450 logger.setLevel(level)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200451
452 def _parse_command_opts(self, parser, args):
453 # Pull the current command from the head of the command line
454 command = args[0]
455 if not command_re.match(command):
456 raise SystemExit("invalid command name %r" % (command,))
457 self.commands.append(command)
458
459 # Dig up the command class that implements this command, so we
460 # 1) know that it's a valid command, and 2) know which options
461 # it takes.
462 try:
463 cmd_class = get_command_class(command)
464 except PackagingModuleError as msg:
465 raise PackagingArgError(msg)
466
467 # XXX We want to push this in packaging.command
468 #
469 # Require that the command class be derived from Command -- want
470 # to be sure that the basic "command" interface is implemented.
471 for meth in ('initialize_options', 'finalize_options', 'run'):
472 if hasattr(cmd_class, meth):
473 continue
474 raise PackagingClassError(
475 'command %r must implement %r' % (cmd_class, meth))
476
477 # Also make sure that the command object provides a list of its
478 # known options.
479 if not (hasattr(cmd_class, 'user_options') and
480 isinstance(cmd_class.user_options, list)):
481 raise PackagingClassError(
482 "command class %s must provide "
483 "'user_options' attribute (a list of tuples)" % cmd_class)
484
485 # If the command class has a list of negative alias options,
486 # merge it in with the global negative aliases.
487 _negative_opt = negative_opt.copy()
488
489 if hasattr(cmd_class, 'negative_opt'):
490 _negative_opt.update(cmd_class.negative_opt)
491
492 # Check for help_options in command class. They have a different
493 # format (tuple of four) so we need to preprocess them here.
494 if (hasattr(cmd_class, 'help_options') and
495 isinstance(cmd_class.help_options, list)):
496 help_options = cmd_class.help_options[:]
497 else:
498 help_options = []
499
500 # All commands support the global options too, just by adding
501 # in 'global_options'.
502 parser.set_option_table(global_options +
503 cmd_class.user_options +
504 help_options)
505 parser.set_negative_aliases(_negative_opt)
506 args, opts = parser.getopt(args[1:])
507
508 if hasattr(opts, 'help') and opts.help:
509 self._show_command_help(cmd_class)
510 return
511
512 if (hasattr(cmd_class, 'help_options') and
513 isinstance(cmd_class.help_options, list)):
514 help_option_found = False
515 for help_option, short, desc, func in cmd_class.help_options:
516 if hasattr(opts, help_option.replace('-', '_')):
517 help_option_found = True
518 if hasattr(func, '__call__'):
519 func()
520 else:
521 raise PackagingClassError(
522 "invalid help function %r for help option %r: "
523 "must be a callable object (function, etc.)"
524 % (func, help_option))
525
526 if help_option_found:
527 return
528
529 # Put the options from the command line into their official
530 # holding pen, the 'command_options' dictionary.
531 opt_dict = self.get_option_dict(command)
532 for name, value in vars(opts).items():
533 opt_dict[name] = ("command line", value)
534
535 return args
536
537 def get_option_dict(self, command):
538 """Get the option dictionary for a given command. If that
539 command's option dictionary hasn't been created yet, then create it
540 and return the new dictionary; otherwise, return the existing
541 option dictionary.
542 """
543 d = self.command_options.get(command)
544 if d is None:
545 d = self.command_options[command] = {}
546 return d
547
548 def show_help(self):
549 self._show_help(self.parser)
550
551 def print_usage(self, parser):
552 parser.set_option_table(global_options)
553
554 actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions]
555 usage = common_usage % {'actions': '\n'.join(actions_)}
556
557 parser.print_help(usage + "\nGlobal options:")
558
559 def _show_help(self, parser, global_options_=True, display_options_=True,
560 commands=[]):
561 # late import because of mutual dependence between these modules
562 from packaging.command.cmd import Command
563
564 print('Usage: pysetup [options] action [action_options]')
565 print('')
566 if global_options_:
567 self.print_usage(self.parser)
568 print('')
569
570 if display_options_:
571 parser.set_option_table(display_options)
572 parser.print_help(
573 "Information display options (just display " +
574 "information, ignore any commands)")
575 print('')
576
577 for command in commands:
578 if isinstance(command, type) and issubclass(command, Command):
579 cls = command
580 else:
581 cls = get_command_class(command)
582 if (hasattr(cls, 'help_options') and
583 isinstance(cls.help_options, list)):
584 parser.set_option_table(cls.user_options + cls.help_options)
585 else:
586 parser.set_option_table(cls.user_options)
587
588 parser.print_help("Options for %r command:" % cls.__name__)
589 print('')
590
591 def _show_command_help(self, command):
592 if isinstance(command, str):
593 command = get_command_class(command)
594
595 name = command.get_command_name()
596
597 desc = getattr(command, 'description', '(no description available)')
598 print('Description: %s' % desc)
599 print('')
600
601 if (hasattr(command, 'help_options') and
602 isinstance(command.help_options, list)):
603 self.parser.set_option_table(command.user_options +
604 command.help_options)
605 else:
606 self.parser.set_option_table(command.user_options)
607
608 self.parser.print_help("Options:")
609 print('')
610
611 def _get_command_groups(self):
612 """Helper function to retrieve all the command class names divided
613 into standard commands (listed in
614 packaging.command.STANDARD_COMMANDS) and extra commands (given in
615 self.cmdclass and not standard commands).
616 """
617 extra_commands = [cmd for cmd in self.cmdclass
618 if cmd not in STANDARD_COMMANDS]
619 return STANDARD_COMMANDS, extra_commands
620
621 def print_commands(self):
622 """Print out a help message listing all available commands with a
623 description of each. The list is divided into standard commands
624 (listed in packaging.command.STANDARD_COMMANDS) and extra commands
625 (given in self.cmdclass and not standard commands). The
626 descriptions come from the command class attribute
627 'description'.
628 """
629 std_commands, extra_commands = self._get_command_groups()
630 max_length = max(len(command)
631 for commands in (std_commands, extra_commands)
632 for command in commands)
633
634 self.print_command_list(std_commands, "Standard commands", max_length)
635 if extra_commands:
636 print()
637 self.print_command_list(extra_commands, "Extra commands",
638 max_length)
639
640 def print_command_list(self, commands, header, max_length):
641 """Print a subset of the list of all commands -- used by
642 'print_commands()'.
643 """
644 print(header + ":")
645
646 for cmd in commands:
647 cls = self.cmdclass.get(cmd) or get_command_class(cmd)
648 description = getattr(cls, 'description',
649 '(no description available)')
650
651 print(" %-*s %s" % (max_length, cmd, description))
652
653 def __call__(self):
654 if self.action is None:
655 return
656 for action, desc, func in actions:
657 if action == self.action:
658 return func(self, self.args)
659 return -1
660
661
662def main(args=None):
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200663 old_level = logger.level
664 old_handlers = copy(logger.handlers)
665 try:
666 dispatcher = Dispatcher(args)
667 if dispatcher.action is None:
668 return
669 return dispatcher()
670 finally:
671 logger.setLevel(old_level)
672 logger.handlers[:] = old_handlers
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200673
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200674
675if __name__ == '__main__':
676 sys.exit(main())