blob: 6e4816d76fabafe6ba8b20f4b11a3fde2a2274be [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)
Tarek Ziade441531f2011-05-31 09:18:24 +0200340 if 'all' in opts or opts['args'] == []:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200341 results = dists
342 else:
343 results = [d for d in dists if d.name.lower() in opts['args']]
344
Tarek Ziade441531f2011-05-31 09:18:24 +0200345 number = 0
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200346 for dist in results:
347 print('%s %s at %s' % (dist.name, dist.metadata['version'], dist.path))
Tarek Ziade441531f2011-05-31 09:18:24 +0200348 number +=1
349
350 print('')
351 if number == 0:
352 print('Nothing seems to be installed.')
353 else:
354 print('Found %d projects installed.' % number)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200355
356
357@action_help(search_usage)
358def _search(dispatcher, args, **kw):
359 """The search action.
360
361 It is able to search for a specific index (specified with --index), using
362 the simple or xmlrpc index types (with --type xmlrpc / --type simple)
363 """
364 opts = _parse_args(args[1:], '', ['simple', 'xmlrpc'])
365 # 1. what kind of index is requested ? (xmlrpc / simple)
366
367
368actions = [
369 ('run', 'Run one or several commands', _run),
370 ('metadata', 'Display the metadata of a project', _metadata),
371 ('install', 'Install a project', _install),
372 ('remove', 'Remove a project', _remove),
373 ('search', 'Search for a project in the indexes', _search),
374 ('list', 'Search for local projects', _list),
375 ('graph', 'Display a graph', _graph),
376 ('create', 'Create a Project', _create),
377]
378
379
380class Dispatcher:
381 """Reads the command-line options
382 """
383 def __init__(self, args=None):
384 self.verbose = 1
385 self.dry_run = False
386 self.help = False
387 self.script_name = 'pysetup'
388 self.cmdclass = {}
389 self.commands = []
390 self.command_options = {}
391
392 for attr in display_option_names:
393 setattr(self, attr, False)
394
395 self.parser = FancyGetopt(global_options + display_options)
396 self.parser.set_negative_aliases(negative_opt)
397 # FIXME this parses everything, including command options (e.g. "run
398 # build -i" errors with "option -i not recognized")
399 args = self.parser.getopt(args=args, object=self)
400
401 # if first arg is "run", we have some commands
402 if len(args) == 0:
403 self.action = None
404 else:
405 self.action = args[0]
406
407 allowed = [action[0] for action in actions] + [None]
408 if self.action not in allowed:
409 msg = 'Unrecognized action "%s"' % self.action
410 raise PackagingArgError(msg)
411
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200412 self._set_logger()
413
414 # for display options we return immediately
415 option_order = self.parser.get_option_order()
416
417 self.args = args
418
419 if self.help or self.action is None:
420 self._show_help(self.parser, display_options_=False)
421
422 def _set_logger(self):
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200423 # setting up the logging level from the command-line options
424 # -q gets warning, error and critical
425 if self.verbose == 0:
426 level = logging.WARNING
427 # default level or -v gets info too
428 # XXX there's a bug somewhere: the help text says that -v is default
429 # (and verbose is set to 1 above), but when the user explicitly gives
430 # -v on the command line, self.verbose is incremented to 2! Here we
431 # compensate for that (I tested manually). On a related note, I think
432 # it's a good thing to use -q/nothing/-v/-vv on the command line
433 # instead of logging constants; it will be easy to add support for
434 # logging configuration in setup.cfg for advanced users. --merwok
435 elif self.verbose in (1, 2):
436 level = logging.INFO
437 else: # -vv and more for debug
438 level = logging.DEBUG
439
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200440 # setting up the stream handler
441 handler = logging.StreamHandler(sys.stderr)
442 handler.setLevel(level)
443 logger.addHandler(handler)
444 logger.setLevel(level)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200445
446 def _parse_command_opts(self, parser, args):
447 # Pull the current command from the head of the command line
448 command = args[0]
449 if not command_re.match(command):
450 raise SystemExit("invalid command name %r" % (command,))
451 self.commands.append(command)
452
453 # Dig up the command class that implements this command, so we
454 # 1) know that it's a valid command, and 2) know which options
455 # it takes.
456 try:
457 cmd_class = get_command_class(command)
458 except PackagingModuleError as msg:
459 raise PackagingArgError(msg)
460
461 # XXX We want to push this in packaging.command
462 #
463 # Require that the command class be derived from Command -- want
464 # to be sure that the basic "command" interface is implemented.
465 for meth in ('initialize_options', 'finalize_options', 'run'):
466 if hasattr(cmd_class, meth):
467 continue
468 raise PackagingClassError(
469 'command %r must implement %r' % (cmd_class, meth))
470
471 # Also make sure that the command object provides a list of its
472 # known options.
473 if not (hasattr(cmd_class, 'user_options') and
474 isinstance(cmd_class.user_options, list)):
475 raise PackagingClassError(
476 "command class %s must provide "
477 "'user_options' attribute (a list of tuples)" % cmd_class)
478
479 # If the command class has a list of negative alias options,
480 # merge it in with the global negative aliases.
481 _negative_opt = negative_opt.copy()
482
483 if hasattr(cmd_class, 'negative_opt'):
484 _negative_opt.update(cmd_class.negative_opt)
485
486 # Check for help_options in command class. They have a different
487 # format (tuple of four) so we need to preprocess them here.
488 if (hasattr(cmd_class, 'help_options') and
489 isinstance(cmd_class.help_options, list)):
490 help_options = cmd_class.help_options[:]
491 else:
492 help_options = []
493
494 # All commands support the global options too, just by adding
495 # in 'global_options'.
496 parser.set_option_table(global_options +
497 cmd_class.user_options +
498 help_options)
499 parser.set_negative_aliases(_negative_opt)
500 args, opts = parser.getopt(args[1:])
501
502 if hasattr(opts, 'help') and opts.help:
503 self._show_command_help(cmd_class)
504 return
505
506 if (hasattr(cmd_class, 'help_options') and
507 isinstance(cmd_class.help_options, list)):
508 help_option_found = False
509 for help_option, short, desc, func in cmd_class.help_options:
510 if hasattr(opts, help_option.replace('-', '_')):
511 help_option_found = True
512 if hasattr(func, '__call__'):
513 func()
514 else:
515 raise PackagingClassError(
516 "invalid help function %r for help option %r: "
517 "must be a callable object (function, etc.)"
518 % (func, help_option))
519
520 if help_option_found:
521 return
522
523 # Put the options from the command line into their official
524 # holding pen, the 'command_options' dictionary.
525 opt_dict = self.get_option_dict(command)
526 for name, value in vars(opts).items():
527 opt_dict[name] = ("command line", value)
528
529 return args
530
531 def get_option_dict(self, command):
532 """Get the option dictionary for a given command. If that
533 command's option dictionary hasn't been created yet, then create it
534 and return the new dictionary; otherwise, return the existing
535 option dictionary.
536 """
537 d = self.command_options.get(command)
538 if d is None:
539 d = self.command_options[command] = {}
540 return d
541
542 def show_help(self):
543 self._show_help(self.parser)
544
545 def print_usage(self, parser):
546 parser.set_option_table(global_options)
547
548 actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions]
549 usage = common_usage % {'actions': '\n'.join(actions_)}
550
551 parser.print_help(usage + "\nGlobal options:")
552
553 def _show_help(self, parser, global_options_=True, display_options_=True,
554 commands=[]):
555 # late import because of mutual dependence between these modules
556 from packaging.command.cmd import Command
557
558 print('Usage: pysetup [options] action [action_options]')
559 print('')
560 if global_options_:
561 self.print_usage(self.parser)
562 print('')
563
564 if display_options_:
565 parser.set_option_table(display_options)
566 parser.print_help(
567 "Information display options (just display " +
568 "information, ignore any commands)")
569 print('')
570
571 for command in commands:
572 if isinstance(command, type) and issubclass(command, Command):
573 cls = command
574 else:
575 cls = get_command_class(command)
576 if (hasattr(cls, 'help_options') and
577 isinstance(cls.help_options, list)):
578 parser.set_option_table(cls.user_options + cls.help_options)
579 else:
580 parser.set_option_table(cls.user_options)
581
582 parser.print_help("Options for %r command:" % cls.__name__)
583 print('')
584
585 def _show_command_help(self, command):
586 if isinstance(command, str):
587 command = get_command_class(command)
588
589 name = command.get_command_name()
590
591 desc = getattr(command, 'description', '(no description available)')
592 print('Description: %s' % desc)
593 print('')
594
595 if (hasattr(command, 'help_options') and
596 isinstance(command.help_options, list)):
597 self.parser.set_option_table(command.user_options +
598 command.help_options)
599 else:
600 self.parser.set_option_table(command.user_options)
601
602 self.parser.print_help("Options:")
603 print('')
604
605 def _get_command_groups(self):
606 """Helper function to retrieve all the command class names divided
607 into standard commands (listed in
608 packaging.command.STANDARD_COMMANDS) and extra commands (given in
609 self.cmdclass and not standard commands).
610 """
611 extra_commands = [cmd for cmd in self.cmdclass
612 if cmd not in STANDARD_COMMANDS]
613 return STANDARD_COMMANDS, extra_commands
614
615 def print_commands(self):
616 """Print out a help message listing all available commands with a
617 description of each. The list is divided into standard commands
618 (listed in packaging.command.STANDARD_COMMANDS) and extra commands
619 (given in self.cmdclass and not standard commands). The
620 descriptions come from the command class attribute
621 'description'.
622 """
623 std_commands, extra_commands = self._get_command_groups()
624 max_length = max(len(command)
625 for commands in (std_commands, extra_commands)
626 for command in commands)
627
628 self.print_command_list(std_commands, "Standard commands", max_length)
629 if extra_commands:
630 print()
631 self.print_command_list(extra_commands, "Extra commands",
632 max_length)
633
634 def print_command_list(self, commands, header, max_length):
635 """Print a subset of the list of all commands -- used by
636 'print_commands()'.
637 """
638 print(header + ":")
639
640 for cmd in commands:
641 cls = self.cmdclass.get(cmd) or get_command_class(cmd)
642 description = getattr(cls, 'description',
643 '(no description available)')
644
645 print(" %-*s %s" % (max_length, cmd, description))
646
647 def __call__(self):
648 if self.action is None:
649 return
650 for action, desc, func in actions:
651 if action == self.action:
652 return func(self, self.args)
653 return -1
654
655
656def main(args=None):
Tarek Ziadeb1b6e132011-05-30 12:07:49 +0200657 old_level = logger.level
658 old_handlers = copy(logger.handlers)
659 try:
660 dispatcher = Dispatcher(args)
661 if dispatcher.action is None:
662 return
663 return dispatcher()
664 finally:
665 logger.setLevel(old_level)
666 logger.handlers[:] = old_handlers
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200667
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200668
669if __name__ == '__main__':
670 sys.exit(main())