Exemplo n.º 1
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('-l', '--for-real',
                            dest='for_real',
                            action='store_true',
                            default=False,
                            help="Actually change message flags. Default is a dry run.")

        parser.add_argument('-f', '--flag',
                            dest='flag',
                            type=str,
                            help="The flag to add of remove")

        parser.add_argument('-o', '--op',
                            dest='op',
                            type=str,
                            help="The operation to do: 'add' or 'remove'")

        parser.add_argument('-u', '--until',
                            dest='all_until',
                            type=str,
                            help="Mark all messages <= specific usermessage id")

        parser.add_argument('-m', '--email',
                            dest='email',
                            type=str,
                            help="Email to set messages for")
        self.add_realm_args(parser)
Exemplo n.º 2
0
    def add_arguments(self, parser: CommandParser) -> None:
        super().add_arguments(parser)

        parser.add_argument(
            '--strict', '-s',
            action='store_true',
            default=False,
            help='Stop execution in case of errors.')
Exemplo n.º 3
0
 def add_arguments(self, parser: CommandParser) -> None:
     default_cutoff = time.time() - 60 * 60 * 24 * 30  # 30 days.
     self.add_realm_args(parser, True)
     parser.add_argument('--since',
                         dest='since',
                         type=int,
                         default=default_cutoff,
                         help='The time in epoch since from which to start the dump.')
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('-s', '--stream',
                            dest='stream',
                            required=True,
                            type=str,
                            help='A stream name.')

        self.add_realm_args(parser, True)
        self.add_user_list_args(parser, all_users_help='Remove all users in realm from this stream.')
Exemplo n.º 5
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('hipchat_tar', nargs='+',
                            metavar='<hipchat data tarfile>',
                            help="tar of Hipchat data")

        parser.add_argument('--output', dest='output_dir',
                            action="store",
                            help='Directory to write exported data to.')

        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 6
0
    def add_arguments(self, parser: CommandParser) -> None:
        self.add_realm_args(parser, True)
        self.add_user_list_args(parser, all_users_help="Add all users in realm to these streams.")

        parser.add_argument(
            '-s', '--streams',
            dest='streams',
            type=str,
            required=True,
            help='A comma-separated list of stream names.')
 def add_arguments(self, parser: CommandParser) -> None:
     self.add_realm_args(parser)
     parser.add_argument(
         '--lookback-hours',
         dest='lookback_hours',
         type=int,
         help="Period a bit larger than that of the cron job that runs "
              "this command so that the lookback periods are sure to overlap.",
         required=True,
     )
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('-f', '--fixture',
                            dest='fixture',
                            type=str,
                            help='The path to the fixture you\'d like to send '
                                 'into Zulip')

        parser.add_argument('-u', '--url',
                            dest='url',
                            type=str,
                            help='The url on your Zulip server that you want '
                                 'to post the fixture to')

        self.add_realm_args(parser, help="Specify which realm/subdomain to connect to; default is zulip")
Exemplo n.º 9
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('-f', '--fixture',
                            dest='fixture',
                            type=str,
                            help='The path to the email message you\'d like to send '
                                 'to the email mirror.\n'
                                 'Accepted formats: json or raw email file. '
                                 'See zerver/tests/fixtures/email/ for examples')
        parser.add_argument('-s', '--stream',
                            dest='stream',
                            type=str,
                            help='The name of the stream to which you\'d like to send '
                            'the message. Default: Denmark')

        self.add_realm_args(parser, help="Specify which realm to connect to; default is zulip")
