def show_formats(): """Print list of available formats (arguments to "--format" option). """ from distutils2.fancy_getopt import FancyGetopt formats = [] for format in bdist.format_commands: formats.append(("formats=" + format, None, bdist.format_command[format][1])) pretty_printer = FancyGetopt(formats) pretty_printer.print_help("List of available distribution formats:")
def show_compilers(): """Print list of available compilers (used by the "--help-compiler" options to "build", "build_ext", "build_clib"). """ # XXX this "knows" that the compiler option it's describing is # "--compiler", which just happens to be the case for the three # commands that use it. from distutils2.fancy_getopt import FancyGetopt compilers = [] for compiler in compiler_class.keys(): compilers.append(("compiler="+compiler, None, compiler_class[compiler][2])) compilers.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help("List of available compilers:")
def show_compilers(): """Print list of available compilers (used by the "--help-compiler" options to "build", "build_ext", "build_clib"). """ from distutils2.fancy_getopt import FancyGetopt compilers = [] for name, cls in _COMPILERS.items(): if isinstance(cls, str): cls = resolve_name(cls) _COMPILERS[name] = cls compilers.append(("compiler=" + name, None, cls.description)) compilers.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help("List of available compilers:")
def show_compilers(): """Print list of available compilers (used by the "--help-compiler" options to "build", "build_ext", "build_clib"). """ from distutils2.fancy_getopt import FancyGetopt compilers = [] for name, cls in _COMPILERS.items(): if isinstance(cls, basestring): cls = resolve_name(cls) _COMPILERS[name] = cls compilers.append(("compiler=" + name, None, cls.description)) compilers.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help("List of available compilers:")
class Dispatcher: """Reads the command-line options """ def __init__(self, args=None): self.verbose = 1 self.dry_run = False self.help = False self.cmdclass = {} self.commands = [] self.command_options = {} for attr in display_option_names: setattr(self, attr, False) self.parser = FancyGetopt(global_options + display_options) self.parser.set_negative_aliases(negative_opt) # FIXME this parses everything, including command options (e.g. "run # build -i" errors with "option -i not recognized") # FIXME unknown options are not detected args = self.parser.getopt(args=args, object=self) # if first arg is "run", we have some commands if len(args) == 0: self.action = None else: self.action = args[0] allowed = [action[0] for action in actions] + [None] if self.action not in allowed: self.show_help() sys.exit('error: action %r not recognized' % self.action) self._set_logger() self.args = args # for display options we return immediately if self.help or self.action is None: self._show_help(self.parser, display_options_=False) def _set_logger(self): # setting up the logging level from the command-line options # -q gets warning, error and critical if self.verbose == 0: level = logging.WARNING # default level or -v gets info too # XXX there's a bug somewhere: the help text says that -v is default # (and verbose is set to 1 above), but when the user explicitly gives # -v on the command line, self.verbose is incremented to 2! Here we # compensate for that (I tested manually). On a related note, I think # it's a good thing to use -q/nothing/-v/-vv on the command line # instead of logging constants; it will be easy to add support for # logging configuration in setup.cfg for advanced users. --merwok elif self.verbose in (1, 2): level = logging.INFO else: # -vv and more for debug level = logging.DEBUG # setting up the stream handler handler = logging.StreamHandler(sys.stderr) handler.setLevel(level) logger.addHandler(handler) logger.setLevel(level) def _parse_command_opts(self, parser, args): # Pull the current command from the head of the command line command = args[0] if not command_re.match(command): self.show_help() # TODO list only commands, not actions sys.exit('error: invalid command name %r' % command) self.commands.append(command) # Dig up the command class that implements this command, so we # 1) know that it's a valid command, and 2) know which options # it takes. try: cmd_class = get_command_class(command) except PackagingModuleError as msg: self.show_help() # TODO list only commands, not actions sys.exit('error: command %r not recognized' % command) # XXX We want to push this in distutils2.command # # Require that the command class be derived from Command -- want # to be sure that the basic "command" interface is implemented. for meth in ('initialize_options', 'finalize_options', 'run'): if hasattr(cmd_class, meth): continue raise PackagingClassError('command %r must implement %r' % (cmd_class, meth)) # Also make sure that the command object provides a list of its # known options. if not (hasattr(cmd_class, 'user_options') and isinstance(cmd_class.user_options, list)): raise PackagingClassError( "command class %s must provide " "'user_options' attribute (a list of tuples)" % cmd_class) # If the command class has a list of negative alias options, # merge it in with the global negative aliases. _negative_opt = negative_opt.copy() if hasattr(cmd_class, 'negative_opt'): _negative_opt.update(cmd_class.negative_opt) # Check for help_options in command class. They have a different # format (tuple of four) so we need to preprocess them here. if (hasattr(cmd_class, 'help_options') and isinstance(cmd_class.help_options, list)): help_options = cmd_class.help_options[:] else: help_options = [] # All commands support the global options too, just by adding # in 'global_options'. parser.set_option_table(global_options + cmd_class.user_options + help_options) parser.set_negative_aliases(_negative_opt) try: args, opts = parser.getopt(args[1:]) except PackagingArgError as msg: self.show_help() sys.exit('error: %s' % msg) if hasattr(opts, 'help') and opts.help: self._show_command_help(cmd_class) return if (hasattr(cmd_class, 'help_options') and isinstance(cmd_class.help_options, list)): help_option_found = False for help_option, short, desc, func in cmd_class.help_options: if hasattr(opts, help_option.replace('-', '_')): help_option_found = True if callable(func): func() else: raise PackagingClassError( "invalid help function %r for help option %r: " "must be a callable object (function, etc.)" % (func, help_option)) if help_option_found: return # Put the options from the command line into their official # holding pen, the 'command_options' dictionary. opt_dict = self.get_option_dict(command) for name, value in vars(opts).items(): opt_dict[name] = ("command line", value) return args def get_option_dict(self, command): """Get the option dictionary for a given command. If that command's option dictionary hasn't been created yet, then create it and return the new dictionary; otherwise, return the existing option dictionary. """ d = self.command_options.get(command) if d is None: d = self.command_options[command] = {} return d def show_help(self): self._show_help(self.parser) def print_usage(self, parser): parser.set_option_table(global_options) actions_ = [' %s: %s' % (name, desc) for name, desc, __ in actions] usage = common_usage % {'actions': '\n'.join(actions_)} parser.print_help(usage + "\nGlobal options:") def _show_help(self, parser, global_options_=True, display_options_=True, commands=[]): # XXX want to print to stdout when help is requested (--help) but to # stderr in case of error! print('Usage: pysetup [options] action [action_options]') print() if global_options_: self.print_usage(self.parser) print() if display_options_: parser.set_option_table(display_options) parser.print_help("Information display options (just display " + "information, ignore any commands)") print() for command in commands: if isinstance(command, type) and issubclass(command, Command): cls = command else: cls = get_command_class(command) if (hasattr(cls, 'help_options') and isinstance(cls.help_options, list)): parser.set_option_table(cls.user_options + cls.help_options) else: parser.set_option_table(cls.user_options) parser.print_help("Options for %r command:" % cls.__name__) print() def _show_command_help(self, command): if isinstance(command, str): command = get_command_class(command) desc = getattr(command, 'description', '(no description available)') print('Description:', desc) print() if (hasattr(command, 'help_options') and isinstance(command.help_options, list)): self.parser.set_option_table(command.user_options + command.help_options) else: self.parser.set_option_table(command.user_options) self.parser.print_help("Options:") print() def _get_command_groups(self): """Helper function to retrieve all the command class names divided into standard commands (listed in distutils2.command.STANDARD_COMMANDS) and extra commands (given in self.cmdclass and not standard commands). """ extra_commands = [ cmd for cmd in self.cmdclass if cmd not in STANDARD_COMMANDS ] return STANDARD_COMMANDS, extra_commands def print_commands(self): """Print out a help message listing all available commands with a description of each. The list is divided into standard commands (listed in distutils2.command.STANDARD_COMMANDS) and extra commands (given in self.cmdclass and not standard commands). The descriptions come from the command class attribute 'description'. """ std_commands, extra_commands = self._get_command_groups() max_length = max( len(command) for commands in (std_commands, extra_commands) for command in commands) self.print_command_list(std_commands, "Standard commands", max_length) if extra_commands: print() self.print_command_list(extra_commands, "Extra commands", max_length) def print_command_list(self, commands, header, max_length): """Print a subset of the list of all commands -- used by 'print_commands()'. """ print(header + ":") for cmd in commands: cls = self.cmdclass.get(cmd) or get_command_class(cmd) description = getattr(cls, 'description', '(no description available)') print(" %-*s %s" % (max_length, cmd, description)) def __call__(self): if self.action is None: return for action, desc, func in actions: if action == self.action: return func(self, self.args) return -1