Exemple #1
0
    def get_command_obj(self, command, create=True):
        """Return the command object for 'command'.  Normally this object
        is cached on a previous call to 'get_command_obj()'; if no command
        object for 'command' is in the cache, then we either create and
        return it (if 'create' is true) or return None.
        """
        cmd_obj = self.command_obj.get(command)
        if not cmd_obj and create:
            logger.debug(
                "Distribution.get_command_obj(): "
                "creating %r command object", command)

            cls = get_command_class(command)
            cmd_obj = self.command_obj[command] = cls(self)
            self.have_run[command] = 0

            # Set any options that were supplied in config files or on the
            # command line.  (XXX support for error reporting is suboptimal
            # here: errors aren't reported until finalize_options is called,
            # which means we won't report the source of the error.)
            options = self.command_options.get(command)
            if options:
                self._set_command_options(cmd_obj, options)

        return cmd_obj
Exemple #2
0
def _run(dispatcher, args, **kw):
    parser = dispatcher.parser
    args = args[1:]

    # Find and parse the config file(s): they will override options from
    # the setup script, but be overridden by the command line.
    # XXX call the functions from config and kill the Distribution class
    # (merging it into Dispatcher)
    dist = Distribution()
    dist.parse_config_files()

    commands = STANDARD_COMMANDS  # FIXME display extra commands

    if args == ['--list-commands']:
        print 'List of available commands:'
        for cmd in commands:
            cls = dispatcher.cmdclass.get(cmd) or get_command_class(cmd)
            desc = getattr(cls, 'description', '(no description available)')
            print '  %s: %s' % (cmd, desc)
        return

    while args:
        args = dispatcher._parse_command_opts(parser, args)
        if args is None:
            return

    for cmd in dispatcher.commands:
        # FIXME need to catch MetadataMissingError here (from the check command
        # e.g.)--or catch any exception, print an error message and exit with 1
        dist.run_command(cmd, dispatcher.command_options[cmd])

    return 0
Exemple #3
0
    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
Exemple #4
0
    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()
Exemple #5
0
def _run(dispatcher, args, **kw):
    parser = dispatcher.parser
    args = args[1:]

    # Find and parse the config file(s): they will override options from
    # the setup script, but be overridden by the command line.
    # XXX call the functions from config and kill the Distribution class
    # (merging it into Dispatcher)
    dist = Distribution()
    dist.parse_config_files()

    commands = STANDARD_COMMANDS  # FIXME display extra commands

    if args == ['--list-commands']:
        print('List of available commands:')
        for cmd in commands:
            cls = dispatcher.cmdclass.get(cmd) or get_command_class(cmd)
            desc = getattr(cls, 'description', '(no description available)')
            print('  %s: %s' % (cmd, desc))
        return

    while args:
        args = dispatcher._parse_command_opts(parser, args)
        if args is None:
            return

    for cmd in dispatcher.commands:
        # FIXME need to catch MetadataMissingError here (from the check command
        # e.g.)--or catch any exception, print an error message and exit with 1
        dist.run_command(cmd, dispatcher.command_options[cmd])

    return 0
Exemple #6
0
    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))
Exemple #7
0
    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)
Exemple #8
0
    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, msg:
            self.show_help()  # TODO list only commands, not actions
            sys.exit('error: command %r not recognized' % command)
Exemple #9
0
    def _show_help(self,
                   parser,
                   global_options=True,
                   display_options=True,
                   commands=[]):
        """Show help for the setup script command line in the form of
        several lists of command-line options.  'parser' should be a
        FancyGetopt instance; do not expect it to be returned in the
        same state, as its option table will be reset to make it
        generate the correct help text.

        If 'global_options' is true, lists the global options:
        --dry-run, etc.  If 'display_options' is true, lists
        the "display-only" options: --help-commands.  Finally,
        lists per-command help for every command name or command class
        in 'commands'.
        """
        if global_options:
            if display_options:
                options = self._get_toplevel_options()
            else:
                options = self.global_options
            parser.set_option_table(options)
            parser.print_help(self.common_usage + "\nGlobal options:")
            print()

        if display_options:
            parser.set_option_table(self.display_options)
            parser.print_help("Information display options (just display " +
                              "information, ignore any commands)")
            print()

        for command in self.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()

        print(gen_usage(self.script_name))
