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