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