Exemplo n.º 10
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        no_settings_commands = [
            'help', 'version', '--help', '--version', '-h',
            'compilemessages', 'makemessages',
            'startapp', 'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
Exemplo n.º 11
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('slack_data_zip', nargs='+',
                            metavar='<slack data zip>',
                            help="Zipped slack data")

        parser.add_argument('realm_name', metavar='<realm_name>',
                            type=str, help="Realm Name")

        parser.add_argument('--token', metavar='<slack_token>',
                            type=str, help='Slack legacy token of the organsation')

        parser.add_argument('--output', dest='output_dir',
                            action="store", default=None,
                            help='Directory to write exported data to.')
        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 12
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('slack_data_zip', nargs='+',
                            metavar='<slack data zip>',
                            help="Zipped slack data")

        parser.add_argument('--token', metavar='<slack_token>',
                            type=str, help='Slack legacy token of the organsation')

        parser.add_argument('--output', dest='output_dir',
                            action="store", default=None,
                            help='Directory to write exported data to.')

        parser.add_argument('--threads',
                            dest='threads',
                            action="store",
                            default=6,
                            help='Threads to use in exporting UserMessage objects in parallel')

        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 13
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('--destroy-rebuild-database',
                            dest='destroy_rebuild_database',
                            default=False,
                            action="store_true",
                            help='Destroys and rebuilds the databases prior to import.')

        parser.add_argument('--import-into-nonempty',
                            dest='import_into_nonempty',
                            default=False,
                            action="store_true",
                            help='Import into an existing nonempty database.')

        parser.add_argument('subdomain', metavar='<subdomain>',
                            type=str, help="Subdomain")

        parser.add_argument('export_paths', nargs='+',
                            metavar='<export path>',
                            help="list of export directories to import")
        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 14
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('addrport', nargs="?", type=str,
                            help='[optional port number or ipaddr:port]\n '
                                 '(use multiple ports to start multiple servers)')

        parser.add_argument('--nokeepalive', action='store_true',
                            dest='no_keep_alive', default=False,
                            help="Tells Tornado to NOT keep alive http connections.")

        parser.add_argument('--noxheaders', action='store_false',
                            dest='xheaders', default=True,
                            help="Tells Tornado to NOT override remote IP with X-Real-IP.")
Exemplo n.º 15
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('gitter_data', nargs='+',
                            metavar='<gitter data>',
                            help="Gitter data in json format")

        parser.add_argument('--output', dest='output_dir',
                            action="store", default=None,
                            help='Directory to write exported data to.')

        parser.add_argument('--threads',
                            dest='threads',
                            action="store",
                            default=6,
                            help='Threads to download avatars and attachments faster')

        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 16
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('--destroy-rebuild-database',
                            dest='destroy_rebuild_database',
                            default=False,
                            action="store_true",
                            help='Destroys and rebuilds the databases prior to import.')

        parser.add_argument('--import-into-nonempty',
                            dest='import_into_nonempty',
                            default=False,
                            action="store_true",
                            help='Import into an existing nonempty database.')

        parser.add_argument('export_files', nargs='+',
                            metavar='<export file>',
                            help="list of JSON exports to import")
        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 17
0
def run_default_tests(command_line_args):
    # This reproduces the logic used by execute_from_command_line to
    # extra whether the subcommand is "test" and whether a settings
    # module has been manually specified.
    try:
        subcommand = command_line_args[1]
    except IndexError:
        return False

    parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
    parser.add_argument('--settings')
    parser.add_argument('--pythonpath')
    parser.add_argument('args', nargs='*')
    try:
        options, args = parser.parse_known_args(command_line_args[2:])
    except CommandError:
        # Ignore any errors, we just wanted to extract any settings option
        # that might have been specified.
        options = {'settings': None}

    return subcommand == 'test' and not options.settings
Exemplo n.º 18
0
    def add_arguments(self, parser: CommandParser) -> None:
        self.add_general_args(parser)
        self.add_algorithm(parser)

        self.add_key_type(parser)
        self.add_key_size(parser)
        self.add_ecc_curve(parser)

        parser.add_argument(
            "--expires",
            metavar="DAYS",
            action=ExpiresAction,
            default=timedelta(365 * 10),
            help="CA certificate expires in DAYS days (default: %(default)s).",
        )
        self.add_ca(
            parser,
            "--parent",
            no_default=True,
            help_text=
            "Make the CA an intermediate CA of the named CA. By default, this is a new root CA.",
        )
        parser.add_argument("name", help="Human-readable name of the CA")
        parser.add_argument(
            "subject",
            action=NameAction,
            help=
            'The subject of the CA in the format "/key1=value1/key2=value2/...", requires at least a'
            "CommonName to be present (/CN=...).",
        )
        self.add_password(
            parser,
            help_text=
            "Optional password used to encrypt the private key. If no argument is passed, "
            "you will be prompted.",
        )
        parser.add_argument(
            "--path",
            type=pathlib.PurePath,
            help=
            "Path where to store Certificate Authorities (relative to CA_DIR).",
        )
        parser.add_argument(
            "--parent-password",
            nargs="?",
            action=PasswordAction,
            metavar="PASSWORD",
            prompt="Password for parent CA: ",
            help="Password for the private key of any parent CA.",
        )

        group = parser.add_argument_group(
            "Default hostname",
            f"""The default hostname is used to compute default URLs for services like OCSP. The hostname is
            usually configured in your settings (current setting: {ca_settings.CA_DEFAULT_HOSTNAME}), but you
            can override that value here. The value must be just the hostname and optionally a port, *without*
            a protocol, e.g.  "ca.example.com" or "ca.example.com:8000".""",
        )
        group = group.add_mutually_exclusive_group()
        group.add_argument(
            "--default-hostname",
            metavar="HOSTNAME",
            help=
            "Override the the default hostname configured in your settings.",
        )
        group.add_argument(
            "--no-default-hostname",
            dest="default_hostname",
            action="store_false",
            help="Disable any default hostname configured in your settings.",
        )

        self.add_acme_group(parser)

        group = parser.add_argument_group(
            "pathlen attribute",
            """Maximum number of CAs that can appear below this one. A pathlen of zero (the default) means it
            can only be used to sign end user certificates and not further CAs.""",
        )
        group = group.add_mutually_exclusive_group()
        group.add_argument(
            "--pathlen",
            default=0,
            type=int,
            help="Maximum number of sublevel CAs (default: %(default)s).")
        group.add_argument(
            "--no-pathlen",
            action="store_const",
            const=None,
            dest="pathlen",
            help="Do not add a pathlen attribute.",
        )

        group = parser.add_argument_group(
            "X509 v3 certificate extensions for CA",
            """Extensions added to the certificate authority itself. These options cannot be changed without
            creating a new authority.""",
        )
        group.add_argument(
            "--ca-crl-url",
            action=MultipleURLAction,
            help=
            "URL to a certificate revokation list. Can be given multiple times.",
        )
        group.add_argument("--ca-ocsp-url",
                           metavar="URL",
                           action=URLAction,
                           help="URL of an OCSP responder.")
        group.add_argument(
            "--ca-issuer-url",
            metavar="URL",
            action=URLAction,
            help="URL to the certificate of your CA (in DER format).",
        )

        nc_group = parser.add_argument_group(
            "Name Constraints",
            "Add name constraints to the CA, limiting what certificates this CA can sign."
        )
        nc_group.add_argument(
            "--permit-name",
            metavar="NAME",
            action="append",
            default=[],
            help="Add the given name to the permitted-subtree.",
        )
        nc_group.add_argument(
            "--exclude-name",
            metavar="NAME",
            action="append",
            default=[],
            help="Add the given name to the excluded-subtree.",
        )

        self.add_ca_args(parser)
Exemplo n.º 19
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument("email", metavar="<email>", type=str, help="Email address of the user")
     self.add_realm_args(parser)
Exemplo n.º 20
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('hipchat_tar', nargs='+',
                            metavar='<hipchat data tarfile>',
                            help="tar of Hipchat data")

        parser.add_argument('--output', dest='output_dir',
                            action="store",
                            help='Directory to write exported data to.')

        parser.add_argument('--mask', dest='masking_content',
                            action="store_true",
                            help='Mask the content for privacy during QA.')

        parser.add_argument('--slim-mode',
                            action="store_true",
                            help="Default to no public stream subscriptions if no token is available." +
                            "  See import docs for details.")

        parser.add_argument('--token', dest='api_token',
                            action="store",
                            help='API token for the HipChat API for fetching subscribers.')

        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 21
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('-n', '--num-messages',
                            dest='num_messages',
                            type=int,
                            default=500,
                            help='The number of messages to create.')

        parser.add_argument('--extra-users',
                            dest='extra_users',
                            type=int,
                            default=0,
                            help='The number of extra users to create')

        parser.add_argument('--extra-bots',
                            dest='extra_bots',
                            type=int,
                            default=0,
                            help='The number of extra bots to create')

        parser.add_argument('--extra-streams',
                            dest='extra_streams',
                            type=int,
                            default=0,
                            help='The number of extra streams to create')

        parser.add_argument('--huddles',
                            dest='num_huddles',
                            type=int,
                            default=3,
                            help='The number of huddles to create.')

        parser.add_argument('--personals',
                            dest='num_personals',
                            type=int,
                            default=6,
                            help='The number of personal pairs to create.')

        parser.add_argument('--threads',
                            dest='threads',
                            type=int,
                            default=1,
                            help='The number of threads to use.')

        parser.add_argument('--percent-huddles',
                            dest='percent_huddles',
                            type=float,
                            default=15,
                            help='The percent of messages to be huddles.')

        parser.add_argument('--percent-personals',
                            dest='percent_personals',
                            type=float,
                            default=15,
                            help='The percent of messages to be personals.')

        parser.add_argument('--stickyness',
                            dest='stickyness',
                            type=float,
                            default=20,
                            help='The percent of messages to repeat recent folks.')

        parser.add_argument('--nodelete',
                            action="store_false",
                            default=True,
                            dest='delete',
                            help='Whether to delete all the existing messages.')

        parser.add_argument('--test-suite',
                            default=False,
                            action="store_true",
                            help='Whether to delete all the existing messages.')
Exemplo n.º 22
0
 def add_arguments(self, parser: CommandParser):
     parser.add_argument("path", type=str)
     parser.add_argument("--verbose", action="store_true")
     parser.add_argument("--test", action="store_true")
Exemplo n.º 23
0
 def add_arguments(self, parser: CommandParser):
     parser.add_argument("path", type=str)
Exemplo n.º 24
0
    def execute(self):
        """
        Given the command-line arguments, figure out which subcommand is being
        run, create a parser appropriate to that command, and run it.
        1、命令行参数解析
        2、
        """
        try:
            # 如果在调用django-admin 的时候没有给出任何的 命令 & 选项
            # 那么slef.argv 列表只有一项 它就是slef.argv[0] 它的值为django-admin
            # 所以这种情况下正好会报 IndexError
            subcommand = self.argv[1]
        except IndexError:
            # 如果没有给出任何命令的情况下 把subcommand设置为help
            # 也就是说不给出命令的情况下 就当做是看django-admin的帮助.
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.

        # django 在标准库的argparser上作出了一些自定义
        # CommandParser 继承了argparser.ArgumentParser
        # CommandParser 位于 jango.core.management.base 这个包中.
        # usage & add_help 都是argparser.ArgumentParser.__init__中的参数
        # CommandParser.__init__(self, cmd, **kwargs): 由这里可以看了cmd=None
        parser = CommandParser(None,
                               usage="%(prog)s subcommand [options] [args]",
                               add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        try:
            # settings 是在django.conf包中LazySettings类的实例
            # 这里有个问题,就是在LazySettings类的代码中没有找到INSTALLED_APPS 的定义
            # settings.INSTALLED_APPS 像这样的语句又有什么意义呢?难道它这样干就单单是为了引发异常?
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(OrderedDict)
                    apps.app_configs = OrderedDict()
                    apps.apps_ready = apps.models_ready = apps.ready = True

                    # Remove options not compatible with the built-in runserver
                    # (e.g. options for the contrib.staticfiles' runserver).
                    # Changes here require manually testing as described in
                    # #27522.
                    _parser = self.fetch_command('runserver').create_parser(
                        'django', 'runserver')
                    _options, _args = _parser.parse_known_args(self.argv[2:])
                    for _arg in _args:
                        self.argv.remove(_arg)

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(
                    self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(
                    self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
Exemplo n.º 25
0
 def add_arguments(self, parser: CommandParser):
     parser.add_argument('invoice', type=int)
     parser.add_argument('--tx', action='store_true')
Exemplo n.º 26
0
 def add_arguments(self, parser: CommandParser):
     parser.add_argument("--invoice", type=int)
     parser.add_argument("--force", action="store_true")
     parser.add_argument("--verbose", action="store_true")
Exemplo n.º 27
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None,
                               usage="%(prog)s subcommand [options] [args]",
                               add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        no_settings_commands = [
            'help',
            'version',
            '--help',
            '--version',
            '-h',
            'compilemessages',
            'makemessages',
            'startapp',
            'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader.
                    pass

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(
                    self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(
                    self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
Exemplo n.º 28
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument("-n",
                            "--num-messages",
                            type=int,
                            default=500,
                            help="The number of messages to create.")

        parser.add_argument(
            "-b",
            "--batch-size",
            type=int,
            default=1000,
            help="How many messages to process in a single batch",
        )

        parser.add_argument("--extra-users",
                            type=int,
                            default=0,
                            help="The number of extra users to create")

        parser.add_argument("--extra-bots",
                            type=int,
                            default=0,
                            help="The number of extra bots to create")

        parser.add_argument("--extra-streams",
                            type=int,
                            default=0,
                            help="The number of extra streams to create")

        parser.add_argument("--max-topics",
                            type=int,
                            help="The number of maximum topics to create")

        parser.add_argument(
            "--huddles",
            dest="num_huddles",
            type=int,
            default=3,
            help="The number of huddles to create.",
        )

        parser.add_argument(
            "--personals",
            dest="num_personals",
            type=int,
            default=6,
            help="The number of personal pairs to create.",
        )

        parser.add_argument("--threads",
                            type=int,
                            default=1,
                            help="The number of threads to use.")

        parser.add_argument(
            "--percent-huddles",
            type=float,
            default=15,
            help="The percent of messages to be huddles.",
        )

        parser.add_argument(
            "--percent-personals",
            type=float,
            default=15,
            help="The percent of messages to be personals.",
        )

        parser.add_argument(
            "--stickyness",
            type=float,
            default=20,
            help="The percent of messages to repeat recent folks.",
        )

        parser.add_argument(
            "--nodelete",
            action="store_false",
            dest="delete",
            help="Whether to delete all the existing messages.",
        )

        parser.add_argument(
            "--test-suite",
            action="store_true",
            help="Configures populate_db to create a deterministic "
            "data set for the backend tests.",
        )
Exemplo n.º 29
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument("email", type=str)
     parser.add_argument("password", type=str)
     parser.add_argument("name", type=str)
     parser.add_argument("--verified", action="store_true", help="Mark the user's email as verified")
     parser.add_argument("--logged-in", action="store_true", help="Log the user in and return their auth token")
Exemplo n.º 30
0
    def add_arguments(self, parser: CommandParser) -> None:
        """
        This Command inherits the same arguments as :class:`carrot.management.commands.carrot.Command`, with the
        addition of one positional argument: **mode**
        """
        parser.add_argument('mode')
        parser.add_argument("-l",
                            "--logfile",
                            type=str,
                            help='The path to the log file',
                            default='/var/log/carrot.log')
        parser.add_argument("-p",
                            "--pidfile",
                            type=str,
                            help='The path to the pid file',
                            default='/var/run/carrot.pid')
        parser.add_argument(
            '--no-scheduler',
            dest='run_scheduler',
            action='store_false',
            default=False,
            help='Do not start scheduled tasks (only runs consumer sets)')
        parser.add_argument(
            '--hard',
            dest='force',
            action='store_true',
            default=False,
            help=
            'Force stop the consumer (can only be used with stop|restart modes). USE WITH CAUTION'
        )
        parser.set_defaults(run_scheduler=True)
        parser.set_defaults(testmode=False)

        parser.add_argument('--consumer-class',
                            type=str,
                            help='The consumer class to use',
                            default='carrot.objects.Consumer')
        parser.add_argument('--loglevel',
                            type=str,
                            default='DEBUG',
                            help='The logging level. Must be one of DEBUG, '
                            'INFO, WARNING, ERROR, CRITICAL')
        parser.add_argument(
            '--testmode',
            dest='testmode',
            action='store_true',
            default=False,
            help=
            'Run in test mode. Prevents the command from running as a service. Should only be '
            'used when running Carrot\'s tests')
Exemplo n.º 31
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('dump1', help='First file to compare')
     parser.add_argument('dump2', help='Second file to compare')
Exemplo n.º 32
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument(
         "--days",
         type=int,
         default=14,
         help="Warn DAYS days ahead of time (default: %(default)s).")
Exemplo n.º 33
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('-n', '--num-messages',
                            dest='num_messages',
                            type=int,
                            default=500,
                            help='The number of messages to create.')

        parser.add_argument('--extra-users',
                            dest='extra_users',
                            type=int,
                            default=0,
                            help='The number of extra users to create')

        parser.add_argument('--extra-bots',
                            dest='extra_bots',
                            type=int,
                            default=0,
                            help='The number of extra bots to create')

        parser.add_argument('--extra-streams',
                            dest='extra_streams',
                            type=int,
                            default=0,
                            help='The number of extra streams to create')

        parser.add_argument('--huddles',
                            dest='num_huddles',
                            type=int,
                            default=3,
                            help='The number of huddles to create.')

        parser.add_argument('--personals',
                            dest='num_personals',
                            type=int,
                            default=6,
                            help='The number of personal pairs to create.')

        parser.add_argument('--threads',
                            dest='threads',
                            type=int,
                            default=1,
                            help='The number of threads to use.')

        parser.add_argument('--percent-huddles',
                            dest='percent_huddles',
                            type=float,
                            default=15,
                            help='The percent of messages to be huddles.')

        parser.add_argument('--percent-personals',
                            dest='percent_personals',
                            type=float,
                            default=15,
                            help='The percent of messages to be personals.')

        parser.add_argument('--stickyness',
                            dest='stickyness',
                            type=float,
                            default=20,
                            help='The percent of messages to repeat recent folks.')

        parser.add_argument('--nodelete',
                            action="store_false",
                            default=True,
                            dest='delete',
                            help='Whether to delete all the existing messages.')

        parser.add_argument('--test-suite',
                            default=False,
                            action="store_true",
                            help='Whether to delete all the existing messages.')
Exemplo n.º 34
0
    def execute(self):
        """
        Given the command-line arguments, figure out which subcommand is being
        run, create a parser appropriate to that command, and run it.
        """
        # 先找出二级指令,没有二级指令就打印帮助信息
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # 预处理的选项,这些选项会和当前传递的选项有冲突,所以先解析出这些选项,这样用户传递的选项才不会被影响.
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        # 这里是指定settings文件
        parser.add_argument('--settings')
        # 这里是指定python路径
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            # 修改环境settings和pythonpath
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        try:
            # django在启动时会创建settings = LazySettings()
            # 通过读取os.environ.get('DJANGO_SETTINGS_MODULE'),来初始化settings对象
            # settings是一个lazy对象,使用self._wrapped保存Settings对象,当读取属性时,lazy对象会先进行_setup,然后会调用getattr(self._wrapped,key)
            # 当要读取INSTALLED_APPS时,会先进行_setup
            # 说白了就是LazySetting对象读取属性时,会真正初始化Settings对象,并赋值给LazySetting._wrapped=Settings()
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc

        if settings.configured:
            # 就是返回self._wrapped is not empty,当前是否已经初始化好了settings
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    # 执行django.setup,如果有错误那么
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(OrderedDict)
                    apps.app_configs = OrderedDict()
                    apps.apps_ready = apps.models_ready = apps.ready = True

                    # Remove options not compatible with the built-in runserver
                    # (e.g. options for the contrib.staticfiles' runserver).
                    # Changes here require manually testing as described in
                    # #27522.
                    _parser = self.fetch_command('runserver').create_parser('django', 'runserver')
                    _options, _args = _parser.parse_known_args(self.argv[2:])
                    for _arg in _args:
                        self.argv.remove(_arg)

            # In all other cases, django.setup() is required to succeed.
            else:
                # 执行django.setup
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            # 这里执行fetch_command('runserver').run_from_argv(['/Users/mering/Proje...manage.py', 'runserver', '--noreload', '--nothreading'])
            # runserver 对应的是django.contrib.staticfiles
            # 加载该class import_module('%s.management.commands.%s' % (app_name, name))
            # import_module('django.contrib.staticfiles.management.commands.runserver')
            # 放回的fetch_command(subcommand)=django.contrib.staticfiles.management.commands.runserver.Command()
            # django.contrib.staticfiles.management.commands.runserver.Command继承自django.core.management.Command,
            # run_from_argv会调用django.core.management.Command.excute-->django.core.management.BaseCommand.excute
            # django.core.management.commands.runserver.Command.handle
            # django.core.management.commands.runserver.Command.run
            # django.core.management.commands.runserver.Command.inner_run
            # django.contrib.staticfiles.management.commands.runserver.Command.get_handler  获得wsgiapp
            #  Debug模式下返回StaticFilesHandler
            # django.core.servers.run
            # def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGIServer):
            #     server_address = (addr, port)
            #     if threading:
            #         # 创建一个新类型继承自socketserver.ThreadingMixIn和WSGIServer
            #         httpd_cls = type('WSGIServer', (socketserver.ThreadingMixIn, server_cls), {})
            #     else:
            #         httpd_cls = server_cls
            #     httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
            #     if threading:
            #         # ThreadingMixIn.daemon_threads indicates how threads will behave on an
            #         # abrupt shutdown; like quitting the server by the user or restarting
            #         # by the auto-reloader. True means the server will not wait for thread
            #         # termination before it quits. This will make auto-reloader faster
            #         # and will prevent the need to kill the server manually if a thread
            #         # isn't terminating correctly.
            #         httpd.daemon_threads = True
            #     httpd.set_app(wsgi_handler)
            #     httpd.serve_forever()
            self.fetch_command(subcommand).run_from_argv(self.argv)
Exemplo n.º 35
0
    def execute(self, argv=None, stdout=None, stderr=None):

        if argv is None:
            argv = sys.argv

        if stdout is None:
            stdout = sys.stdout

        if stderr is None:
            stderr = sys.stderr

        if django.VERSION >= (1, 8):
            from django.core.management.base import CommandParser
            parser = CommandParser(None,
                usage="%(prog)s subcommand [options] [args]",
                add_help=False)
            parser.add_argument('--version', action='store_true', help="show program's version number and exit")
            parser.add_argument('-h', '--help', action='store_true', help="show this help message and exit")

            try:
                options, argv = parser.parse_known_args(argv)
            except:
                pass  # Ignore any option errors at this point.
        else:
            from django.core.management import LaxOptionParser

            parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                option_list=(),
                add_help_option=False)
            parser.add_option('--version', action='store_true', help="show program's version number and exit")
            parser.add_option('-h', '--help', action='store_true', help="show this help message and exit")

            try:
                options, argv = parser.parse_args(argv)
            except:
                pass  # Ignore any option errors at this point.

        if len(argv) > 1:
            subcommand = argv[1]
        else:
            subcommand = 'help'  # Display help if no arguments were given.


        if options.help:

            if subcommand == 'help':
                if hasattr(parser, 'print_lax_help'):
                    parser.print_lax_help()
                else:
                    parser.print_help(stdout)
                stdout.write(self.main_help_text() + '\n')
            else:
                command = self.fetch_command(subcommand)
                if command is not None:
                    command.print_help(self.prog_name, subcommand, file=stdout)
                else:
                    stdout.write(self.unknown_command_text(subcommand) + '\n')

        elif subcommand == 'version' or options.version:

            stdout.write(wirecloud.platform.__version__ + '\n')

        elif subcommand == 'help':

            if len(argv) <= 2:
                if hasattr(parser, 'print_lax_help'):
                    parser.print_lax_help()
                else:
                    parser.print_help(stdout)
                stdout.write(self.main_help_text() + '\n')
            elif argv[2] == '--commands':
                stdout.write(self.main_help_text(commands_only=True) + '\n')
            else:
                command = self.fetch_command(argv[2])
                if command is not None:
                    command.print_help(self.prog_name, argv[2], file=stdout)
                else:
                    stdout.write(self.unknown_command_text(argv[2]) + '\n')

        else:
            command = self.fetch_command(subcommand)
            if command is not None:
                command.run_from_argv(argv, stdout=stdout, stderr=stderr)
            else:
                stdout.write(self.unknown_command_text(subcommand) + '\n')
Exemplo n.º 36
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('--verbose', default=False, action='store_true')
Exemplo n.º 37
0
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(OrderedDict)
                    apps.app_configs = OrderedDict()
                    apps.apps_ready = apps.models_ready = apps.ready = True

                    # Remove options not compatible with the built-in runserver
                    # (e.g. options for the contrib.staticfiles' runserver).
                    # Changes here require manually testing as described in
                    # #27522.
                    _parser = self.fetch_command('runserver').create_parser('django', 'runserver')
                    _options, _args = _parser.parse_known_args(self.argv[2:])
                    for _arg in _args:
                        self.argv.remove(_arg)

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
Exemplo n.º 38
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('hipchat_tar', nargs='+',
                            metavar='<hipchat data tarfile>',
                            help="tar of Hipchat data")

        parser.add_argument('--output', dest='output_dir',
                            action="store",
                            help='Directory to write exported data to.')

        parser.add_argument('--mask', dest='masking_content',
                            action="store_true",
                            help='Mask the content for privacy during QA.')

        parser.add_argument('--slim-mode', dest='slim_mode',
                            action="store_true",
                            help="Default to no public stream subscriptions if no token is available." +
                            "  See import docs for details.")

        parser.add_argument('--token', dest='api_token',
                            action="store",
                            help='API token for the HipChat API for fetching subscribers.')

        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 39
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('--processes',
                         dest='processes',
                         action="store",
                         default=6,
                         help='Processes to use for exporting uploads in parallel')
Exemplo n.º 40
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument("email", metavar="<email>", help="Email address of the user")
     self.add_realm_args(parser)
Exemplo n.º 41
0
 def create_parser(self, prog_name, subcommand):
     """
     Create and return the ``ArgumentParser`` which will be used to
     parse the arguments to this command.
     """
     parser = CommandParser(
         self,
         prog="%s %s" % (os.path.basename(prog_name), subcommand),
         description=self.help or None,
     )
     #parser.add_argument('--version', action='version', version=self.get_version())
     parser.add_argument(
         '-v',
         '--verbosity',
         action='store',
         dest='verbosity',
         default=1,
         type=int,
         choices=[0, 1, 2, 3],
         help=
         'Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output',
     )
     parser.add_argument(
         '--settings',
         help=('The Python path to a settings module, e.g. '
               '"myproject.settings.main". If this isn\'t provided, the '
               'DJANGO_SETTINGS_MODULE environment variable will be used.'),
     )
     parser.add_argument(
         '--pythonpath',
         help=
         'A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".',
     )
     parser.add_argument('--traceback',
                         action='store_true',
                         help='Raise on CommandError exceptions')
     parser.add_argument(
         '--no-color',
         action='store_true',
         dest='no_color',
         default=False,
         help="Don't colorize the command output.",
     )
     self.add_arguments(parser)
     return parser
Exemplo n.º 42
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('-t', '--trim',
                         dest='trim',
                         default=False,
                         action='store_true',
                         help="Actually trim excess")
Exemplo n.º 43
0
 def add_arguments(self, parser: CommandParser) -> None:
     self.add_base_args(parser, no_default_ca=True)
     parser.add_argument(
         "cert", action=CertificateAction, allow_revoked=True, help="The certificate to resign."
     )
Exemplo n.º 44
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('--processes',
                         action="store",
                         default=settings.DEFAULT_DATA_EXPORT_IMPORT_PARALLELISM,
                         help='Processes to use for exporting uploads in parallel')
Exemplo n.º 45
0
 def add_arguments(self, parser: CommandParser):
     parser.add_argument('from_user', type=str)
     parser.add_argument('to_user', type=str)
Exemplo n.º 46
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument("--reason",
                         action=ReasonAction,
                         help="An optional reason for revokation.")
     super().add_arguments(parser)
Exemplo n.º 47
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('--verbose', default=False, action='store_true')
Exemplo n.º 48
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('--realm', action='store')
     parser.add_argument('--date', action='store', default="2013-09-06")
     parser.add_argument('--duration', action='store', default=1, type=int,
                         help="How many days to show usage information for")
Exemplo n.º 49
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('--path', type=str)
Exemplo n.º 50
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument('-n',
                            '--num-messages',
                            dest='num_messages',
                            type=int,
                            default=500,
                            help='The number of messages to create.')

        parser.add_argument(
            '-b',
            '--batch-size',
            dest='batch_size',
            type=int,
            default=1000,
            help='How many messages to process in a single batch')

        parser.add_argument('--extra-users',
                            dest='extra_users',
                            type=int,
                            default=0,
                            help='The number of extra users to create')

        parser.add_argument('--extra-bots',
                            dest='extra_bots',
                            type=int,
                            default=0,
                            help='The number of extra bots to create')

        parser.add_argument('--extra-streams',
                            dest='extra_streams',
                            type=int,
                            default=0,
                            help='The number of extra streams to create')

        parser.add_argument('--huddles',
                            dest='num_huddles',
                            type=int,
                            default=3,
                            help='The number of huddles to create.')

        parser.add_argument('--personals',
                            dest='num_personals',
                            type=int,
                            default=6,
                            help='The number of personal pairs to create.')

        parser.add_argument('--threads',
                            dest='threads',
                            type=int,
                            default=1,
                            help='The number of threads to use.')

        parser.add_argument('--percent-huddles',
                            dest='percent_huddles',
                            type=float,
                            default=15,
                            help='The percent of messages to be huddles.')

        parser.add_argument('--percent-personals',
                            dest='percent_personals',
                            type=float,
                            default=15,
                            help='The percent of messages to be personals.')

        parser.add_argument(
            '--stickyness',
            dest='stickyness',
            type=float,
            default=20,
            help='The percent of messages to repeat recent folks.')

        parser.add_argument(
            '--nodelete',
            action="store_false",
            default=True,
            dest='delete',
            help='Whether to delete all the existing messages.')

        parser.add_argument(
            '--test-suite',
            default=False,
            action="store_true",
            help='Configures populate_db to create a deterministic '
            'data set for the backend tests.')
Exemplo n.º 51
0
    def add_arguments(self, parser: CommandParser) -> None:
        parser.add_argument(
            "--destroy-rebuild-database",
            action="store_true",
            help="Destroys and rebuilds the databases prior to import.",
        )

        parser.add_argument(
            "--import-into-nonempty",
            action="store_true",
            help="Import into an existing nonempty database.",
        )

        parser.add_argument(
            "--allow-reserved-subdomain",
            action="store_true",
            help="Allow use of reserved subdomains",
        )

        parser.add_argument("subdomain", metavar="<subdomain>", help="Subdomain")

        parser.add_argument(
            "export_paths",
            nargs="+",
            metavar="<export path>",
            help="list of export directories to import",
        )
        parser.add_argument(
            "--processes",
            default=settings.DEFAULT_DATA_EXPORT_IMPORT_PARALLELISM,
            help="Number of processes to use for uploading Avatars to S3 in parallel",
        )
        parser.formatter_class = argparse.RawTextHelpFormatter
Exemplo n.º 52
0
 def create_parser(self, prog_name, subcommand):
     """
     Create and return the ``ArgumentParser`` which will be used to
     parse the arguments to this command.
     """
     parser = CommandParser(
         self, prog="%s %s" % (os.path.basename(prog_name), subcommand), description=self.help or None
     )
     # parser.add_argument('--version', action='version', version=self.get_version())
     parser.add_argument(
         "-v",
         "--verbosity",
         action="store",
         dest="verbosity",
         default=1,
         type=int,
         choices=[0, 1, 2, 3],
         help="Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output",
     )
     parser.add_argument(
         "--settings",
         help=(
             "The Python path to a settings module, e.g. "
             '"myproject.settings.main". If this isn\'t provided, the '
             "DJANGO_SETTINGS_MODULE environment variable will be used."
         ),
     )
     parser.add_argument(
         "--pythonpath", help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'
     )
     parser.add_argument("--traceback", action="store_true", help="Raise on CommandError exceptions")
     parser.add_argument(
         "--no-color", action="store_true", dest="no_color", default=False, help="Don't colorize the command output."
     )
     self.add_arguments(parser)
     return parser
Exemplo n.º 53
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('--resource', help='Only sync the specified resource')
Exemplo n.º 54
0
    def execute(self):
        """
        Given the command-line arguments, figure out which subcommand is being
        run, create a parser appropriate to that command, and run it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
        except ImportError as exc:
            self.settings_exception = exc

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(dict)
                    apps.app_configs = {}
                    apps.apps_ready = apps.models_ready = apps.ready = True

                    # Remove options not compatible with the built-in runserver
                    # (e.g. options for the contrib.staticfiles' runserver).
                    # Changes here require manually testing as described in
                    # #27522.
                    _parser = self.fetch_command('runserver').create_parser('django', 'runserver')
                    _options, _args = _parser.parse_known_args(self.argv[2:])
                    for _arg in _args:
                        self.argv.remove(_arg)

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif not options.args:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
Exemplo n.º 55
0
from __future__ import unicode_literals
Exemplo n.º 56
0
 def add_arguments(self, parser: CommandParser) -> None:
     parser.add_argument('-t', '--trim',
                         dest='trim',
                         default=False,
                         action='store_true',
                         help="Actually trim excess")
Exemplo n.º 57
0
 def add_arguments(self, parser: CommandParser):
     parser.add_argument('lhs')
     parser.add_argument('rhs')