Exemple #10
0
    def _show_command_help(self, command):
        if isinstance(command, basestring):
            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
Exemple #11
0
    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()
Exemple #12
0
    def _show_help(self, parser, global_options=True, display_options=True,
                   commands=[]):
        """Show help for the setup script command line in the form of
        several lists of command-line options.  'parser' should be a
        FancyGetopt instance; do not expect it to be returned in the
        same state, as its option table will be reset to make it
        generate the correct help text.

        If 'global_options' is true, lists the global options:
        --dry-run, etc.  If 'display_options' is true, lists
        the "display-only" options: --help-commands.  Finally,
        lists per-command help for every command name or command class
        in 'commands'.
        """
        if global_options:
            if display_options:
                options = self._get_toplevel_options()
            else:
                options = self.global_options
            parser.set_option_table(options)
            parser.print_help(self.common_usage + "\nGlobal options:")
            print

        if display_options:
            parser.set_option_table(self.display_options)
            parser.print_help(
                "Information display options (just display " +
                "information, ignore any commands)")
            print

        for command in self.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

        print gen_usage(self.script_name)
Exemple #13
0
    def _parse_command_opts(self, parser, args):
        """Parse the command-line options for a single command.
        'parser' must be a FancyGetopt instance; 'args' must be the list
        of arguments, starting with the current command (whose options
        we are about to parse).  Returns a new version of 'args' with
        the next command at the front of the list; will be the empty
        list if there are no more commands on the command line.  Returns
        None if the user asked for help on this command.
        """
        # Pull the current command from the head of the command line
        command = args[0]
        if not command_re.match(command):
            raise SystemExit("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, msg:
            raise PackagingArgError(msg)
Exemple #14
0
    def get_command_obj(self, command, create=True):
        """Return the command object for 'command'.  Normally this object
        is cached on a previous call to 'get_command_obj()'; if no command
        object for 'command' is in the cache, then we either create and
        return it (if 'create' is true) or return None.
        """
        cmd_obj = self.command_obj.get(command)
        if not cmd_obj and create:
            logger.debug("Distribution.get_command_obj(): "
                         "creating %r command object", command)

            cls = get_command_class(command)
            cmd_obj = self.command_obj[command] = cls(self)
            self.have_run[command] = 0

            # Set any options that were supplied in config files or on the
            # command line.  (XXX support for error reporting is suboptimal
            # here: errors aren't reported until finalize_options is called,
            # which means we won't report the source of the error.)
            options = self.command_options.get(command)
            if options:
                self._set_command_options(cmd_obj, options)

        return cmd_obj
Exemple #15
0
    def _parse_command_opts(self, parser, args):
        """Parse the command-line options for a single command.
        'parser' must be a FancyGetopt instance; 'args' must be the list
        of arguments, starting with the current command (whose options
        we are about to parse).  Returns a new version of 'args' with
        the next command at the front of the list; will be the empty
        list if there are no more commands on the command line.  Returns
        None if the user asked for help on this command.
        """
        # Pull the current command from the head of the command line
        command = args[0]
        if not command_re.match(command):
            raise SystemExit("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:
            raise PackagingArgError(msg)

        # 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 = self.negative_opt
        if hasattr(cmd_class, 'negative_opt'):
            negative_opt = negative_opt.copy()
            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(self.global_options + cmd_class.user_options +
                                help_options)
        parser.set_negative_aliases(negative_opt)
        args, opts = parser.getopt(args[1:])
        if hasattr(opts, 'help') and opts.help:
            self._show_help(parser,
                            display_options=False,
                            commands=[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 not callable(func):
                        raise PackagingClassError(
                            "invalid help function %r for help option %r: "
                            "must be a callable object (function, etc.)" %
                            (func, help_option))
                    func()

            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
Exemple #16
0
    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