def __call__(self, parser: configargparse.ArgumentParser, namespace: configargparse.Namespace,
values: Sequence[str], option_string: str=None) -> None:
if len(values) > 2:
raise ErrorMessage("%s takes 1 or 2 arguments, not more." % highlight("--init"))
if values[0] not in _initializers:
raise ErrorMessage("Unknown initializer \"%s\". Acceptable values are: %s" %
(highlight(values[0]), highlight(", ".join(_initializers.keys()))))
initializer = _initializers[values[0]]
if len(values) > 1:
initializer.configfolder = values[1] # override config folder if it's not the default
if os.path.exists(initializer.configfolder):
raise ErrorMessage("%s already exists. If you want to overwrite it, remove it first." %
initializer.configfolder)
initializer.build_config()
parser.exit(0)
python类ArgumentParser()的实例源码
def add_args(self, parser: configargparse.ArgumentParser) -> None:
_aptly_args.add_shared_args(parser)
gr_aptly = parser.add_argument_group("Aptly Versioner options")
gr_aptly.add_argument("--aptly-fallback-version", dest="aptly_fallback_version", default=None,
help="If the APT repository does not yet contain a package with the name specified by "
"--aptly-query, the Aptly Versioner can return a fallback value. This is useful "
"for fresh repositories.")
gr_aptly.add_argument("--aptly-versioner-opts", dest="aptly_versioner_opts", default="",
help="Specify additional command-line parameters which will be appended to every "
"invocation of aptly by the Aptly Versioner.")
gr_aptly.add_argument("--aptly-query", dest="aptly_query", default=None,
help="Set the query to run on the aptly repo. For example: get the latest revision of a "
"specific version through --aptly-query='Name ([yourpackage]), $Version (>=0.9.5), "
"Version (<=0.9.6)'). More information on the query syntax can be found on "
"https://aptly.info. To find the overall latest version of GoPythonGo in a repo, "
"you would use --aptly-query='Name (gopythongo)'")
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gr_pip = parser.add_argument_group("PIP Assembler options")
gr_pip.add_argument("--pip-opts", dest="pip_opts", action="append", default=[], env_var="PIP_OPTS",
help="Any string specified here will be directly appended to all pip command-lines when it "
"is invoked, allowing you to specify arbitrary extra command-line parameters, like "
"--extra-index. Make sure that you use an equals sign, i.e. --pip-opts='' to avoid "
"'Unknown parameter' errors! http://bugs.python.org/issue9334")
gr_pip.add_argument("--upgrade-pip", dest="upgrade_pip", action="store_true", default=False,
help="If specified, GoPythonGo will update pip and virtualenv inside the build environment "
"to the newest available version before installing packages")
gr_setuppy = parser.add_argument_group("Setup.py Assembler options")
gr_setuppy.add_argument("--setuppy-install", dest="setuppy_install", action="append", default=[],
help="After all pip commands have run, this can run 'python setup.py install' on " +
"additional packages available in any filesystem path. This option can be " +
"used multiple times")
gr_python = parser.add_argument_group("Python ecosystem options")
gr_python.add_argument("--use-virtualenv", dest="virtualenv_binary", default="/usr/bin/virtualenv",
env_var="VIRTUALENV_EXECUTABLE",
help="Set an alternative virtualenv binary to use inside the builder container")
gr_python.add_argument("--python-binary", dest="python_binary", default="python3",
help="Force virtualenv to use a certain Python version (Default: 'python3'). This will "
"be passed to virtualenv's -p parameter. You must change this if you want to build "
"and ship Python 2.x virtual environments.")
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gr_django = parser.add_argument_group("Django Assembler options")
gr_django.add_argument("--collect-static", dest="collect_static", action="store_true", default=False,
help="If set, run 'django-admin.py collectstatic' inside the bundle")
gr_django.add_argument("--static-root", dest="static_root", default=None,
help="Where to collect static files from (Django's STATIC_ROOT)")
gr_django.add_argument("--assert-static-root-empty", dest="fresh_static", action="store_true", default=False,
help="If set, this script will make sure that STATIC_ROOT is empty " +
"before running collectstatic by DELETING it (be careful!)")
gr_django.add_argument("--django-settings", dest="django_settings_module", default=None,
help="'--settings' argument to pass to django-admin.py when it is called by " +
"this script. If --django-generate-secret-key is set, SECRET_KEY will be set "
"in the environment.")
gr_django.add_argument("--django-gen-secret-key", dest="django_secret_key_file", default=None,
env_var="DJANGO_GEN_SECRET_KEY",
help="If set, GoPythonGo will write SECRET_KEY='(random)' to the given filename. The "
"resulting file can be read from envdir or systemd (EnvironmentFile). This is "
"useful for shipping environment configuration for projects adhering to 12factor "
"(and/or using the django12factor library).")
def add_args(parser: configargparse.ArgumentParser) -> None:
global _assemblers
pos_args = parser.add_argument_group("Python ecosystem arguments (positional)")
pos_args.add_argument("build_path",
help="set the location where the virtual environment will be built, this " +
"is IMPORTANT as it is also the location where the virtualenv must " +
"ALWAYS reside (i.e. the install directory. Virtualenvs are NOT relocatable" +
"by default! All path parameters are relative to this path")
pos_args.add_argument("packages", metavar="package<=>version", nargs="*",
help="a list of package/version specifiers. Remember to quote your " +
"strings as in \"Django>=1.9,<1.10\"")
parser.add_argument("--help-assembler", action=AssemblerHelpAction, choices=_assemblers.keys(), default=None)
for assembler in _assemblers.values():
assembler.add_args(parser)
def _find_default_mounts() -> Set[str]:
global config_paths
basepath = os.getcwd()
miniparser = configargparse.ArgumentParser()
miniparser.add_argument(*args_for_setting_config_path, dest="config", action="append",
default=[])
args, _ = miniparser.parse_known_args()
# type: ignore, because mypy doesn't parse add_argument above correctly
if not args.config:
args.config = default_config_files
paths = set()
paths.add(basepath)
for cfg in args.config:
if os.path.isfile(cfg):
paths.add(os.path.abspath(os.path.dirname(cfg)))
config_paths.add(os.path.abspath(os.path.dirname(cfg)))
return paths
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gr_fpm = parser.add_argument_group("FPM Packer options")
gr_fpm.add_argument("--use-fpm", dest="fpm", default="/usr/local/bin/fpm",
env_var="FPM_EXECUTABLE",
help="The full path to the fpm executable to use")
gr_fpm.add_argument("--run-fpm", dest="run_fpm", action="append", metavar="OPTS_FILE",
default=[], const=".gopythongo/fpm_opts", nargs="?",
help="Execute FPM (can be used multiple times). You must pass a filename to this "
"parameter, which specifies a file containing the command-line parameters for "
"invoking FPM (one per line). FPM will be invoked with the CWD set to the build "
"folder inside the selected builder. Templating is supported. You can use 'template:' "
"prefixes INSIDE THE OPTS_FILE ITSELF and also process OPTS_FILE as a template. "
"Default opts file: .gopythongo/fpm_opts")
gr_opts = parser.add_argument_group("FPM related options (can also be used in OPTS_FILE):")
gr_opts.add_argument("--fpm-format", dest="fpm_format", choices=["deb"], default="deb",
help="Output package format. Only 'deb' is supported for now")
gr_opts.add_argument("--fpm-opts", dest="fpm_extra_opts", default="", env_var="FPM_OPTS",
help="Any string specified here will be directly appended to the FPM command-line when it "
"is invoked, allowing you to specify arbitrary extra command-line parameters. Make "
"sure that you use an equals sign, i.e. --fpm-opts='' to avoid 'Unknown parameter' "
"errors! (http://bugs.python.org/issue9334).")
def add_shared_args(parser: configargparse.ArgumentParser) -> None:
global _docker_shared_args_added
if not _docker_shared_args_added:
gr_docker_shared = parser.add_argument_group("Docker common parameters (Builder and Store)")
gr_docker_shared.add_argument("--docker-api", dest="docker_api", default="unix://var/run/docker.sock",
help="The Docker API endpoint as a http/unix URL. (Default: "
"unix://var/run/docker.sock)")
gr_docker_shared.add_argument("--docker-tls-client-cert", dest="docker_tls_client_cert", default=None,
help="Path to a SSL client certificate in PEM format to use when connecting to "
"the Docker API.")
gr_docker_shared.add_argument("--docker-tls-verify", dest="docker_tls_verify", default=False,
help="Set this to a CA certificate PEM file to verify that the Docker server's "
"TLS certificate was signed by this CA.")
gr_docker_shared.add_argument("--docker-ssl-version", dest="docker_ssl_version", default=5,
help="Set to 3 (TLSv1), 4 (TLSv1.1) or 5 (TLSv1.2) to force the connection to "
"use a particular protocol version. (Default: 5).")
gr_docker_shared.add_argument("--docker-tls-noverify-hostname", dest="docker_dont_verify_hostname",
default=False, action="store_true",
help="Set this if the Docker API client should skip verifying the Docker API's "
"hostname.")
_docker_shared_args_added = True
def set_args():
# type: () -> configargparse.ArgumentParser
"""Read in the args
"""
parser = configargparse.ArgumentParser(
default_config_files=["push_server.ini"],
)
parser.add_argument('--config', help='Common configuration file path',
dest='config_file', is_config_file=True)
parser.add_argument('--debug', '-d', help="Debug info", default=False,
action="store_true")
parser.add_argument('--storage', help='Credential storage file',
default='creds.txt', type=str)
parser.add_argument('--topic', help='Message topic', default=None,
type=str)
parser.add_argument('--ttl', help='Message time to live', default=300,
type=int)
parser.add_argument('--msg', help='message body to send', default=None,
type=str, required=True)
return parser
def set_args():
# type: () -> configargparse.ArgumentParser
"""Read in the args
"""
parser = configargparse.ArgumentParser(
default_config_files=["push_server.ini"],
)
parser.add_argument('--config', help='Common configuration file path',
dest='config_file', is_config_file=True)
parser.add_argument('--debug', '-d', help="Debug info", default=False,
action="store_true")
parser.add_argument('--port', '-p', help="Port to monitor",
default=8200, type=int)
parser.add_argument('--storage', help='Credential storage file',
default='creds.txt', type=str)
return parser
def __init__(self, parent_parsers=None, config_file=None):
parent_parsers = parent_parsers or []
self.parser = configargparse.ArgumentParser(parents=parent_parsers)
self.parser.add_argument(
'-c', '--config', is_config_file=True, default=config_file,
help='Path to a configuration file in YAML format.'
)
self.parser.add_argument(
'-l', '--live-mode', action='store_true', dest='live_mode',
env_var=ENV_LIVE_TEST,
help='Activate "live" recording mode for tests.'
)
self.args = self.parser.parse_args([])
def __call__(self, parser: configargparse.ArgumentParser, namespace: configargparse.Namespace,
values: Union[str, Sequence[Any], None], option_string: str=None) -> None:
from gopythongo.initializers import get_initializers
initializers = get_initializers()
if values and values in initializers.keys():
initializers[cast(str, values)].print_help()
else:
print("Quick start configuration generators\n"
"====================================\n"
"\n"
"When you want to start working with GoPythonGo in a project, you need to\n"
"configure GoPythonGo for your workflow. This means that you need to select\n"
"a builder, one or more assemblers, a packer and a store fitting your processes\n"
"and deployment options.\n"
"\n"
"To make it easier to get started, GoPythonGo can generate common configurations\n"
"for you as a starting point. The modules generating these quick start\n"
"configurations are called \"%s\". It's also easy to write a plugin to\n"
"support common defaults in your organization. GoPythonGo ships with some default\n"
"Initializers. Those are:\n"
"\n"
" %s - build a virtualenv using Debian's pbuilder isolation system\n"
" and package it in a .deb. Then store it in an APT repository\n"
" using aptly.\n"
"\n"
" %s - build a virtualenv in a Docker-based build environment then\n"
" copy it into a Docker production container and push that to\n"
" a Docker container registry,\n"
"\n"
"You generate a quick start configuration by using --init [configtype] [path],\n"
"where path is optional (default: .config/). You can get more information on the\n"
"individual Initializers by using\n"
"%s." %
(highlight("Initializers"), highlight("pbuilder_deb"), highlight("docker"),
highlight("--help-initializer=[%s]" % ", ".join(initializers.keys()))))
parser.exit()
def add_args(parser: configargparse.ArgumentParser) -> None:
gp_init = parser.add_argument_group("Quick start / Configuration generators")
gp_init.add_argument("--init", action=InitializerAction, nargs="+", metavar=("BUILDTYPE", "PATH"),
help="Initialize a default configuration. BUILDTYPE must be one of (%s) and PATH"
"is the path of the configuration folder you want to initialize." %
(", ".join(_initializers.keys())))
parser.add_argument("--help-initializer", action=InitializerHelpAction, choices=_initializers.keys(), default=None)
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gr_pymod = parser.add_argument_group("Pymodule Versioner options")
gr_pymod.add_argument("--pymodule-read", dest="pymodule_read", default=None,
help="A fully qualified dotted path to a str attribute in a Python module accessible on"
"the current PYTHONPATH to be read to get the version string.")
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gp_search = parser.add_argument_group("Search File Versioner options")
gp_search.add_argument("--search-version-in", dest="search_version_in", default=None,
help="The file to read to find the version string.")
gp_search.add_argument("--search-version-regex", dest="search_version_regex",
default="([0-9]+\.[0-9]+\.[0-9]+\.?(dev|rc|pre|post)?)",
help="Define the regular expression that we search for. The first match wins.")
def add_args(self, parser: configargparse.ArgumentParser) -> None:
pass
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gr_regex = parser.add_argument_group("Regex Version Parser options")
gr_regex.add_argument("--version-regex", dest="version_regex", default=None,
help="Select the regular expression used to parse the version string read by the version "
"reader. It must contain named groups for 'major', 'minor' and 'patch' and can "
"optionally contain named groups for 'prerelease' and 'metadata' mapping to the "
"fields as described by semver.org. Example: "
"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.(?P<patch>[0-9]+)")
def add_args(self, parser: configargparse.ArgumentParser) -> None:
pass
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gr_bv = parser.add_argument_group("Bumpversion Versioner options")
gr_bv.add_argument("--use-bumpversion", dest="bumpversion_executable", default=None,
env_var="BUMPVERSION_EXECUTABLE",
help="Set the path to the bumpversion shellscript. Required if you want to use the "
"bumpversion Versioner. By default GoPythonGo will use the version it shipped with.")
gr_bv.add_argument("--bumpversion-config", dest="bumpversion_config", default=None,
help="Set the path to a bumpversion config file to use.")
gr_bv.add_argument("--bumpversion-part", dest="bumpversion_part", default=None,
help="Select the part of the version string that you want to bump.")
gr_bv.add_argument("--bumpversion-file", dest="bumpversion_files", action="append", default=[],
help="List the files that bumpversion should modify.")
gr_bv.add_argument("--bumpversion-opts", dest="bumpversion_opts", default="",
help="Additional arbitrary command-line options to pass to bumpversion.")
def add_args(parser: configargparse.ArgumentParser) -> None:
global _versioners, _version_parsers
collected_actions = set()
collected_actions.add("none")
for vp in _version_parsers.values():
for action in vp.supported_actions:
collected_actions.add(action)
parser.add_argument("--help-versioner", choices=_versioners.keys(), default=None,
action=versioner_help.VersionerHelpAction)
parser.add_argument("--help-versionparser", choices=_version_parsers.keys(), default=None,
action=parser_help.VersionParserHelpAction)
gp_version = parser.add_argument_group("Version determination")
gp_version.add_argument("--versioner", dest="input_versioner", default=None,
help="Specify from where to read the base version string. See --help-versioner for "
"details. Most versioners take specific additional command-line parameters")
gp_version.add_argument("--version-parser", dest="version_parser", choices=_version_parsers.keys(), default="semver",
help="Parse the version string read by --versioner with this parser. See "
"--help-versionparser for details")
gp_version.add_argument("--version-action", dest="version_action",
choices=collected_actions, default="none",
help="Choose what the selected Store should instruct its preferred Version Parser to do to "
"the version for the output package. Most included Version Parsers can only increment "
"numeric version parts. If you need more control, you should take a look at the "
"bumpversion Versioner")
for v in _versioners.values():
v.add_args(parser)
for vp in _version_parsers.values():
vp.add_args(parser)
def __call__(self, parser: configargparse.ArgumentParser, namespace: configargparse.Namespace,
values: Union[str, Sequence[Any], None], option_string: str=None) -> None:
from gopythongo.assemblers import get_assemblers
assemblers = get_assemblers()
if values in assemblers.keys():
assemblers[cast(str, values)].print_help()
else:
print("Assemblers\n"
"==========\n"
"\n")
parser.exit(0)
def add_args(self, parser: configargparse.ArgumentParser) -> None:
_docker_args.add_shared_args(parser)
gp_docker = parser.add_argument_group("Docker Builder options")
gp_docker.add_argument("--docker-buildfile", dest="docker_buildfile", default=None,
help="Specify a Dockerfile to build the the build environment. The build commands will "
"then be executed inside the resulting container. The file is always processed as "
"a Jinja template and must contain certain variable placeholders. Read "
"--help-builder=docker for more information.")
gp_docker.add_argument("--docker-leave-containers", dest="docker_leave_containers", action="store_true",
default=False, env_var="DOCKER_LEAVE_CONTAINERS",
help="After creating a build environment and a runtime container, if this option is "
"used, GoPythonGo will not use 'docker rm' to clean up the resulting containers.")
gp_docker.add_argument("--docker-leave-images", dest="docker_leave_images", action="store_true",
default=False, env_var="DOCKER_LEAVE_IMAGES",
help="After creating a build environment and a runtime container, if this option is "
"used, GoPythonGo will not use '--force-rm' to clean up the intermediate build "
"images.")
gp_docker.add_argument("--docker-debug-savecontext", dest="docker_debug_save_context", default=None,
help="Set this to a filename to save the .tar.gz that GoPythonGo assembles as a "
"Docker context to build the build environment container using 'docker build'.")
gp_docker.add_argument("--docker-buildarg", dest="docker_buildargs", default=[], action="append",
help="Allows you to set Docker build args in the form of 'KEY=VALUE' which will be "
"passed to the Docker daemon and into your Dockerfile as ARGs.")
gp_docker.add_argument("--dockerfile-var", dest="dockerfile_vars", default=[], action="append",
help="Allows you to set Dockerfile Jinja template context variables in the form of "
"'key=value' which will be passed into your Dockerfile template before it is "
"rendered to be sent to the Docker daemon.")
def add_args(self, parser: configargparse.ArgumentParser) -> None:
pass
def __call__(self, parser: configargparse.ArgumentParser, namespace: configargparse.Namespace,
values: Union[str, Sequence[Any], None], option_string: str=None) -> None:
from gopythongo.builders import get_builders
builders = get_builders()
if values in builders.keys():
builders[cast(str, values)].print_help()
else:
print("Builders\n"
"========\n"
"\n")
parser.exit(0)
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gr_pbuilder = parser.add_argument_group("Pbuilder Builder options")
gr_pbuilder.add_argument("--use-pbuilder", dest="pbuilder_executable", default="/usr/sbin/pbuilder",
env_var="PBUILDER_EXECUTABLE",
help="Specify an alternative pbuilder executable")
gr_pbuilder.add_argument("--basetgz", dest="basetgz", default="/var/cache/pbuilder/base.tgz", env_var="BASETGZ",
help="Cache and reuse the pbuilder base environment. gopythongo will call pbuilder "
"create on this file if it doesn't exist")
gr_pbuilder.add_argument("--distribution", dest="pbuilder_distribution", default=None, env_var="DISTRIBUTION",
help="Use this distribution for creating the pbuilder environment using debootstrap.")
gr_pbuilder.add_argument("--pbuilder-force-recreate", dest="pbuilder_force_recreate", action="store_true",
help="Delete the base environment if it exists already")
gr_pbuilder.add_argument("--pbuilder-reprovision", dest="pbuilder_reprovision", action="store_true",
default=False,
help="Run all --run-after-create commands regardless of whether the pbuilder base "
"environment already exists.")
gr_pbuilder.add_argument("--pbuilder-opts", dest="pbuilder_opts", default="", env_var="PBUILDER_OPTS",
help="Options which will be put into every pbuilder command-line executed by "
"GoPythonGo")
gr_pbuilder.add_argument("--pbuilder-create-opts", dest="pbuilder_create_opts", default="",
env_var="PBUILDER_CREATE_OPTS",
help="Options which will be appended to the pbuilder --create command-line")
gr_pbuilder.add_argument("--pbuilder-execute-opts", dest="pbuilder_execute_opts", default="",
env_var="PBUILDER_EXECUTE_OPTS",
help="Options which will be appended to the pbuilder --execute command-line")
gr_pbuilder.add_argument("--no-install-defaults", dest="install_defaults", action="store_false",
default=True,
help="By default GoPythonGo will always install python, python-virtualenv, "
"python-pip, python[3]-dev, virtualenv and possibly eatmydata. If you set this "
"flag you will have to install python using --install-pkg, or GoPythonGo will "
"not be able to run inside the container, but this gives you more control about "
"what Python version runs.")
def __call__(self, parser: configargparse.ArgumentParser, namespace: configargparse.Namespace,
values: Union[str, Sequence[Any], None], option_string: str=None) -> None:
parser.print_values()
parser.exit(0)
def add_args(self, parser: configargparse.ArgumentParser) -> None:
"""
Add command-line arguments to configure this plugin inside GoPythonGo. Do NOT add *required* arguments
to the command-line parser.
:param parser: An ArgumentParser instance that you can call ``add_argument_group`` etc. on
:type parser: configargparse.ArgumentParser
"""
pass
def __call__(self, parser: configargparse.ArgumentParser, namespace: configargparse.Namespace,
values: Union[str, Sequence[Any], None], option_string: str=None) -> None:
from gopythongo.packers import get_packers
packers = get_packers()
if values in packers.keys():
packers[cast(str, values)].print_help()
else:
print("Packers\n"
"=======\n"
"\n")
parser.exit(0)
def add_args(self, parser: configargparse.ArgumentParser) -> None:
gp_tgz = parser.add_argument_group("Tar/Gzip Packer options")
gp_tgz.add_argument("--targz-basename", dest="targz_basename", default=None,
help="Each .tar.gz created by each instance of --targz in the parameters will be named "
"[basename]_[ext]-[version].tar.gz where [ext] is specified in --targz and [version] "
"is retrieved from the selected Versioner")
gp_tgz.add_argument("--targz", dest="targz", action="append", default=[],
help="Takes an argument in the form 'ext:path' where 'ext' is appended to the "
"targz-basename and then the contents of path are stored and compressed in a .tar.gz "
"archive. 'ext' is optional, but be careful to not overwrite your archives when you "
"use multiple --targz arguments.")
gp_tgz.add_argument("--targz-relative", dest="targz_relative", action="store_true", default=False,
help="Store relative paths in the .tar.gz archives.")
def add_args(parser: configargparse.ArgumentParser) -> None:
for m in _packers.values():
m.add_args(parser)
gr_packers = parser.add_argument_group("Packer shared options")
gr_packers.add_argument("--copy-out", dest="copy_out", default=None,
help="The destination path inside the build environment, where the resulting packages will "
"be copied. This will usually be the path of a bindmount, created with --mount in the "
"build folder of your build server, for example.")
parser.add_argument("--help-packer", action=PackerHelpAction, choices=_packers.keys(), default=None)