Exemplo n.º 1
0
    def _create_parser(cls, seed_values=None):
        """Creates a config parser that supports %([key-name])s value substitution.

    A handful of seed values will be set to act as if specified in the loaded config file's DEFAULT
    section, and be available for use in substitutions.  The caller may override some of these
    seed values.

    :param seed_values: A dict with optional override seed values for buildroot, pants_workdir,
                        pants_supportdir and pants_distdir.
    """
        seed_values = seed_values or {}
        buildroot = seed_values.get('buildroot', get_buildroot())

        all_seed_values = {
            'buildroot': buildroot,
            'homedir': os.path.expanduser('~'),
            'user': getpass.getuser(),
            'pants_bootstrapdir': get_pants_cachedir(),
            'pants_configdir': get_pants_configdir(),
        }

        def update_dir_from_seed_values(key, default):
            all_seed_values[key] = seed_values.get(
                key, os.path.join(buildroot, default))

        update_dir_from_seed_values('pants_workdir', '.pants.d')
        update_dir_from_seed_values('pants_supportdir', 'build-support')
        update_dir_from_seed_values('pants_distdir', 'dist')

        return configparser.SafeConfigParser(all_seed_values)
Exemplo n.º 2
0
    def _determine_seed_values(*,
                               seed_values: Optional[SeedValues] = None
                               ) -> Dict[str, str]:
        """We pre-populate several default values to allow %([key-name])s interpolation.

    This sets up those defaults and checks if the user overrided any of the values."""
        safe_seed_values = seed_values or {}
        buildroot = cast(str, safe_seed_values.get('buildroot',
                                                   get_buildroot()))

        all_seed_values: Dict[str, str] = {
            'buildroot': buildroot,
            'homedir': os.path.expanduser('~'),
            'user': getpass.getuser(),
            'pants_bootstrapdir': get_pants_cachedir(),
            'pants_configdir': get_pants_configdir(),
        }

        def update_seed_values(key: str, *, default_dir: str) -> None:
            all_seed_values[key] = cast(
                str,
                safe_seed_values.get(key, os.path.join(buildroot,
                                                       default_dir)))

        update_seed_values('pants_workdir', default_dir='.pants.d')
        update_seed_values('pants_supportdir', default_dir='build-support')
        update_seed_values('pants_distdir', default_dir='dist')

        return all_seed_values
Exemplo n.º 3
0
  def _create_parser(cls, seed_values=None):
    """Creates a config parser that supports %([key-name])s value substitution.

    A handful of seed values will be set to act as if specified in the loaded config file's DEFAULT
    section, and be available for use in substitutions.  The caller may override some of these
    seed values.

    :param seed_values: A dict with optional override seed values for buildroot, pants_workdir,
                        pants_supportdir and pants_distdir.
    """
    seed_values = seed_values or {}
    buildroot = seed_values.get('buildroot', get_buildroot())

    all_seed_values = {
      'buildroot': buildroot,
      'homedir': os.path.expanduser('~'),
      'user': getpass.getuser(),
      'pants_bootstrapdir': get_pants_cachedir(),
      'pants_configdir': get_pants_configdir(),
    }

    def update_dir_from_seed_values(key, default):
      all_seed_values[key] = seed_values.get(key, os.path.join(buildroot, default))
    update_dir_from_seed_values('pants_workdir', '.pants.d')
    update_dir_from_seed_values('pants_supportdir', 'build-support')
    update_dir_from_seed_values('pants_distdir', 'dist')

    return configparser.SafeConfigParser(all_seed_values)
Exemplo n.º 4
0
 def test_expand_home_configdir(self) -> None:
     with environment_as(XDG_CONFIG_HOME="~/somewhere/in/home"):
         self.assertEqual(
             os.path.expanduser(os.path.join("~/somewhere/in/home",
                                             "pants")),
             get_pants_configdir(),
         )
Exemplo n.º 5
0
    def _determine_seed_values(*,
                               seed_values: Optional[SeedValues] = None
                               ) -> Dict[str, str]:
        """We pre-populate several default values to allow %([key-name])s interpolation.

        This sets up those defaults and checks if the user overrode any of the values.
        """
        safe_seed_values = seed_values or {}
        buildroot = cast(str, safe_seed_values.get("buildroot",
                                                   get_buildroot()))

        all_seed_values: Dict[str, str] = {
            "buildroot": buildroot,
            "homedir": os.path.expanduser("~"),
            "user": getpass.getuser(),
            "pants_bootstrapdir": get_pants_cachedir(),
            "pants_configdir": get_pants_configdir(),
        }

        def update_seed_values(key: str, *, default_dir: str) -> None:
            all_seed_values[key] = cast(
                str,
                safe_seed_values.get(key, os.path.join(buildroot,
                                                       default_dir)))

        update_seed_values("pants_workdir", default_dir=".pants.d")
        update_seed_values("pants_supportdir", default_dir="build-support")
        update_seed_values("pants_distdir", default_dir="dist")

        return all_seed_values
Exemplo n.º 6
0
  def register_bootstrap_options(cls, register):
    """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
    buildroot = get_buildroot()
    register('--plugins', advanced=True, type=Options.list, help='Load these plugins.')
    register('--backend-packages', advanced=True, type=Options.list,
             help='Load backends from these packages that are already on the path.')

    register('--pants-bootstrapdir', advanced=True, metavar='<dir>', default=get_pants_cachedir(),
             help='Use this dir for global cache.')
    register('--pants-configdir', advanced=True, metavar='<dir>', default=get_pants_configdir(),
             help='Use this dir for global config files.')
    register('--pants-workdir', metavar='<dir>', default=os.path.join(buildroot, '.pants.d'),
             help='Write intermediate output files to this dir.')
    register('--pants-supportdir', metavar='<dir>',
             default=os.path.join(buildroot, 'build-support'),
             help='Use support files from this dir.')
    register('--pants-distdir', metavar='<dir>', default=os.path.join(buildroot, 'dist'),
             help='Write end-product artifacts to this dir.')
    register('--config-override', help='A second config file, to override pants.ini.')
    register('--pantsrc', action='store_true', default=True,
             help='Use pantsrc files.')
    register('--pantsrc-files', action='append', metavar='<path>',
             default=['/etc/pantsrc', '~/.pants.rc'],
             help='Override config with values from these files. '
                  'Later files override earlier ones.')
    register('--pythonpath', action='append',
             help='Add these directories to PYTHONPATH to search for plugins.')
    register('--target-spec-file', action='append', dest='target_spec_files',
             help='Read additional specs from this file, one per line')

    # These logging options are registered in the bootstrap phase so that plugins can log during
    # registration and not so that their values can be interpolated in configs.
    register('-d', '--logdir', metavar='<dir>',
             help='Write logs to files under this directory.')

    # Although logging supports the WARN level, its not documented and could conceivably be yanked.
    # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
    # setup a 'WARN' logging level name that maps to 'WARNING'.
    logging.addLevelName(logging.WARNING, 'WARN')
    register('-l', '--level', choices=['debug', 'info', 'warn'], default='info', recursive=True,
             help='Set the logging level.')

    register('-q', '--quiet', action='store_true',
             help='Squelches all console output apart from errors.')
Exemplo n.º 7
0
  def register_bootstrap_options(cls, register):
    """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
    buildroot = get_buildroot()

    # Although logging supports the WARN level, its not documented and could conceivably be yanked.
    # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
    # setup a 'WARN' logging level name that maps to 'WARNING'.
    logging.addLevelName(logging.WARNING, 'WARN')
    register('-l', '--level', choices=['debug', 'info', 'warn'], default='info', recursive=True,
             help='Set the logging level.')
    register('-q', '--quiet', type=bool, recursive=True,
             help='Squelches most console output.')
    # Not really needed in bootstrap options, but putting it here means it displays right
    # after -l and -q in help output, which is conveniently contextual.
    register('--colors', type=bool, default=True, recursive=True,
             help='Set whether log messages are displayed in color.')

    # Pants code uses this only to verify that we are of the requested version. However
    # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
    # and use it to select the right version.
    # Note that to print the version of the pants instance you're running, use -v, -V or --version.
    register('--pants-version', advanced=True, default=pants_version(),
             help='Use this pants version.')

    register('--plugins', advanced=True, type=list, help='Load these plugins.')
    register('--plugin-cache-dir', advanced=True,
             default=os.path.join(get_pants_cachedir(), 'plugins'),
             help='Cache resolved plugin requirements here.')

    register('--backend-packages', advanced=True, type=list,
             help='Load backends from these packages that are already on the path.')

    register('--pants-bootstrapdir', advanced=True, metavar='<dir>', default=get_pants_cachedir(),
             help='Use this dir for global cache.')
    register('--pants-configdir', advanced=True, metavar='<dir>', default=get_pants_configdir(),
             help='Use this dir for global config files.')
    register('--pants-workdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, '.pants.d'),
             help='Write intermediate output files to this dir.')
    register('--pants-supportdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'build-support'),
             help='Use support files from this dir.')
    register('--pants-distdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'dist'),
             help='Write end-product artifacts to this dir.')
    register('--pants-config-files', advanced=True, type=list,
             default=[get_default_pants_config_file()], help='Paths to Pants config files.')
    # TODO: Deprecate --config-override in favor of --pants-config-files.
    # But only once we're able to both append and override list-valued options, as there are
    # use-cases for both here.
    # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
    # to set extra config file locations in an initial bootstrap config file.
    register('--config-override', advanced=True, type=list, metavar='<path>',
             help='A second config file, to override pants.ini.')
    register('--pantsrc', advanced=True, type=bool, default=True,
             help='Use pantsrc files.')
    register('--pantsrc-files', advanced=True, type=list, metavar='<path>',
             default=['/etc/pantsrc', '~/.pants.rc'],
             help='Override config with values from these files. '
                  'Later files override earlier ones.')
    register('--pythonpath', advanced=True, type=list,
             help='Add these directories to PYTHONPATH to search for plugins.')
    register('--target-spec-file', type=list, dest='target_spec_files',
             help='Read additional specs from this file, one per line')
    register('--verify-config', type=bool, default=True,
             help='Verify that all config file values correspond to known options.')

    # These logging options are registered in the bootstrap phase so that plugins can log during
    # registration and not so that their values can be interpolated in configs.
    register('-d', '--logdir', advanced=True, metavar='<dir>',
             help='Write logs to files under this directory.')

    # This facilitates bootstrap-time configuration of pantsd usage such that we can
    # determine whether or not to use the Pailgun client to invoke a given pants run
    # without resorting to heavier options parsing.
    register('--enable-pantsd', advanced=True, type=bool, default=False,
             help='Enables use of the pants daemon. (Beta)')
Exemplo n.º 8
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

        "Bootstrap options" are a small set of options whose values are useful when registering other
        options. Therefore we must bootstrap them early, before other options are registered, let
        alone parsed.

        Bootstrap option values can be interpolated into the config file, and can be referenced
        programmatically in registration code, e.g., as register.bootstrap.pants_workdir.

        Note that regular code can also access these options as normal global-scope options. Their
        status as "bootstrap options" is only pertinent during option registration.
        """
        buildroot = get_buildroot()
        default_distdir_name = "dist"
        default_rel_distdir = f"/{default_distdir_name}/"

        register(
            "-l",
            "--level",
            type=LogLevel,
            default=LogLevel.INFO,
            recursive=True,
            help="Set the logging level.",
        )

        register(
            "--log-show-rust-3rdparty",
            type=bool,
            default=False,
            advanced=True,
            help=
            "Whether to show/hide logging done by 3rdparty rust crates used by the pants "
            "engine.",
        )

        # Toggles v1/v2 `Task` vs `@rule` pipelines on/off.
        # Having these in bootstrap options allows them to affect registration of non-bootstrap options.
        register("--v1",
                 advanced=True,
                 type=bool,
                 default=True,
                 help="Enables execution of v1 Tasks.")

        register(
            "--v2",
            advanced=True,
            type=bool,
            default=True,
            help="Enables execution of v2 @goal_rules.",
        )

        # TODO(#7203): make a regexp option type!
        register(
            "--ignore-pants-warnings",
            type=list,
            member_type=str,
            default=[],
            advanced=True,
            help="Regexps matching warning strings to ignore, e.g. "
            '["DEPRECATED: scope some_scope will be removed"]. The regexps will be matched '
            "from the start of the warning string, and will always be case-insensitive. "
            "See the `warnings` module documentation for more background on these are used.",
        )
        register(
            "--option-name-check-distance",
            advanced=True,
            type=int,
            default=2,
            help=
            "The maximum Levenshtein distance to use when offering suggestions for invalid "
            "option names.",
        )

        register(
            "--pants-version",
            advanced=True,
            default=pants_version(),
            help=
            "Use this pants version. Note Pants code only uses this to verify that you are "
            "using the requested version, as Pants cannot dynamically change the version it "
            "is using once the program is already running. This option is useful to set in "
            "your pants.toml, however, and then you can grep the value to select which "
            "version to use for setup scripts (e.g. `./pants`), runner scripts, IDE plugins, "
            "etc. For example, the setup script we distribute at https://www.pantsbuild.org/install.html#recommended-installation "
            "uses this value to determine which Python version to run with. You may find the "
            "version of the pants instance you are running using -v, -V, or --version.",
        )
        register(
            "--pants-bin-name",
            advanced=True,
            default="./pants",
            help="The name of the script or binary used to invoke pants. "
            "Useful when printing help messages.",
        )

        register(
            "--plugins",
            advanced=True,
            type=list,
            help=
            "Allow v1 backends to be loaded from these plugins.  The default backends for "
            "each plugin will be loaded automatically. Other backends in a plugin can be "
            "loaded by listing them in --backend-packages.",
        )
        register(
            "--plugins2",
            advanced=True,
            type=list,
            help=
            "Allow v2 backends to be loaded from these plugins.  The default backends for "
            "each plugin will be loaded automatically. Other backends in a plugin can be "
            "loaded by listing them in --backend-packages.",
        )
        register(
            "--plugins-force-resolve",
            advanced=True,
            type=bool,
            default=False,
            help="Re-resolve plugins even if previously resolved.",
        )
        register(
            "--plugin-cache-dir",
            advanced=True,
            default=os.path.join(get_pants_cachedir(), "plugins"),
            help="Cache resolved plugin requirements here.",
        )

        register(
            "--backend-packages",
            advanced=True,
            type=list,
            default=[
                "pants.backend.graph_info",
                "pants.backend.python",
                "pants.backend.python.lint.isort",
                "pants.backend.jvm",
                "pants.backend.native",
                "pants.backend.codegen.protobuf.java",
                "pants.backend.codegen.thrift.java",
                "pants.backend.codegen.thrift.python",
                "pants.backend.codegen.grpcio.python",
                "pants.backend.project_info",
                "pants.cache",
            ],
            help=
            ("Register v1 tasks from these backends. The backend packages must be present on "
             "the PYTHONPATH, typically because they are in the Pants core dist, in a "
             "plugin dist, or available as sources in the repo."),
        )
        register(
            "--backend-packages2",
            advanced=True,
            type=list,
            default=[],
            help=
            ("Register v2 rules from these backends. The backend packages must be present on "
             "the PYTHONPATH, typically because they are in the Pants core dist, in a "
             "plugin dist, or available as sources in the repo."),
        )

        register(
            "--pants-bootstrapdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_cachedir(),
            help="Use this dir for global cache.",
        )
        register(
            "--pants-configdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_configdir(),
            help="Use this dir for global config files.",
        )
        register(
            "--pants-workdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, ".pants.d"),
            help="Write intermediate output files to this dir.",
        )
        register(
            "--pants-physical-workdir-base",
            advanced=True,
            metavar="<dir>",
            default=None,
            help=
            "When set, a base directory in which to store `--pants-workdir` contents. "
            "If this option is a set, the workdir will be created as symlink into a "
            "per-workspace subdirectory.",
        )
        register(
            "--pants-supportdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "build-support"),
            help="Use support files from this dir.",
        )
        register(
            "--pants-distdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "dist"),
            help="Write end-product artifacts to this dir.",
        )
        register(
            "--pants-subprocessdir",
            advanced=True,
            default=os.path.join(buildroot, ".pids"),
            help=
            "The directory to use for tracking subprocess metadata, if any. This should "
            "live outside of the dir used by `--pants-workdir` to allow for tracking "
            "subprocesses that outlive the workdir data (e.g. `./pants server`).",
        )
        register(
            "--pants-config-files",
            advanced=True,
            type=list,
            daemon=False,
            default=[get_default_pants_config_file()],
            help="Paths to Pants config files.",
        )
        # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
        # to set extra config file locations in an initial bootstrap config file.
        register("--pantsrc",
                 advanced=True,
                 type=bool,
                 default=True,
                 help="Use pantsrc files.")
        register(
            "--pantsrc-files",
            advanced=True,
            type=list,
            metavar="<path>",
            daemon=False,
            default=["/etc/pantsrc", "~/.pants.rc"],
            help="Override config with values from these files. "
            "Later files override earlier ones.",
        )
        register(
            "--pythonpath",
            advanced=True,
            type=list,
            help="Add these directories to PYTHONPATH to search for plugins.",
        )
        register(
            "--spec-file",
            type=list,
            dest="spec_files",
            daemon=False,
            help=
            "Read additional specs from this file (e.g. target addresses or file names). "
            "Each spec should be one per line.",
        )
        register(
            "--verify-config",
            type=bool,
            default=True,
            daemon=False,
            advanced=True,
            help=
            "Verify that all config file values correspond to known options.",
        )

        register(
            "--build-ignore",
            advanced=True,
            type=list,
            default=[
                ".*/", "bower_components/", "node_modules/", "*.egg-info/"
            ],
            help="Paths to ignore when identifying BUILD files. "
            "This does not affect any other filesystem operations. "
            "Patterns use the gitignore pattern syntax (https://git-scm.com/docs/gitignore).",
        )
        register(
            "--pants-ignore",
            advanced=True,
            type=list,
            member_type=str,
            default=[".*/", default_rel_distdir],
            help=
            "Paths to ignore for all filesystem operations performed by pants "
            "(e.g. BUILD file scanning, glob matching, etc). "
            "Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore). "
            "The `--pants-distdir` and `--pants-workdir` locations are inherently ignored."
            "--pants-ignore can be used in tandem with --pants-ignore-use-gitignore, and any rules "
            "specified here apply after rules specified in a .gitignore file.",
        )
        register(
            "--pants-ignore-use-gitignore",
            advanced=True,
            type=bool,
            default=True,
            help=
            "Make use of a root .gitignore file when determining whether to ignore filesystem "
            "operations performed by pants. If used together with `--pants-ignore`, any exclude/include "
            "patterns specified there apply after .gitignore rules.",
        )
        register(
            "--owners-not-found-behavior",
            advanced=True,
            type=OwnersNotFoundBehavior,
            default=OwnersNotFoundBehavior.error,
            help=
            "What to do when file arguments do not have any owning target. This happens when there "
            "are no targets whose `sources` fields include the file argument.",
        )
        register(
            "--files-not-found-behavior",
            advanced=True,
            type=FileNotFoundBehavior,
            default=FileNotFoundBehavior.warn,
            help=
            "What to do when files and globs specified in BUILD files, such as in the "
            "`sources` field, cannot be found. This happens when the files do not exist on "
            "your machine or when they are ignored by the `--pants-ignore` option.",
        )

        # TODO(#7203): make a regexp option type!
        register(
            "--exclude-target-regexp",
            advanced=True,
            type=list,
            default=[],
            daemon=False,
            metavar="<regexp>",
            help="Exclude target roots that match these regexes.",
        )
        register(
            "--subproject-roots",
            type=list,
            advanced=True,
            default=[],
            help=
            "Paths that correspond with build roots for any subproject that this "
            "project depends on.",
        )

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register(
            "-d",
            "--logdir",
            advanced=True,
            metavar="<dir>",
            help="Write logs to files under this directory.",
        )

        # This facilitates bootstrap-time configuration of pantsd usage such that we can
        # determine whether or not to use the Pailgun client to invoke a given pants run
        # without resorting to heavier options parsing.
        register(
            "--enable-pantsd",
            advanced=True,
            type=bool,
            default=False,
            help=
            "Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)",
        )

        # Whether or not to make necessary arrangements to have concurrent runs in pants.
        # In practice, this means that if this is set, a run will not even try to use pantsd.
        # NB: Eventually, we would like to deprecate this flag in favor of making pantsd runs parallelizable.
        register(
            "--concurrent",
            advanced=True,
            type=bool,
            default=False,
            daemon=False,
            help=
            "Enable concurrent runs of pants. Without this enabled, pants will "
            "start up all concurrent invocations (e.g. in other terminals) without pantsd. "
            "Enabling this option requires parallel pants invocations to block on the first",
        )

        # Calling pants command (inner run) from other pants command is unusual behaviour,
        # and most users should never set this flag.
        # It is automatically set by pants when an inner run is detected.
        # Currently, pants commands with this option set don't use pantsd,
        # but this effect should not be relied upon.
        # This option allows us to know who was the parent of pants inner runs for informational purposes.
        register(
            "--parent-build-id",
            advanced=True,
            default=None,
            help=
            "The build ID of the other pants run which spawned this one, if any.",
        )

        # Shutdown pantsd after the current run.
        # This needs to be accessed at the same time as enable_pantsd,
        # so we register it at bootstrap time.
        register(
            "--shutdown-pantsd-after-run",
            advanced=True,
            type=bool,
            default=False,
            removal_version="1.29.0.dev2",
            removal_hint=
            "Not widely used, and will soon be rewritten to be inherent.",
            help=
            "Create a new pantsd server, and use it, and shut it down immediately after. "
            "If pantsd is already running, it will shut it down and spawn a new instance (Beta)",
        )

        # NB: We really don't want this option to invalidate the daemon, because different clients might have
        # different needs. For instance, an IDE might have a very long timeout because it only wants to refresh
        # a project in the background, while a user might want a shorter timeout for interactivity.
        register(
            "--pantsd-timeout-when-multiple-invocations",
            advanced=True,
            type=float,
            default=60.0,
            daemon=False,
            help=
            "The maximum amount of time to wait for the invocation to start until "
            "raising a timeout exception. "
            "Because pantsd currently does not support parallel runs, "
            "any prior running Pants command must be finished for the current one to start. "
            "To never timeout, use the value -1.",
        )

        # These facilitate configuring the native engine.
        register(
            "--native-engine-visualize-to",
            advanced=True,
            default=None,
            type=dir_option,
            daemon=False,
            help=
            "A directory to write execution and rule graphs to as `dot` files. The contents "
            "of the directory will be overwritten if any filenames collide.",
        )
        register(
            "--print-exception-stacktrace",
            advanced=True,
            type=bool,
            help=
            "Print to console the full exception stack trace if encountered.",
        )

        # BinaryUtil options.
        register(
            "--binaries-baseurls",
            type=list,
            advanced=True,
            default=["https://binaries.pantsbuild.org"],
            help="List of URLs from which binary tools are downloaded. URLs are "
            "searched in order until the requested path is found.",
        )
        register(
            "--binaries-fetch-timeout-secs",
            type=int,
            default=30,
            advanced=True,
            daemon=False,
            help=
            "Timeout in seconds for URL reads when fetching binary tools from the "
            "repos specified by --baseurls.",
        )
        register(
            "--binaries-path-by-id",
            type=dict,
            advanced=True,
            help=
            ("Maps output of uname for a machine to a binary search path: "
             "(sysname, id) -> (os, arch), e.g. {('darwin', '15'): ('mac', '10.11'), "
             "('linux', 'arm32'): ('linux', 'arm32')}."),
        )
        register(
            "--allow-external-binary-tool-downloads",
            type=bool,
            default=True,
            advanced=True,
            help=
            "If False, require BinaryTool subclasses to download their contents from urls "
            "generated from --binaries-baseurls, even if the tool has an external url "
            "generator. This can be necessary if using Pants in an environment which cannot "
            "contact the wider Internet.",
        )

        # Pants Daemon options.
        register(
            "--pantsd-pailgun-host",
            advanced=True,
            default="127.0.0.1",
            removal_version="1.30.0.dev0",
            removal_hint=
            "The nailgun protocol is not authenticated, and so only binds to "
            "127.0.0.1.",
            help="The host to bind the pants nailgun server to.",
        )
        register(
            "--pantsd-pailgun-port",
            advanced=True,
            type=int,
            default=0,
            help=
            "The port to bind the pants nailgun server to. Defaults to a random port.",
        )
        # TODO(#7514): Make this default to 1.0 seconds if stdin is a tty!
        register(
            "--pantsd-pailgun-quit-timeout",
            advanced=True,
            type=float,
            default=5.0,
            help=
            "The length of time (in seconds) to wait for further output after sending a "
            "signal to the remote pantsd process before killing it.",
        )
        register(
            "--pantsd-log-dir",
            advanced=True,
            default=None,
            help="The directory to log pantsd output to.",
        )
        register(
            "--pantsd-invalidation-globs",
            advanced=True,
            type=list,
            default=[],
            help=
            "Filesystem events matching any of these globs will trigger a daemon restart. "
            "Pants' own code, plugins, and `--pants-config-files` are inherently invalidated.",
        )

        # Watchman options.
        register(
            "--watchman-enable",
            type=bool,
            advanced=True,
            default=False,
            removal_version="1.30.0.dev0",
            removal_hint=
            "The native watcher is now sufficient to monitor for filesystem changes.",
            help=
            "Use the watchman daemon filesystem event watcher to watch for changes "
            "in the buildroot in addition to the built in watcher.",
        )
        register("--watchman-version",
                 advanced=True,
                 default="4.9.0-pants1",
                 help="Watchman version.")
        register(
            "--watchman-supportdir",
            advanced=True,
            default="bin/watchman",
            help=
            "Find watchman binaries under this dir. Used as part of the path to lookup "
            "the binary with --binaries-baseurls and --pants-bootstrapdir.",
        )
        register(
            "--watchman-startup-timeout",
            type=float,
            advanced=True,
            default=60.0,
            help=
            "The watchman socket timeout (in seconds) for the initial `watch-project` command. "
            "This may need to be set higher for larger repos due to watchman startup cost.",
        )
        register(
            "--watchman-socket-timeout",
            type=float,
            advanced=True,
            default=0.1,
            help=
            "The watchman client socket timeout in seconds. Setting this to too high a "
            "value can negatively impact the latency of runs forked by pantsd.",
        )
        register(
            "--watchman-socket-path",
            type=str,
            advanced=True,
            default=None,
            help=
            "The path to the watchman UNIX socket. This can be overridden if the default "
            "absolute path length exceeds the maximum allowed by the OS.",
        )

        register(
            "--build-file-prelude-globs",
            advanced=True,
            type=list,
            default=[],
            help=
            "Python files to evaluate and whose symbols should be exposed to all BUILD files ."
            "This allows for writing functions which create multiple rules, or set default "
            "arguments for rules. The order these files will be evaluated is undefined - they should not rely on each "
            "other, or override symbols from each other.",
        )

        register(
            "--local-store-dir",
            advanced=True,
            help="Directory to use for engine's local file store.",
            # This default is also hard-coded into the engine's rust code in
            # fs::Store::default_path
            default=os.path.expanduser("~/.cache/pants/lmdb_store"),
        )
        register(
            "--local-execution-root-dir",
            advanced=True,
            help=
            "Directory to use for engine's local process execution sandboxing.",
            default=tempfile.gettempdir(),
        )
        register(
            "--remote-execution",
            advanced=True,
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.remote_execution,
            help="Enables remote workers for increased parallelism. (Alpha)",
        )
        register(
            "--remote-store-server",
            advanced=True,
            type=list,
            default=[],
            help=
            "host:port of grpc server to use as remote execution file store.",
        )
        # TODO: Infer this from remote-store-connection-limit.
        register(
            "--remote-store-thread-count",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_thread_count,
            help=
            "Thread count to use for the pool that interacts with the remote file store.",
        )
        register(
            "--remote-execution-server",
            advanced=True,
            help=
            "host:port of grpc server to use as remote execution scheduler.",
        )
        register(
            "--remote-store-chunk-bytes",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_chunk_bytes,
            help=
            "Size in bytes of chunks transferred to/from the remote file store.",
        )
        register(
            "--remote-store-chunk-upload-timeout-seconds",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.
            remote_store_chunk_upload_timeout_seconds,
            help=
            "Timeout (in seconds) for uploads of individual chunks to the remote file store.",
        )
        register(
            "--remote-store-rpc-retries",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_rpc_retries,
            help=
            "Number of times to retry any RPC to the remote store before giving up.",
        )
        register(
            "--remote-store-connection-limit",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_connection_limit,
            help=
            "Number of remote stores to concurrently allow connections to.",
        )
        register(
            "--remote-execution-process-cache-namespace",
            advanced=True,
            help="The cache namespace for remote process execution. "
            "Bump this to invalidate every artifact's remote execution. "
            "This is the remote execution equivalent of the legacy cache-key-gen-version "
            "flag.",
        )
        register(
            "--remote-instance-name",
            advanced=True,
            help=
            "Name of the remote execution instance to use. Used for routing within "
            "--remote-execution-server and --remote-store-server.",
        )
        register(
            "--remote-ca-certs-path",
            advanced=True,
            help=
            "Path to a PEM file containing CA certificates used for verifying secure "
            "connections to --remote-execution-server and --remote-store-server. "
            "If not specified, TLS will not be used.",
        )
        register(
            "--remote-oauth-bearer-token-path",
            advanced=True,
            help=
            "Path to a file containing an oauth token to use for grpc connections to "
            "--remote-execution-server and --remote-store-server. If not specified, no "
            "authorization will be performed.",
        )
        register(
            "--remote-execution-extra-platform-properties",
            advanced=True,
            help="Platform properties to set on remote execution requests. "
            "Format: property=value. Multiple values should be specified as multiple "
            "occurrences of this flag. Pants itself may add additional platform properties.",
            type=list,
            default=[],
        )
        register(
            "--remote-execution-headers",
            advanced=True,
            help="Headers to set on remote execution requests. "
            "Format: header=value. Pants itself may add additional headers.",
            type=dict,
            default={},
        )
        register(
            "--process-execution-local-parallelism",
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_local_parallelism,
            advanced=True,
            help="Number of concurrent processes that may be executed locally.",
        )
        register(
            "--process-execution-remote-parallelism",
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_remote_parallelism,
            advanced=True,
            help=
            "Number of concurrent processes that may be executed remotely.",
        )
        register(
            "--process-execution-cleanup-local-dirs",
            type=bool,
            default=True,
            advanced=True,
            help=
            "Whether or not to cleanup directories used for local process execution "
            "(primarily useful for e.g. debugging).",
        )
        register(
            "--process-execution-speculation-delay",
            type=float,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_speculation_delay,
            advanced=True,
            help=
            "Number of seconds to wait before speculating a second request for a slow process. "
            " see `--process-execution-speculation-strategy`",
        )
        register(
            "--process-execution-speculation-strategy",
            choices=["remote_first", "local_first", "none"],
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_speculation_strategy,
            help=
            "Speculate a second request for an underlying process if the first one does not complete within "
            "`--process-execution-speculation-delay` seconds.\n"
            "`local_first` (default): Try to run the process locally first, "
            "and fall back to remote execution if available.\n"
            "`remote_first`: Run the process on the remote execution backend if available, "
            "and fall back to the local host if remote calls take longer than the speculation timeout.\n"
            "`none`: Do not speculate about long running processes.",
            advanced=True,
        )
        register(
            "--process-execution-use-local-cache",
            type=bool,
            default=True,
            advanced=True,
            help=
            "Whether to keep process executions in a local cache persisted to disk.",
        )
        register(
            "--process-execution-local-enable-nailgun",
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_local_enable_nailgun,
            help=
            "Whether or not to use nailgun to run the requests that are marked as nailgunnable.",
            advanced=True,
        )
        register(
            "--experimental-fs-watcher",
            type=bool,
            default=True,
            advanced=True,
            removal_version="1.30.0.dev0",
            removal_hint="Enabled by default: flag is disabled.",
            help=
            "Whether to use the engine filesystem watcher which registers the workspace"
            " for kernel file change events",
        )
Exemplo n.º 9
0
 def test_expand_home_configdir(self):
   with environment_as(XDG_CONFIG_HOME='~/somewhere/in/home'):
     self.assertEqual(os.path.expanduser(os.path.join('~/somewhere/in/home', 'pants')),
                       get_pants_configdir())
Exemplo n.º 10
0
 def test_get_configdir(self):
   with environment_as(XDG_CONFIG_HOME=''):
     self.assertEqual(os.path.expanduser('~/.config/pants'), get_pants_configdir())
Exemplo n.º 11
0
def test_get_pants_configdir() -> None:
    assert Native().default_config_path() == get_pants_configdir()
Exemplo n.º 12
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
        buildroot = get_buildroot()

        # Although logging supports the WARN level, its not documented and could conceivably be yanked.
        # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
        # setup a 'WARN' logging level name that maps to 'WARNING'.
        logging.addLevelName(logging.WARNING, 'WARN')
        register('-l',
                 '--level',
                 choices=['debug', 'info', 'warn'],
                 default='info',
                 recursive=True,
                 help='Set the logging level.')
        register('-q',
                 '--quiet',
                 action='store_true',
                 help='Squelches all console output apart from errors.')
        # Not really needed in bootstrap options, but putting it here means it displays right
        # after -l and -q in help output, which is conveniently contextual.
        register('--colors',
                 action='store_true',
                 default=True,
                 recursive=True,
                 help='Set whether log messages are displayed in color.')

        # NB: Right now this option is a placeholder that is unused within pants itself except when
        # specified on the command line to print the OSS pants version.  Both the IntelliJ Pants plugin
        # and the pantsbuild/setup bootstrap script grep for pants_version though so this option
        # registration serves in part as documentation of the dependency.
        # TODO(John Sirois): Move pantsbuild.pants bootstrapping into pants itself and have it use this
        # version option directly.
        register(
            '-V',
            '--pants-version',
            '--version',  # NB: pants_version is the 1st long option
            # since that's the one read from pants.ini;
            # the version form only works from the CLI.
            nargs=
            '?',  # Allows using the flag with no args on the CLI to print version as well
            # as setting the version in pants.ini
            default=pants_version(
            ),  # Displays the current version correctly in `./pants -h`.
            const=pants_version(
            ),  # Displays the current version via `./pants -V`.
            help="Prints pants' version number and exits.")

        register('--plugins',
                 advanced=True,
                 type=list_option,
                 help='Load these plugins.')
        register(
            '--backend-packages',
            advanced=True,
            type=list_option,
            help=
            'Load backends from these packages that are already on the path.')

        register('--pants-bootstrapdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_cachedir(),
                 help='Use this dir for global cache.')
        register('--pants-configdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_configdir(),
                 help='Use this dir for global config files.')
        register('--pants-workdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, '.pants.d'),
                 help='Write intermediate output files to this dir.')
        register('--pants-supportdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'build-support'),
                 help='Use support files from this dir.')
        register('--pants-distdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'dist'),
                 help='Write end-product artifacts to this dir.')
        register('--config-override',
                 advanced=True,
                 action='append',
                 metavar='<path>',
                 help='A second config file, to override pants.ini.')
        register('--pantsrc',
                 advanced=True,
                 action='store_true',
                 default=True,
                 help='Use pantsrc files.')
        register('--pantsrc-files',
                 advanced=True,
                 action='append',
                 metavar='<path>',
                 default=['/etc/pantsrc', '~/.pants.rc'],
                 help='Override config with values from these files. '
                 'Later files override earlier ones.')
        register(
            '--pythonpath',
            advanced=True,
            action='append',
            help='Add these directories to PYTHONPATH to search for plugins.')
        register('--target-spec-file',
                 action='append',
                 dest='target_spec_files',
                 help='Read additional specs from this file, one per line')

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register('-d',
                 '--logdir',
                 advanced=True,
                 metavar='<dir>',
                 help='Write logs to files under this directory.')
Exemplo n.º 13
0
 def test_get_configdir(self) -> None:
     with environment_as(XDG_CONFIG_HOME=""):
         self.assertEqual(os.path.expanduser("~/.config/pants"),
                          get_pants_configdir())
Exemplo n.º 14
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

        "Bootstrap options" are the set of options necessary to create a Scheduler. If an option is
        not consumed during creation of a Scheduler, it should be in `register_options` instead.

        Bootstrap option values can be interpolated into the config file, and can be referenced
        programmatically in registration code, e.g., as register.bootstrap.pants_workdir.

        Note that regular code can also access these options as normal global-scope options. Their
        status as "bootstrap options" is only pertinent during option registration.
        """
        buildroot = get_buildroot()
        default_distdir_name = "dist"
        default_rel_distdir = f"/{default_distdir_name}/"

        register(
            "-l",
            "--level",
            type=LogLevel,
            default=LogLevel.INFO,
            help="Set the logging level.",
        )

        register(
            "--log-show-rust-3rdparty",
            type=bool,
            default=False,
            advanced=True,
            help=
            "Whether to show/hide logging done by 3rdparty Rust crates used by the Pants "
            "engine.",
        )

        register(
            "--colors",
            type=bool,
            default=sys.stdout.isatty(),
            help=
            ("Whether Pants should use colors in output or not. This may also impact whether "
             "some tools Pants run use color."),
        )

        register(
            "--v1",
            advanced=True,
            type=bool,
            default=False,
            help="Enables execution of v1 Tasks.",
            removal_version="2.1.0.dev0",
            removal_hint=
            "The v1 engine no longer exists. This option does nothing.",
        )

        register(
            "--v2",
            advanced=True,
            type=bool,
            default=True,
            help="Enables execution of v2 @goal_rules.",
            removal_version="2.1.0.dev0",
            removal_hint=
            "The v2 engine is the only one available. This option does nothing.",
        )

        # TODO(#7203): make a regexp option type!
        register(
            "--ignore-pants-warnings",
            type=list,
            member_type=str,
            default=[],
            advanced=True,
            help="Regexps matching warning strings to ignore, e.g. "
            '["DEPRECATED: scope some_scope will be removed"]. The regexps will be matched '
            "from the start of the warning string, and will always be case-insensitive. "
            "See the `warnings` module documentation for more background on these are used.",
        )
        register(
            "--option-name-check-distance",
            advanced=True,
            type=int,
            default=2,
            help=
            ("The maximum Levenshtein distance to use when offering suggestions for invalid "
             "option names."),
            removal_version="2.1.0.dev0",
            removal_hint=
            ("The option `--option-name-check-distance` no longer does anything, as Pants now "
             "always uses the default of 2."),
        )

        register(
            "--pants-version",
            advanced=True,
            default=pants_version(),
            daemon=True,
            help=
            "Use this pants version. Note Pants code only uses this to verify that you are "
            "using the requested version, as Pants cannot dynamically change the version it "
            "is using once the program is already running. This option is useful to set in "
            "your pants.toml, however, and then you can grep the value to select which "
            "version to use for setup scripts (e.g. `./pants`), runner scripts, IDE plugins, "
            "etc. For example, the setup script we distribute at "
            "https://www.pantsbuild.org/docs/installation uses this value to determine which Python"
            "version to run with. You may find the version of the Pants instance you are running "
            "by using -v, -V, or --version.",
        )
        register(
            "--pants-bin-name",
            advanced=True,
            default="./pants",
            help="The name of the script or binary used to invoke Pants. "
            "Useful when printing help messages.",
        )
        register(
            "--plugins",
            advanced=True,
            type=list,
            help=
            "Allow backends to be loaded from these plugins.  The default backends for "
            "each plugin will be loaded automatically. Other backends in a plugin can be "
            "loaded by listing them in --backend-packages.",
        )
        register(
            "--plugins2",
            advanced=True,
            type=list,
            removal_version="2.1.0.dev0",
            removal_hint="Use --plugins instead.",
            help=
            "Allow backends to be loaded from these plugins.  The default backends for "
            "each plugin will be loaded automatically. Other backends in a plugin can be "
            "loaded by listing them in --backend-packages.",
        )
        register(
            "--plugins-force-resolve",
            advanced=True,
            type=bool,
            default=False,
            help="Re-resolve plugins even if previously resolved.",
        )
        register(
            "--plugin-cache-dir",
            advanced=True,
            default=os.path.join(get_pants_cachedir(), "plugins"),
            help="Cache resolved plugin requirements here.",
        )
        register(
            "--backend-packages",
            advanced=True,
            type=list,
            default=[],
            help=
            ("Register rules from these backends. The backend packages must be present on "
             "the PYTHONPATH, typically because they are in the Pants core dist, in a "
             "plugin dist, or available as sources in the repo."),
        )
        register(
            "--backend-packages2",
            advanced=True,
            type=list,
            default=[],
            removal_version="2.1.0.dev0",
            removal_hint="Use --backend-packages instead.",
            help=
            ("Register rules from these backends. The backend packages must be present on "
             "the PYTHONPATH, typically because they are in the Pants core dist, in a "
             "plugin dist, or available as sources in the repo."),
        )

        register(
            "--pants-bootstrapdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_cachedir(),
            help="Use this dir for global cache.",
        )
        register(
            "--pants-configdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_configdir(),
            help="Use this dir for global config files.",
        )
        register(
            "--pants-workdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, ".pants.d"),
            daemon=True,
            help="Write intermediate output files to this dir.",
        )
        register(
            "--pants-physical-workdir-base",
            advanced=True,
            metavar="<dir>",
            default=None,
            daemon=True,
            help=
            "When set, a base directory in which to store `--pants-workdir` contents. "
            "If this option is a set, the workdir will be created as symlink into a "
            "per-workspace subdirectory.",
        )
        register(
            "--pants-supportdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "build-support"),
            help="Use support files from this dir.",
        )
        register(
            "--pants-distdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "dist"),
            help="Write end-product artifacts to this dir.",
        )
        register(
            "--pants-subprocessdir",
            advanced=True,
            default=os.path.join(buildroot, ".pids"),
            daemon=True,
            help=
            "The directory to use for tracking subprocess metadata, if any. This should "
            "live outside of the dir used by `--pants-workdir` to allow for tracking "
            "subprocesses that outlive the workdir data.",
        )
        register(
            "--pants-config-files",
            advanced=True,
            type=list,
            # NB: We don't fingerprint the list of config files, because the content of the config
            # files independently affects fingerprints.
            fingerprint=False,
            default=[get_default_pants_config_file()],
            help="Paths to Pants config files.",
        )
        register(
            "--pantsrc",
            advanced=True,
            type=bool,
            default=True,
            # NB: See `--pants-config-files`.
            fingerprint=False,
            help="Use pantsrc files.",
        )
        register(
            "--pantsrc-files",
            advanced=True,
            type=list,
            metavar="<path>",
            # NB: See `--pants-config-files`.
            fingerprint=False,
            default=["/etc/pantsrc", "~/.pants.rc"],
            help=
            ("Override config with values from these files, using syntax matching that of "
             "`--pants-config-files`."),
        )
        register(
            "--pythonpath",
            advanced=True,
            type=list,
            help="Add these directories to PYTHONPATH to search for plugins.",
        )
        register(
            "--spec-files",
            type=list,
            # NB: See `--pants-config-files`.
            fingerprint=False,
            help=
            "Read additional specs (e.g., target addresses or file names), one per line,"
            "from these files.",
        )
        register(
            "--spec-file",
            type=list,
            removal_version="2.1.0.dev0",
            removal_hint="Use --spec-files",
            fingerprint=False,
            help=
            "Read additional specs from this file (e.g. target addresses or file names). "
            "Each spec should be one per line.",
        )
        register(
            "--verify-config",
            type=bool,
            default=True,
            advanced=True,
            help=
            "Verify that all config file values correspond to known options.",
        )

        register(
            "--pants-ignore",
            advanced=True,
            type=list,
            member_type=str,
            default=[".*/", default_rel_distdir],
            help=
            "Paths to ignore for all filesystem operations performed by pants "
            "(e.g. BUILD file scanning, glob matching, etc). "
            "Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore). "
            "The `--pants-distdir` and `--pants-workdir` locations are inherently ignored. "
            "--pants-ignore can be used in tandem with --pants-ignore-use-gitignore, and any rules "
            "specified here apply after rules specified in a .gitignore file.",
        )
        register(
            "--pants-ignore-use-gitignore",
            advanced=True,
            type=bool,
            default=True,
            help=
            "Make use of a root .gitignore file when determining whether to ignore filesystem "
            "operations performed by Pants. If used together with `--pants-ignore`, any exclude/include "
            "patterns specified there apply after .gitignore rules.",
        )

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register(
            "-d",
            "--logdir",
            advanced=True,
            metavar="<dir>",
            daemon=True,
            help="Write logs to files under this directory.",
        )

        register(
            "--pantsd",
            advanced=True,
            type=bool,
            default=True,
            daemon=True,
            help=
            ("Enables use of the Pants daemon (pantsd). pantsd can significantly improve "
             "runtime performance by lowering per-run startup cost, and by caching filesystem "
             "operations and rule execution."),
        )

        # Whether or not to make necessary arrangements to have concurrent runs in pants.
        # In practice, this means that if this is set, a run will not even try to use pantsd.
        # NB: Eventually, we would like to deprecate this flag in favor of making pantsd runs parallelizable.
        register(
            "--concurrent",
            advanced=True,
            type=bool,
            default=False,
            help=
            "Enable concurrent runs of Pants. Without this enabled, Pants will "
            "start up all concurrent invocations (e.g. in other terminals) without pantsd. "
            "Enabling this option requires parallel Pants invocations to block on the first",
        )

        # Calling pants command (inner run) from other pants command is unusual behaviour,
        # and most users should never set this flag.
        # It is automatically set by pants when an inner run is detected.
        # Currently, pants commands with this option set don't use pantsd,
        # but this effect should not be relied upon.
        # This option allows us to know who was the parent of pants inner runs for informational purposes.
        register(
            "--parent-build-id",
            advanced=True,
            default=None,
            help=
            "The build ID of the other Pants run which spawned this one, if any.",
        )

        # NB: We really don't want this option to invalidate the daemon, because different clients might have
        # different needs. For instance, an IDE might have a very long timeout because it only wants to refresh
        # a project in the background, while a user might want a shorter timeout for interactivity.
        register(
            "--pantsd-timeout-when-multiple-invocations",
            advanced=True,
            type=float,
            default=60.0,
            help=
            "The maximum amount of time to wait for the invocation to start until "
            "raising a timeout exception. "
            "Because pantsd currently does not support parallel runs, "
            "any prior running Pants command must be finished for the current one to start. "
            "To never timeout, use the value -1.",
        )
        register(
            "--pantsd-max-memory-usage",
            advanced=True,
            type=int,
            default=2**30,
            help=
            ("The maximum memory usage of a pantsd process (in bytes). There is at most one "
             "pantsd process per workspace."),
        )

        # These facilitate configuring the native engine.
        register(
            "--native-engine-visualize-to",
            advanced=True,
            default=None,
            type=dir_option,
            help=
            "A directory to write execution and rule graphs to as `dot` files. The contents "
            "of the directory will be overwritten if any filenames collide.",
        )
        register(
            "--print-exception-stacktrace",
            advanced=True,
            type=bool,
            default=False,
            # TODO: We must restart the daemon because of global mutable state in `init/logging.py`
            #  from `ExceptionSink.should_print_exception_stacktrace`. Fix this and only use
            #  `fingerprint=True` instead.
            daemon=True,
            help=
            "Print to console the full exception stack trace if encountered.",
        )

        # BinaryUtil options.
        # TODO: Nuke these once we get rid of src/python/pants/binaries/binary_util.py
        #  (see there for what that will take).
        register(
            "--binaries-baseurls",
            type=list,
            advanced=True,
            default=["https://binaries.pantsbuild.org"],
            help="List of URLs from which binary tools are downloaded. URLs are "
            "searched in order until the requested path is found.",
        )
        register(
            "--binaries-fetch-timeout-secs",
            type=int,
            default=30,
            advanced=True,
            help=
            "Timeout in seconds for URL reads when fetching binary tools from the "
            "repos specified by --baseurls.",
        )
        register(
            "--binaries-path-by-id",
            type=dict,
            advanced=True,
            help=
            ("Maps output of uname for a machine to a binary search path: "
             "(sysname, id) -> (os, arch), e.g. {('darwin', '15'): ('mac', '10.11'), "
             "('linux', 'arm32'): ('linux', 'arm32')}."),
        )
        register(
            "--allow-external-binary-tool-downloads",
            type=bool,
            default=True,
            advanced=True,
            help=
            "If False, require BinaryTool subclasses to download their contents from urls "
            "generated from --binaries-baseurls, even if the tool has an external url "
            "generator. This can be necessary if using Pants in an environment which cannot "
            "contact the wider Internet.",
        )

        # Pants Daemon options.
        register(
            "--pantsd-pailgun-port",
            advanced=True,
            type=int,
            default=0,
            daemon=True,
            help=
            "The port to bind the Pants nailgun server to. Defaults to a random port.",
        )
        # TODO(#7514): Make this default to 1.0 seconds if stdin is a tty!
        register(
            "--pantsd-pailgun-quit-timeout",
            advanced=True,
            type=float,
            default=5.0,
            help=
            "The length of time (in seconds) to wait for further output after sending a "
            "signal to the remote pantsd process before killing it.",
        )
        register(
            "--pantsd-log-dir",
            advanced=True,
            default=None,
            daemon=True,
            help="The directory to log pantsd output to.",
        )
        register(
            "--pantsd-invalidation-globs",
            advanced=True,
            type=list,
            default=[],
            daemon=True,
            help=
            "Filesystem events matching any of these globs will trigger a daemon restart. "
            "Pants's own code, plugins, and `--pants-config-files` are inherently invalidated.",
        )

        cache_instructions = (
            "The path may be absolute or relative. If the directory is within the build root, be "
            "sure to include it in `--pants-ignore`.")
        register(
            "--local-store-dir",
            advanced=True,
            help=
            (f"Directory to use for the local file store, which stores the results of "
             f"subprocesses run by Pants. {cache_instructions}"),
            # This default is also hard-coded into the engine's rust code in
            # fs::Store::default_path so that tools using a Store outside of pants
            # are likely to be able to use the same storage location.
            default=os.path.join(get_pants_cachedir(), "lmdb_store"),
        )
        register(
            "--local-execution-root-dir",
            advanced=True,
            help=
            f"Directory to use for local process execution sandboxing. {cache_instructions}",
            default=tempfile.gettempdir(),
        )
        register(
            "--named-caches-dir",
            advanced=True,
            help=
            ("Directory to use for named global caches for tools and processes with trusted, "
             f"concurrency-safe caches. {cache_instructions}"),
            default=os.path.join(get_pants_cachedir(), "named_caches"),
        )
        register(
            "--remote-execution",
            advanced=True,
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.remote_execution,
            help="Enables remote workers for increased parallelism. (Alpha)",
        )
        register(
            "--remote-store-server",
            advanced=True,
            type=list,
            default=[],
            help=
            "host:port of grpc server to use as remote execution file store.",
        )
        # TODO: Infer this from remote-store-connection-limit.
        register(
            "--remote-store-thread-count",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_thread_count,
            help=
            "Thread count to use for the pool that interacts with the remote file store.",
        )
        register(
            "--remote-execution-server",
            advanced=True,
            help=
            "host:port of grpc server to use as remote execution scheduler.",
        )
        register(
            "--remote-store-chunk-bytes",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_chunk_bytes,
            help=
            "Size in bytes of chunks transferred to/from the remote file store.",
        )
        register(
            "--remote-store-chunk-upload-timeout-seconds",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.
            remote_store_chunk_upload_timeout_seconds,
            help=
            "Timeout (in seconds) for uploads of individual chunks to the remote file store.",
        )
        register(
            "--remote-store-rpc-retries",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_rpc_retries,
            help=
            "Number of times to retry any RPC to the remote store before giving up.",
        )
        register(
            "--remote-store-connection-limit",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_connection_limit,
            help=
            "Number of remote stores to concurrently allow connections to.",
        )
        register(
            "--remote-execution-process-cache-namespace",
            advanced=True,
            help="The cache namespace for remote process execution. "
            "Bump this to invalidate every artifact's remote execution. "
            "This is the remote execution equivalent of the legacy cache-key-gen-version "
            "flag.",
        )
        register(
            "--remote-instance-name",
            advanced=True,
            help=
            "Name of the remote execution instance to use. Used for routing within "
            "--remote-execution-server and --remote-store-server.",
        )
        register(
            "--remote-ca-certs-path",
            advanced=True,
            help=
            "Path to a PEM file containing CA certificates used for verifying secure "
            "connections to --remote-execution-server and --remote-store-server. "
            "If not specified, TLS will not be used.",
        )
        register(
            "--remote-oauth-bearer-token-path",
            advanced=True,
            help=
            "Path to a file containing an oauth token to use for grpc connections to "
            "--remote-execution-server and --remote-store-server. If not specified, no "
            "authorization will be performed.",
        )
        register(
            "--remote-execution-extra-platform-properties",
            advanced=True,
            help="Platform properties to set on remote execution requests. "
            "Format: property=value. Multiple values should be specified as multiple "
            "occurrences of this flag. Pants itself may add additional platform properties.",
            type=list,
            default=[],
        )
        register(
            "--remote-execution-headers",
            advanced=True,
            help="Headers to set on remote execution requests. "
            "Format: header=value. Pants itself may add additional headers.",
            type=dict,
            default={},
        )
        register(
            "--remote-execution-enable-streaming",
            type=bool,
            default=True,
            advanced=True,
            help=
            "This option no longer does anything. (It used to enable the streaming remote execution client "
            "which is now the only remote execution client.)",
            removal_version="2.1.0.dev0",
            removal_hint="This option is no longer applicable.",
        )
        register(
            "--remote-execution-overall-deadline-secs",
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            remote_execution_overall_deadline_secs,
            advanced=True,
            help=
            "Overall timeout in seconds for each remote execution request from time of submission",
        )
        register(
            "--process-execution-local-parallelism",
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_local_parallelism,
            advanced=True,
            help="Number of concurrent processes that may be executed locally.",
        )
        register(
            "--process-execution-remote-parallelism",
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_remote_parallelism,
            advanced=True,
            help=
            "Number of concurrent processes that may be executed remotely.",
        )
        register(
            "--process-execution-cleanup-local-dirs",
            type=bool,
            default=True,
            advanced=True,
            help=
            "Whether or not to cleanup directories used for local process execution "
            "(primarily useful for e.g. debugging).",
        )
        register(
            "--process-execution-speculation-delay",
            type=float,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_speculation_delay,
            advanced=True,
            help=
            "Number of seconds to wait before speculating a second request for a slow process. "
            " see `--process-execution-speculation-strategy`",
        )
        register(
            "--process-execution-speculation-strategy",
            choices=["remote_first", "local_first", "none"],
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_speculation_strategy,
            help=
            "Speculate a second request for an underlying process if the first one does not complete within "
            "`--process-execution-speculation-delay` seconds.\n"
            "`local_first` (default): Try to run the process locally first, "
            "and fall back to remote execution if available.\n"
            "`remote_first`: Run the process on the remote execution backend if available, "
            "and fall back to the local host if remote calls take longer than the speculation timeout.\n"
            "`none`: Do not speculate about long running processes.",
            advanced=True,
        )
        register(
            "--process-execution-use-local-cache",
            type=bool,
            default=True,
            advanced=True,
            help=
            "Whether to keep process executions in a local cache persisted to disk.",
        )
        register(
            "--process-execution-local-enable-nailgun",
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_local_enable_nailgun,
            help=
            "Whether or not to use nailgun to run the requests that are marked as nailgunnable.",
            advanced=True,
        )
Exemplo n.º 15
0
class Config(object):
    """Encapsulates ini-style config file loading and access.

  Supports recursive variable substitution using standard python format strings. E.g.,
  %(var_name)s will be replaced with the value of var_name.
  """
    DEFAULT_SECTION = ConfigParser.DEFAULTSECT

    _defaults = {
        'homedir': os.path.expanduser('~'),
        'user': getpass.getuser(),
        'pants_bootstrapdir': get_pants_cachedir(),
        'pants_configdir': get_pants_configdir()
    }
    reset_default_bootstrap_option_values(_defaults)

    class ConfigError(Exception):
        pass

    @classmethod
    def reset_default_bootstrap_option_values(cls,
                                              values=None,
                                              buildroot=None):
        reset_default_bootstrap_option_values(cls._defaults, values, buildroot)

    _cached_config = None

    @classmethod
    def _munge_configpaths_arg(cls, configpaths):
        """Converts a string or iterable-of-strings argument into a tuple of strings.

    Result is hashable, so may be used as a cache key.
    """
        if is_text_or_binary(configpaths):
            return (configpaths, )
        return tuple(configpaths) if configpaths else (os.path.join(
            get_buildroot(), 'pants.ini'), )

    @classmethod
    def from_cache(cls):
        if not cls._cached_config:
            raise cls.ConfigError('No config cached.')
        return cls._cached_config

    @classmethod
    def cache(cls, config):
        cls._cached_config = config

    @classmethod
    def load(cls, configpaths=None):
        """Loads config from the given paths.

     By default this is the path to the pants.ini file in the current build root directory.
     Callers may specify a single path, or a list of the paths of configs to be chained, with
     later instances taking precedence over eariler ones.

     Any defaults supplied will act as if specified in the loaded config file's DEFAULT section.
     The 'buildroot', invoking 'user' and invoking user's 'homedir' are automatically defaulted.
    """
        configpaths = cls._munge_configpaths_arg(configpaths)
        single_file_configs = []
        for configpath in configpaths:
            parser = cls.create_parser()
            with open(configpath, 'r') as ini:
                parser.readfp(ini)
            single_file_configs.append(SingleFileConfig(configpath, parser))
        return ChainedConfig(single_file_configs)

    @classmethod
    def create_parser(cls):
        """Creates a config parser that supports %([key-name])s value substitution.

    Any defaults supplied will act as if specified in the loaded config file's DEFAULT section and
    be available for substitutions, along with all the standard defaults defined above.
    """
        return ConfigParser.SafeConfigParser(cls._defaults)

    def getbool(self, section, option, default=None):
        """Equivalent to calling get with expected type bool."""
        return self.get(section, option, type=bool, default=default)

    def getint(self, section, option, default=None):
        """Equivalent to calling get with expected type int."""
        return self.get(section, option, type=int, default=default)

    def getfloat(self, section, option, default=None):
        """Equivalent to calling get with expected type float."""
        return self.get(section, option, type=float, default=default)

    def getlist(self, section, option, default=None):
        """Equivalent to calling get with expected type list."""
        return self.get(section, option, type=list, default=default)

    def getdict(self, section, option, default=None):
        """Equivalent to calling get with expected type dict."""
        return self.get(section, option, type=dict, default=default)

    def getdefault(self, option, type=str, default=None):
        """
      Retrieves option from the DEFAULT section if it exists and attempts to parse it as type.
      If there is no definition found, the default value supplied is returned.
    """
        return self.get(Config.DEFAULT_SECTION, option, type, default=default)

    def get(self, section, option, type=str, default=None):
        """
      Retrieves option from the specified section if it exists and attempts to parse it as type.
      If the specified section is missing a definition for the option, the value is looked up in the
      DEFAULT section.  If there is still no definition found, the default value supplied is
      returned.
    """
        return self._getinstance(section, option, type, default=default)

    def get_required(self, section, option, type=str):
        """Retrieves option from the specified section and attempts to parse it as type.
    If the specified section is missing a definition for the option, the value is
    looked up in the DEFAULT section. If there is still no definition found,
    a `ConfigError` is raised.

    :param string section: Section to lookup the option in, before looking in DEFAULT.
    :param string option: Option to retrieve.
    :param type: Type to retrieve the option as.
    :returns: The option as the specified type.
    :raises: :class:`pants.base.config.Config.ConfigError` if option is not found.
    """
        val = self.get(section, option, type=type)
        # Empty str catches blank options. If blank entries are ok, use get(..., default='') instead.
        if val is None or val == '':
            raise Config.ConfigError('Required option %s.%s is not defined.' %
                                     (section, option))
        return val

    @staticmethod
    def format_raw_value(raw_value):
        lines = raw_value.splitlines()
        for line_number in range(0, len(lines)):
            lines[line_number] = "{line_number:{width}}: {line}".format(
                line_number=line_number + 1,
                line=lines[line_number],
                width=len(str(len(lines))))
        return '\n'.join(lines)

    def _getinstance(self, section, option, type, default=None):
        if not self.has_option(section, option):
            return default
        raw_value = self.get_value(section, option)
        if issubclass(type, str):
            return raw_value

        try:
            parsed_value = eval(raw_value, {}, {})
        except SyntaxError as e:
            raise Config.ConfigError(
                'No valid {type_name} for {section}.{option}:\n{value}\n{error}'
                .format(type_name=type.__name__,
                        section=section,
                        option=option,
                        value=Config.format_raw_value(raw_value),
                        error=e))
        if not isinstance(parsed_value, type):
            raise Config.ConfigError(
                'No valid {type_name} for {section}.{option}:\n{value}'.format(
                    type_name=type.__name__,
                    section=section,
                    option=option,
                    value=Config.format_raw_value(raw_value)))

        return parsed_value

    # Subclasses must implement.

    def sources(self):
        """Return the sources of this config as a list of filenames."""
        raise NotImplementedError()

    def has_section(self, section):
        """Return whether this config has the section."""
        raise NotImplementedError()

    def has_option(self, section, option):
        """Return whether this config specified a value the option."""
        raise NotImplementedError()

    def get_value(self, section, option):
        """Return the value of the option in this config, as a string, or None if no value specified."""
        raise NotImplementedError()
Exemplo n.º 16
0
  def register_bootstrap_options(cls, register):
    """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
    buildroot = get_buildroot()
    default_distdir_name = 'dist'
    default_distdir = os.path.join(buildroot, default_distdir_name)
    default_rel_distdir = '/{}/'.format(default_distdir_name)

    register('-l', '--level', choices=['trace', 'debug', 'info', 'warn'], default='info',
             recursive=True, help='Set the logging level.')
    register('-q', '--quiet', type=bool, recursive=True, daemon=False,
             help='Squelches most console output. NOTE: Some tasks default to behaving quietly: '
                  'inverting this option supports making them noisier than they would be otherwise.')
    register('--log-show-rust-3rdparty', type=bool, default=False, advanced=True,
             help='Whether to show/hide logging done by 3rdparty rust crates used by the pants '
                  'engine.')

    # Not really needed in bootstrap options, but putting it here means it displays right
    # after -l and -q in help output, which is conveniently contextual.
    register('--colors', type=bool, default=sys.stdout.isatty(), recursive=True, daemon=False,
             help='Set whether log messages are displayed in color.')
    # TODO(#7203): make a regexp option type!
    register('--ignore-pants-warnings', type=list, member_type=str, default=[],
             help='Regexps matching warning strings to ignore, e.g. '
                  '["DEPRECATED: scope some_scope will be removed"]. The regexps will be matched '
                  'from the start of the warning string, and will always be case-insensitive. '
                  'See the `warnings` module documentation for more background on these are used.')
    register('--option-name-check-distance', advanced=True, type=int, default=2,
             help='The maximum Levenshtein distance to use when offering suggestions for invalid '
                  'option names.')

    register('--pants-version', advanced=True, default=pants_version(),
             help='Use this pants version. Note Pants code only uses this to verify that you are '
                  'using the requested version, as Pants cannot dynamically change the version it '
                  'is using once the program is already running. This option is useful to set in '
                  'your pants.ini, however, and then you can grep the value to select which '
                  'version to use for setup scripts (e.g. `./pants`), runner scripts, IDE plugins, '
                  'etc. For example, the setup script we distribute at https://www.pantsbuild.org/install.html#recommended-installation '
                  'uses this value to determine which Python version to run with. You may find the '
                  'version of the pants instance you are running using -v, -V, or --version.')

    register('--pants-runtime-python-version', advanced=True,
             removal_version='1.19.0.dev0',
             deprecation_start_version='1.17.0.dev0',
             removal_hint=dedent("""
                  This option was only used to help with Pants' migration to run on Python 3. \
                  Pants will now correctly default to whichever Python versions are supported for \
                  the current `pants_version` you are using. Please make sure you are using the \
                  most up-to-date version of the `./pants` script with:

                    curl -L -O https://pantsbuild.github.io/setup/pants

                  and then unset this option."""),
             help='Use this Python version to run Pants. The option expects the major and minor '
                  'version, e.g. 2.7 or 3.6. Note Pants code only uses this to verify that you are '
                  'using the requested interpreter, as Pants cannot dynamically change the '
                  'interpreter it is using once the program is already running. This option is '
                  'useful to set in your pants.ini, however, and then you can grep the value to '
                  'select which interpreter to use for setup scripts (e.g. `./pants`), runner '
                  'scripts, IDE plugins, etc. For example, the setup script we distribute at '
                  'https://www.pantsbuild.org/install.html#recommended-installation uses this '
                  'value to determine which Python version to run with. Also note this does not mean '
                  'your own code must use this Python version. See '
                  'https://www.pantsbuild.org/python_readme.html#configure-the-python-version '
                  'for how to configure your code\'s compatibility.')

    register('--plugins', advanced=True, type=list, help='Load these plugins.')
    register('--plugin-cache-dir', advanced=True,
             default=os.path.join(get_pants_cachedir(), 'plugins'),
             help='Cache resolved plugin requirements here.')

    register('--backend-packages', advanced=True, type=list,
             default=['pants.backend.graph_info',
                      'pants.backend.python',
                      'pants.backend.jvm',
                      'pants.backend.native',
                      # TODO: Move into the graph_info backend.
                      'pants.rules.core',
                      'pants.backend.codegen.antlr.java',
                      'pants.backend.codegen.antlr.python',
                      'pants.backend.codegen.jaxb',
                      'pants.backend.codegen.protobuf.java',
                      'pants.backend.codegen.ragel.java',
                      'pants.backend.codegen.thrift.java',
                      'pants.backend.codegen.thrift.python',
                      'pants.backend.codegen.grpcio.python',
                      'pants.backend.codegen.wire.java',
                      'pants.backend.project_info'],
             help='Load backends from these packages that are already on the path. '
                  'Add contrib and custom backends to this list.')

    register('--pants-bootstrapdir', advanced=True, metavar='<dir>', default=get_pants_cachedir(),
             help='Use this dir for global cache.')
    register('--pants-configdir', advanced=True, metavar='<dir>', default=get_pants_configdir(),
             help='Use this dir for global config files.')
    register('--pants-workdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, '.pants.d'),
             help='Write intermediate output files to this dir.')
    register('--pants-supportdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'build-support'),
             help='Use support files from this dir.')
    register('--pants-distdir', advanced=True, metavar='<dir>',
             default=default_distdir,
             help='Write end-product artifacts to this dir. If you modify this path, you '
                  'should also update --build-ignore and --pants-ignore to include the '
                  'custom dist dir path as well.')
    register('--pants-subprocessdir', advanced=True, default=os.path.join(buildroot, '.pids'),
             help='The directory to use for tracking subprocess metadata, if any. This should '
                  'live outside of the dir used by `--pants-workdir` to allow for tracking '
                  'subprocesses that outlive the workdir data (e.g. `./pants server`).')
    register('--pants-config-files', advanced=True, type=list, daemon=False,
             default=[get_default_pants_config_file()], help='Paths to Pants config files.')
    # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
    # to set extra config file locations in an initial bootstrap config file.
    register('--pantsrc', advanced=True, type=bool, default=True,
             help='Use pantsrc files.')
    register('--pantsrc-files', advanced=True, type=list, metavar='<path>', daemon=False,
             default=['/etc/pantsrc', '~/.pants.rc'],
             help='Override config with values from these files. '
                  'Later files override earlier ones.')
    register('--pythonpath', advanced=True, type=list,
             help='Add these directories to PYTHONPATH to search for plugins.')
    register('--target-spec-file', type=list, dest='target_spec_files', daemon=False,
             help='Read additional specs from this file, one per line')
    register('--verify-config', type=bool, default=True, daemon=False,
             advanced=True,
             help='Verify that all config file values correspond to known options.')

    register('--build-ignore', advanced=True, type=list,
             default=['.*/', default_rel_distdir, 'bower_components/',
                      'node_modules/', '*.egg-info/'],
             help='Paths to ignore when identifying BUILD files. '
                  'This does not affect any other filesystem operations. '
                  'Patterns use the gitignore pattern syntax (https://git-scm.com/docs/gitignore).')
    register('--pants-ignore', advanced=True, type=list,
             default=['.*/', default_rel_distdir],
             help='Paths to ignore for all filesystem operations performed by pants '
                  '(e.g. BUILD file scanning, glob matching, etc). '
                  'Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore).')
    register('--glob-expansion-failure', advanced=True,
             default=GlobMatchErrorBehavior.warn, type=GlobMatchErrorBehavior,
             help="Raise an exception if any targets declaring source files "
                  "fail to match any glob provided in the 'sources' argument.")

    # TODO(#7203): make a regexp option type!
    register('--exclude-target-regexp', advanced=True, type=list, default=[], daemon=False,
             metavar='<regexp>', help='Exclude target roots that match these regexes.')
    register('--subproject-roots', type=list, advanced=True, default=[],
             help='Paths that correspond with build roots for any subproject that this '
                  'project depends on.')
    register('--owner-of', type=list, member_type=file_option, default=[], daemon=False, metavar='<path>',
             help='Select the targets that own these files. '
                  'This is the third target calculation strategy along with the --changed-* '
                  'options and specifying the targets directly. These three types of target '
                  'selection are mutually exclusive.')

    # These logging options are registered in the bootstrap phase so that plugins can log during
    # registration and not so that their values can be interpolated in configs.
    register('-d', '--logdir', advanced=True, metavar='<dir>',
             help='Write logs to files under this directory.')

    # This facilitates bootstrap-time configuration of pantsd usage such that we can
    # determine whether or not to use the Pailgun client to invoke a given pants run
    # without resorting to heavier options parsing.
    register('--enable-pantsd', advanced=True, type=bool, default=False,
             help='Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)')

    # Shutdown pantsd after the current run.
    # This needs to be accessed at the same time as enable_pantsd,
    # so we register it at bootstrap time.
    register('--shutdown-pantsd-after-run', advanced=True, type=bool, default=False,
      help='Create a new pantsd server, and use it, and shut it down immediately after. '
           'If pantsd is already running, it will shut it down and spawn a new instance (Beta)')

    # These facilitate configuring the native engine.
    register('--native-engine-visualize-to', advanced=True, default=None, type=dir_option, daemon=False,
             help='A directory to write execution and rule graphs to as `dot` files. The contents '
                  'of the directory will be overwritten if any filenames collide.')
    register('--print-exception-stacktrace', advanced=True, type=bool,
             help='Print to console the full exception stack trace if encountered.')

    # BinaryUtil options.
    register('--binaries-baseurls', type=list, advanced=True,
             default=['https://binaries.pantsbuild.org'],
             help='List of URLs from which binary tools are downloaded. URLs are '
                  'searched in order until the requested path is found.')
    register('--binaries-fetch-timeout-secs', type=int, default=30, advanced=True, daemon=False,
             help='Timeout in seconds for URL reads when fetching binary tools from the '
                  'repos specified by --baseurls.')
    register('--binaries-path-by-id', type=dict, advanced=True,
             help=("Maps output of uname for a machine to a binary search path: "
                   "(sysname, id) -> (os, arch), e.g. {('darwin', '15'): ('mac', '10.11'), "
                   "('linux', 'arm32'): ('linux', 'arm32')}."))
    register('--allow-external-binary-tool-downloads', type=bool, default=True, advanced=True,
             help="If False, require BinaryTool subclasses to download their contents from urls "
                  "generated from --binaries-baseurls, even if the tool has an external url "
                  "generator. This can be necessary if using Pants in an environment which cannot "
                  "contact the wider Internet.")

    # Pants Daemon options.
    register('--pantsd-pailgun-host', advanced=True, default='127.0.0.1',
             help='The host to bind the pants nailgun server to.')
    register('--pantsd-pailgun-port', advanced=True, type=int, default=0,
             help='The port to bind the pants nailgun server to. Defaults to a random port.')
    # TODO(#7514): Make this default to 1.0 seconds if stdin is a tty!
    register('--pantsd-pailgun-quit-timeout', advanced=True, type=float, default=5.0,
             help='The length of time (in seconds) to wait for further output after sending a '
                  'signal to the remote pantsd process before killing it.')
    register('--pantsd-log-dir', advanced=True, default=None,
             help='The directory to log pantsd output to.')
    register('--pantsd-invalidation-globs', advanced=True, type=list, default=[],
             help='Filesystem events matching any of these globs will trigger a daemon restart.')

    # Watchman options.
    register('--watchman-version', advanced=True, default='4.9.0-pants1', help='Watchman version.')
    register('--watchman-supportdir', advanced=True, default='bin/watchman',
             help='Find watchman binaries under this dir. Used as part of the path to lookup '
                  'the binary with --binaries-baseurls and --pants-bootstrapdir.')
    register('--watchman-startup-timeout', type=float, advanced=True, default=30.0,
             help='The watchman socket timeout (in seconds) for the initial `watch-project` command. '
                  'This may need to be set higher for larger repos due to watchman startup cost.')
    register('--watchman-socket-timeout', type=float, advanced=True, default=0.1,
             help='The watchman client socket timeout in seconds. Setting this to too high a '
                  'value can negatively impact the latency of runs forked by pantsd.')
    register('--watchman-socket-path', type=str, advanced=True, default=None,
             help='The path to the watchman UNIX socket. This can be overridden if the default '
                  'absolute path length exceeds the maximum allowed by the OS.')

    # This option changes the parser behavior in a fundamental way (which currently invalidates
    # all caches), and needs to be parsed out early, so we make it a bootstrap option.
    register('--build-file-imports', choices=['allow', 'warn', 'error'], default='warn',
             advanced=True,
             help='Whether to allow import statements in BUILD files')

    register('--local-store-dir', advanced=True,
             help="Directory to use for engine's local file store.",
             # This default is also hard-coded into the engine's rust code in
             # fs::Store::default_path
             default=os.path.expanduser('~/.cache/pants/lmdb_store'))
    register('--remote-store-server', advanced=True, type=list, default=[],
             help='host:port of grpc server to use as remote execution file store.')
    register('--remote-store-thread-count', type=int, advanced=True,
             default=DEFAULT_EXECUTION_OPTIONS.remote_store_thread_count,
             help='Thread count to use for the pool that interacts with the remote file store.')
    register('--remote-execution-server', advanced=True,
             help='host:port of grpc server to use as remote execution scheduler.')
    register('--remote-store-chunk-bytes', type=int, advanced=True,
             default=DEFAULT_EXECUTION_OPTIONS.remote_store_chunk_bytes,
             help='Size in bytes of chunks transferred to/from the remote file store.')
    register('--remote-store-chunk-upload-timeout-seconds', type=int, advanced=True,
             default=DEFAULT_EXECUTION_OPTIONS.remote_store_chunk_upload_timeout_seconds,
             help='Timeout (in seconds) for uploads of individual chunks to the remote file store.')
    register('--remote-store-rpc-retries', type=int, advanced=True,
             default=DEFAULT_EXECUTION_OPTIONS.remote_store_rpc_retries,
             help='Number of times to retry any RPC to the remote store before giving up.')
    register('--remote-execution-process-cache-namespace', advanced=True,
             help="The cache namespace for remote process execution. "
                  "Bump this to invalidate every artifact's remote execution. "
                  "This is the remote execution equivalent of the legacy cache-key-gen-version "
                  "flag.")
    register('--remote-instance-name', advanced=True,
             help='Name of the remote execution instance to use. Used for routing within '
                  '--remote-execution-server and --remote-store-server.')
    register('--remote-ca-certs-path', advanced=True,
             help='Path to a PEM file containing CA certificates used for verifying secure '
                  'connections to --remote-execution-server and --remote-store-server. '
                  'If not specified, TLS will not be used.')
    register('--remote-oauth-bearer-token-path', advanced=True,
             help='Path to a file containing an oauth token to use for grpc connections to '
                  '--remote-execution-server and --remote-store-server. If not specified, no '
                  'authorization will be performed.')
    register('--remote-execution-extra-platform-properties', advanced=True,
             help='Platform properties to set on remote execution requests. '
                  'Format: property=value. Multiple values should be specified as multiple '
                  'occurrences of this flag. Pants itself may add additional platform properties.',
                   type=list, default=[])

    # This should eventually deprecate the RunTracker worker count, which is used for legacy cache
    # lookups via CacheSetup in TaskBase.
    register('--process-execution-parallelism', type=int, default=multiprocessing.cpu_count(),
             advanced=True,
             help='Number of concurrent processes that may be executed either locally and remotely.')
    register('--process-execution-cleanup-local-dirs', type=bool, default=True, advanced=True,
             help='Whether or not to cleanup directories used for local process execution '
                  '(primarily useful for e.g. debugging).')
Exemplo n.º 17
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

        "Bootstrap options" are the set of options necessary to create a Scheduler. If an option is
        not consumed during creation of a Scheduler, it should be in `register_options` instead.

        Bootstrap option values can be interpolated into the config file, and can be referenced
        programmatically in registration code, e.g., as register.bootstrap.pants_workdir.

        Note that regular code can also access these options as normal global-scope options. Their
        status as "bootstrap options" is only pertinent during option registration.
        """
        buildroot = get_buildroot()
        default_distdir_name = "dist"
        default_rel_distdir = f"/{default_distdir_name}/"

        register(
            "--backend-packages",
            advanced=True,
            type=list,
            default=[],
            help=
            ("Register functionality from these backends.\n\nThe backend packages must be "
             "present on the PYTHONPATH, typically because they are in the Pants core dist, in a "
             "plugin dist, or available as sources in the repo."),
        )
        register(
            "--plugins",
            advanced=True,
            type=list,
            help=
            ("Allow backends to be loaded from these plugins (usually released through PyPI). "
             "The default backends for each plugin will be loaded automatically. Other backends "
             "in a plugin can be loaded by listing them in `backend_packages` in the "
             "`[GLOBAL]` scope."),
        )
        register(
            "--plugins-force-resolve",
            advanced=True,
            type=bool,
            default=False,
            help="Re-resolve plugins, even if previously resolved.",
        )
        register(
            "--plugin-cache-dir",
            advanced=True,
            default=os.path.join(get_pants_cachedir(), "plugins"),
            help="Cache resolved plugin requirements here.",
        )

        register("-l",
                 "--level",
                 type=LogLevel,
                 default=LogLevel.INFO,
                 help="Set the logging level.")
        register(
            "--show-log-target",
            type=bool,
            default=False,
            advanced=True,
            help=
            "Display the target where a log message originates in that log message's output. "
            "This can be helpful when paired with --log-levels-by-target.",
        )

        register(
            "--log-levels-by-target",
            type=dict,
            default={},
            advanced=True,
            help=
            "Set a more specific logging level for one or more logging targets. The names of "
            "logging targets are specified in log strings when the --show-log-target option is set. "
            "The logging levels are one of: "
            '"error", "warn", "info", "debug", "trace". '
            "All logging targets not specified here use the global log level set with --level. For example, "
            'you can set `--log-levels-by-target=\'{"workunit_store": "info", "pants.engine.rules": "warn"}\'`.',
        )

        register(
            "--log-show-rust-3rdparty",
            type=bool,
            default=False,
            advanced=True,
            help=
            "Whether to show/hide logging done by 3rdparty Rust crates used by the Pants "
            "engine.",
        )

        register(
            "--colors",
            type=bool,
            default=sys.stdout.isatty(),
            help=
            ("Whether Pants should use colors in output or not. This may also impact whether "
             "some tools Pants run use color."),
        )

        # TODO(#7203): make a regexp option type!
        register(
            "--ignore-pants-warnings",
            type=list,
            member_type=str,
            default=[],
            advanced=True,
            help="Regexps matching warning strings to ignore, e.g. "
            '["DEPRECATED: the option `--my-opt` will be removed"]. The regex patterns will be '
            "matched from the start of the warning string, and are case-insensitive.",
        )

        register(
            "--pants-version",
            advanced=True,
            default=pants_version(),
            daemon=True,
            help=
            "Use this Pants version. Note that Pants only uses this to verify that you are "
            "using the requested version, as Pants cannot dynamically change the version it "
            "is using once the program is already running.\n\nIf you use the `./pants` script from "
            "https://www.pantsbuild.org/docs/installation, however, changing the value in your "
            "`pants.toml` will cause the new version to be installed and run automatically.\n\n"
            "Run `./pants --version` to check what is being used.",
        )
        register(
            "--pants-bin-name",
            advanced=True,
            default="./pants",
            help="The name of the script or binary used to invoke Pants. "
            "Useful when printing help messages.",
        )

        register(
            "--pants-bootstrapdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_cachedir(),
            help="Use this dir for global cache.",
        )
        register(
            "--pants-configdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_configdir(),
            help="Use this dir for global config files.",
        )
        register(
            "--pants-workdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, ".pants.d"),
            daemon=True,
            help="Write intermediate logs and output files to this dir.",
        )
        register(
            "--pants-physical-workdir-base",
            advanced=True,
            metavar="<dir>",
            default=None,
            daemon=True,
            help=
            "When set, a base directory in which to store `--pants-workdir` contents. "
            "If this option is a set, the workdir will be created as symlink into a "
            "per-workspace subdirectory.",
        )
        register(
            "--pants-supportdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "build-support"),
            help="Use support files from this dir.",
        )
        register(
            "--pants-distdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "dist"),
            help="Write end-product artifacts to this dir.",
        )
        # TODO: Change the default to false in 2.1, deprecate the option in 2.2 and remove in 2.3.
        register(
            "--pants-distdir-legacy-paths",
            type=bool,
            advanced=True,
            default=True,
            help=
            "Whether to write binaries to the pre-2.0 paths under distdir. These legacy "
            "paths are not qualified by target address, so may be ambiguous.  This option "
            "is a temporary mechanism for easing transition to 2.0.  We recommemd switching "
            "to the new, unambiguous paths ASAP, by setting this option to true.",
        )
        register(
            "--pants-subprocessdir",
            advanced=True,
            default=os.path.join(buildroot, ".pids"),
            daemon=True,
            help=
            "The directory to use for tracking subprocess metadata, if any. This should "
            "live outside of the dir used by `pants_workdir` to allow for tracking "
            "subprocesses that outlive the workdir data.",
        )
        register(
            "--pants-config-files",
            advanced=True,
            type=list,
            # NB: We don't fingerprint the list of config files, because the content of the config
            # files independently affects fingerprints.
            fingerprint=False,
            default=[get_default_pants_config_file()],
            help=
            ("Paths to Pants config files. This may only be set through the environment variable "
             "`PANTS_CONFIG_FILES` and the command line argument `--pants-config-files`; it will "
             "be ignored if in a config file like `pants.toml`."),
        )
        register(
            "--pantsrc",
            advanced=True,
            type=bool,
            default=True,
            # NB: See `--pants-config-files`.
            fingerprint=False,
            help=
            ("Use pantsrc files located at the paths specified in the global option "
             "`pantsrc_files`."),
        )
        register(
            "--pantsrc-files",
            advanced=True,
            type=list,
            metavar="<path>",
            # NB: See `--pants-config-files`.
            fingerprint=False,
            default=["/etc/pantsrc", "~/.pants.rc"],
            help=
            ("Override config with values from these files, using syntax matching that of "
             "`--pants-config-files`."),
        )
        register(
            "--pythonpath",
            advanced=True,
            type=list,
            help=
            ("Add these directories to PYTHONPATH to search for plugins. This does not impact "
             "the PYTHONPATH used by Pants when running your Python code."),
        )
        register(
            "--spec-files",
            type=list,
            # NB: See `--pants-config-files`.
            fingerprint=False,
            help=
            ("Read additional specs (target addresses, files, and/or globs), one per line,"
             "from these files."),
        )
        register(
            "--spec-file",
            type=list,
            removal_version="2.1.0.dev0",
            removal_hint="Use --spec-files",
            fingerprint=False,
            help=
            "Read additional specs from this file (e.g. target addresses or file names). "
            "Each spec should be one per line.",
        )
        register(
            "--verify-config",
            type=bool,
            default=True,
            advanced=True,
            help=
            "Verify that all config file values correspond to known options.",
        )

        register(
            "--pants-ignore",
            advanced=True,
            type=list,
            member_type=str,
            default=[".*/", default_rel_distdir],
            help=
            "Paths to ignore for all filesystem operations performed by pants "
            "(e.g. BUILD file scanning, glob matching, etc). "
            "Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore). "
            "The `pants_distdir` and `pants_workdir` locations are automatically ignored. "
            "`pants_ignore` can be used in tandem with `pants_ignore_use_gitignore`; any rules "
            "specified here are applied after rules specified in a .gitignore file.",
        )
        register(
            "--pants-ignore-use-gitignore",
            advanced=True,
            type=bool,
            default=True,
            help=
            "Make use of a root .gitignore file when determining whether to ignore filesystem "
            "operations performed by Pants. If used together with `--pants-ignore`, any exclude/include "
            "patterns specified there apply after .gitignore rules.",
        )

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register(
            "-d",
            "--logdir",
            advanced=True,
            metavar="<dir>",
            daemon=True,
            help="Write logs to files under this directory.",
        )

        register(
            "--pantsd",
            advanced=True,
            type=bool,
            default=True,
            daemon=True,
            help=
            ("Enables use of the Pants daemon (pantsd). pantsd can significantly improve "
             "runtime performance by lowering per-run startup cost, and by memoizing filesystem "
             "operations and rule execution."),
        )

        # Whether or not to make necessary arrangements to have concurrent runs in pants.
        # In practice, this means that if this is set, a run will not even try to use pantsd.
        # NB: Eventually, we would like to deprecate this flag in favor of making pantsd runs parallelizable.
        register(
            "--concurrent",
            advanced=True,
            type=bool,
            default=False,
            help=
            "Enable concurrent runs of Pants. Without this enabled, Pants will "
            "start up all concurrent invocations (e.g. in other terminals) without pantsd. "
            "Enabling this option requires parallel Pants invocations to block on the first",
        )

        # NB: We really don't want this option to invalidate the daemon, because different clients might have
        # different needs. For instance, an IDE might have a very long timeout because it only wants to refresh
        # a project in the background, while a user might want a shorter timeout for interactivity.
        register(
            "--pantsd-timeout-when-multiple-invocations",
            advanced=True,
            type=float,
            default=60.0,
            help=
            "The maximum amount of time to wait for the invocation to start until "
            "raising a timeout exception. "
            "Because pantsd currently does not support parallel runs, "
            "any prior running Pants command must be finished for the current one to start. "
            "To never timeout, use the value -1.",
        )
        register(
            "--pantsd-max-memory-usage",
            advanced=True,
            type=int,
            default=2**30,
            help=
            ("The maximum memory usage of a pantsd process (in bytes). There is at most one "
             "pantsd process per workspace."),
        )

        # These facilitate configuring the native engine.
        register(
            "--print-stacktrace",
            advanced=True,
            type=bool,
            default=False,
            help="Print the full exception stack trace for any errors.",
        )
        register(
            "--print-exception-stacktrace",
            advanced=True,
            type=bool,
            default=False,
            help=
            "Print to console the full exception stack trace if encountered.",
            removal_version="2.1.0.dev0",
            removal_hint=
            "Use `--print-stacktrace` instead of `--print-exception-stacktrace`.",
        )
        register(
            "--native-engine-visualize-to",
            advanced=True,
            default=None,
            type=dir_option,
            help=
            "A directory to write execution and rule graphs to as `dot` files. The contents "
            "of the directory will be overwritten if any filenames collide.",
        )

        # Pants Daemon options.
        register(
            "--pantsd-pailgun-port",
            advanced=True,
            type=int,
            default=0,
            daemon=True,
            help=
            "The port to bind the Pants nailgun server to. Defaults to a random port.",
        )
        # TODO(#7514): Make this default to 1.0 seconds if stdin is a tty!
        register(
            "--pantsd-pailgun-quit-timeout",
            advanced=True,
            type=float,
            default=5.0,
            help=
            "The length of time (in seconds) to wait for further output after sending a "
            "signal to the remote pantsd process before killing it.",
        )
        register(
            "--pantsd-log-dir",
            advanced=True,
            default=None,
            daemon=True,
            help="The directory to log pantsd output to.",
        )
        register(
            "--pantsd-invalidation-globs",
            advanced=True,
            type=list,
            default=[],
            daemon=True,
            help=
            "Filesystem events matching any of these globs will trigger a daemon restart. "
            "Pants's own code, plugins, and `--pants-config-files` are inherently invalidated.",
        )

        cache_instructions = (
            "The path may be absolute or relative. If the directory is within the build root, be "
            "sure to include it in `--pants-ignore`.")
        register(
            "--local-store-dir",
            advanced=True,
            help=
            (f"Directory to use for the local file store, which stores the results of "
             f"subprocesses run by Pants. {cache_instructions}"),
            # This default is also hard-coded into the engine's rust code in
            # fs::Store::default_path so that tools using a Store outside of pants
            # are likely to be able to use the same storage location.
            default=os.path.join(get_pants_cachedir(), "lmdb_store"),
        )
        register(
            "--local-execution-root-dir",
            advanced=True,
            help=
            f"Directory to use for local process execution sandboxing. {cache_instructions}",
            default=tempfile.gettempdir(),
        )
        register(
            "--named-caches-dir",
            advanced=True,
            help=
            ("Directory to use for named global caches for tools and processes with trusted, "
             f"concurrency-safe caches. {cache_instructions}"),
            default=os.path.join(get_pants_cachedir(), "named_caches"),
        )

        register(
            "--ca-certs-path",
            advanced=True,
            type=str,
            default=None,
            help=
            "Path to a file containing PEM-format CA certificates used for verifying secure "
            "connections when downloading files required by a build.",
        )

        register(
            "--process-execution-local-parallelism",
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_local_parallelism,
            advanced=True,
            help="Number of concurrent processes that may be executed locally.",
        )
        register(
            "--process-execution-remote-parallelism",
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_remote_parallelism,
            advanced=True,
            help=
            "Number of concurrent processes that may be executed remotely.",
        )
        register(
            "--process-execution-cleanup-local-dirs",
            type=bool,
            default=True,
            advanced=True,
            help=
            "Whether or not to cleanup directories used for local process execution "
            "(primarily useful for e.g. debugging).",
        )
        register(
            "--process-execution-speculation-delay",
            type=float,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_speculation_delay,
            advanced=True,
            help=
            "Number of seconds to wait before speculating a second request for a slow process. "
            " see `--process-execution-speculation-strategy`",
        )
        register(
            "--process-execution-speculation-strategy",
            choices=["remote_first", "local_first", "none"],
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_speculation_strategy,
            help=
            "Speculate a second request for an underlying process if the first one does not complete within "
            "`--process-execution-speculation-delay` seconds.\n"
            "`local_first` (default): Try to run the process locally first, "
            "and fall back to remote execution if available.\n"
            "`remote_first`: Run the process on the remote execution backend if available, "
            "and fall back to the local host if remote calls take longer than the speculation timeout.\n"
            "`none`: Do not speculate about long running processes.",
            advanced=True,
        )
        register(
            "--process-execution-use-local-cache",
            type=bool,
            default=True,
            advanced=True,
            help=
            "Whether to keep process executions in a local cache persisted to disk.",
        )
        register(
            "--process-execution-local-enable-nailgun",
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_local_enable_nailgun,
            help=
            "Whether or not to use nailgun to run the requests that are marked as nailgunnable.",
            advanced=True,
        )

        register(
            "--remote-execution",
            advanced=True,
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.remote_execution,
            help="Enables remote workers for increased parallelism. (Alpha)",
        )
        register(
            "--remote-cache-read",
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.remote_cache_read,
            advanced=True,
            help="Whether to enable reading from a remote cache",
        )
        register(
            "--remote-cache-write",
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.remote_cache_write,
            advanced=True,
            help="Whether to enable writing results to a remote cache",
        )

        register(
            "--remote-store-server",
            advanced=True,
            type=list,
            default=[],
            help=
            "host:port of grpc server to use as remote execution file store.",
        )
        # TODO: Infer this from remote-store-connection-limit.
        register(
            "--remote-store-thread-count",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_thread_count,
            help=
            "Thread count to use for the pool that interacts with the remote file store.",
        )
        register(
            "--remote-execution-server",
            advanced=True,
            help=
            "host:port of grpc server to use as remote execution scheduler.",
        )
        register(
            "--remote-store-chunk-bytes",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_chunk_bytes,
            help=
            "Size in bytes of chunks transferred to/from the remote file store.",
        )
        register(
            "--remote-store-chunk-upload-timeout-seconds",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.
            remote_store_chunk_upload_timeout_seconds,
            help=
            "Timeout (in seconds) for uploads of individual chunks to the remote file store.",
        )
        register(
            "--remote-store-rpc-retries",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_rpc_retries,
            help=
            "Number of times to retry any RPC to the remote store before giving up.",
        )
        register(
            "--remote-store-connection-limit",
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_connection_limit,
            help=
            "Number of remote stores to concurrently allow connections to.",
        )
        register(
            "--remote-execution-process-cache-namespace",
            advanced=True,
            help="The cache namespace for remote process execution. "
            "Bump this to invalidate every artifact's remote execution. "
            "This is the remote execution equivalent of the legacy cache-key-gen-version "
            "flag.",
        )
        register(
            "--remote-instance-name",
            advanced=True,
            help=
            "Name of the remote execution instance to use. Used for routing within "
            "--remote-execution-server and --remote-store-server.",
        )
        register(
            "--remote-ca-certs-path",
            advanced=True,
            help=
            "Path to a PEM file containing CA certificates used for verifying secure "
            "connections to --remote-execution-server and --remote-store-server. "
            "If not specified, TLS will not be used.",
        )
        register(
            "--remote-oauth-bearer-token-path",
            advanced=True,
            help=
            "Path to a file containing an oauth token to use for grpc connections to "
            "--remote-execution-server and --remote-store-server. If not specified, no "
            "authorization will be performed.",
        )
        register(
            "--remote-execution-extra-platform-properties",
            advanced=True,
            help="Platform properties to set on remote execution requests. "
            "Format: property=value. Multiple values should be specified as multiple "
            "occurrences of this flag. Pants itself may add additional platform properties.",
            type=list,
            default=[],
        )
        register(
            "--remote-execution-headers",
            advanced=True,
            help="Headers to set on remote execution requests. "
            "Format: header=value. Pants itself may add additional headers.",
            type=dict,
            default={},
        )
        register(
            "--remote-execution-overall-deadline-secs",
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            remote_execution_overall_deadline_secs,
            advanced=True,
            help=
            "Overall timeout in seconds for each remote execution request from time of submission",
        )
Exemplo n.º 18
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
        buildroot = get_buildroot()
        default_distdir_name = 'dist'
        default_distdir = os.path.join(buildroot, default_distdir_name)
        default_rel_distdir = '/{}/'.format(default_distdir_name)

        register('-l',
                 '--level',
                 choices=['trace', 'debug', 'info', 'warn'],
                 default='info',
                 recursive=True,
                 help='Set the logging level.')
        register(
            '-q',
            '--quiet',
            type=bool,
            recursive=True,
            daemon=False,
            help=
            'Squelches most console output. NOTE: Some tasks default to behaving quietly: '
            'inverting this option supports making them noisier than they would be otherwise.'
        )
        register(
            '--log-show-rust-3rdparty',
            type=bool,
            default=False,
            advanced=True,
            help=
            'Whether to show/hide logging done by 3rdparty rust crates used by the pants '
            'engine.')

        # Not really needed in bootstrap options, but putting it here means it displays right
        # after -l and -q in help output, which is conveniently contextual.
        register('--colors',
                 type=bool,
                 default=sys.stdout.isatty(),
                 recursive=True,
                 daemon=False,
                 help='Set whether log messages are displayed in color.')
        # TODO(#7203): make a regexp option type!
        register(
            '--ignore-pants-warnings',
            type=list,
            member_type=str,
            default=[],
            help='Regexps matching warning strings to ignore, e.g. '
            '["DEPRECATED: scope some_scope will be removed"]. The regexps will be matched '
            'from the start of the warning string, and will always be case-insensitive. '
            'See the `warnings` module documentation for more background on these are used.'
        )
        register(
            '--option-name-check-distance',
            advanced=True,
            type=int,
            default=2,
            help=
            'The maximum Levenshtein distance to use when offering suggestions for invalid '
            'option names.')

        register(
            '--pants-version',
            advanced=True,
            default=pants_version(),
            help=
            'Use this pants version. Note Pants code only uses this to verify that you are '
            'using the requested version, as Pants cannot dynamically change the version it '
            'is using once the program is already running. This option is useful to set in '
            'your pants.ini, however, and then you can grep the value to select which '
            'version to use for setup scripts (e.g. `./pants`), runner scripts, IDE plugins, '
            'etc. For example, the setup script we distribute at https://www.pantsbuild.org/install.html#recommended-installation '
            'uses this value to determine which Python version to run with. You may find the '
            'version of the pants instance you are running using -v, -V, or --version.'
        )

        register('--plugins',
                 advanced=True,
                 type=list,
                 help='Load these plugins.')
        register('--plugin-cache-dir',
                 advanced=True,
                 default=os.path.join(get_pants_cachedir(), 'plugins'),
                 help='Cache resolved plugin requirements here.')

        register(
            '--backend-packages',
            advanced=True,
            type=list,
            default=[
                'pants.backend.graph_info', 'pants.backend.python',
                'pants.backend.jvm', 'pants.backend.native',
                'pants.backend.codegen.antlr.java',
                'pants.backend.codegen.antlr.python',
                'pants.backend.codegen.jaxb',
                'pants.backend.codegen.protobuf.java',
                'pants.backend.codegen.ragel.java',
                'pants.backend.codegen.thrift.java',
                'pants.backend.codegen.thrift.python',
                'pants.backend.codegen.grpcio.python',
                'pants.backend.codegen.wire.java', 'pants.backend.project_info'
            ],
            help=
            'Load backends from these packages that are already on the path. '
            'Add contrib and custom backends to this list.')

        register('--pants-bootstrapdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_cachedir(),
                 help='Use this dir for global cache.')
        register('--pants-configdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_configdir(),
                 help='Use this dir for global config files.')
        register('--pants-workdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, '.pants.d'),
                 help='Write intermediate output files to this dir.')
        register('--pants-supportdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'build-support'),
                 help='Use support files from this dir.')
        register(
            '--pants-distdir',
            advanced=True,
            metavar='<dir>',
            default=default_distdir,
            help=
            'Write end-product artifacts to this dir. If you modify this path, you '
            'should also update --build-ignore and --pants-ignore to include the '
            'custom dist dir path as well.')
        register(
            '--pants-subprocessdir',
            advanced=True,
            default=os.path.join(buildroot, '.pids'),
            help=
            'The directory to use for tracking subprocess metadata, if any. This should '
            'live outside of the dir used by `--pants-workdir` to allow for tracking '
            'subprocesses that outlive the workdir data (e.g. `./pants server`).'
        )
        register('--pants-config-files',
                 advanced=True,
                 type=list,
                 daemon=False,
                 default=[get_default_pants_config_file()],
                 help='Paths to Pants config files.')
        # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
        # to set extra config file locations in an initial bootstrap config file.
        register('--pantsrc',
                 advanced=True,
                 type=bool,
                 default=True,
                 help='Use pantsrc files.')
        register('--pantsrc-files',
                 advanced=True,
                 type=list,
                 metavar='<path>',
                 daemon=False,
                 default=['/etc/pantsrc', '~/.pants.rc'],
                 help='Override config with values from these files. '
                 'Later files override earlier ones.')
        register(
            '--pythonpath',
            advanced=True,
            type=list,
            help='Add these directories to PYTHONPATH to search for plugins.')
        register('--target-spec-file',
                 type=list,
                 dest='target_spec_files',
                 daemon=False,
                 help='Read additional specs from this file, one per line')
        register(
            '--verify-config',
            type=bool,
            default=True,
            daemon=False,
            advanced=True,
            help=
            'Verify that all config file values correspond to known options.')

        register(
            '--build-ignore',
            advanced=True,
            type=list,
            default=[
                '.*/', default_rel_distdir, 'bower_components/',
                'node_modules/', '*.egg-info/'
            ],
            help='Paths to ignore when identifying BUILD files. '
            'This does not affect any other filesystem operations. '
            'Patterns use the gitignore pattern syntax (https://git-scm.com/docs/gitignore).'
        )
        register(
            '--pants-ignore',
            advanced=True,
            type=list,
            default=['.*/', default_rel_distdir],
            help=
            'Paths to ignore for all filesystem operations performed by pants '
            '(e.g. BUILD file scanning, glob matching, etc). '
            'Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore).'
        )
        register(
            '--glob-expansion-failure',
            advanced=True,
            default=GlobMatchErrorBehavior.warn,
            type=GlobMatchErrorBehavior,
            help="Raise an exception if any targets declaring source files "
            "fail to match any glob provided in the 'sources' argument.")

        # TODO(#7203): make a regexp option type!
        register('--exclude-target-regexp',
                 advanced=True,
                 type=list,
                 default=[],
                 daemon=False,
                 metavar='<regexp>',
                 help='Exclude target roots that match these regexes.')
        register(
            '--subproject-roots',
            type=list,
            advanced=True,
            default=[],
            help=
            'Paths that correspond with build roots for any subproject that this '
            'project depends on.')
        register(
            '--owner-of',
            type=list,
            member_type=file_option,
            default=[],
            daemon=False,
            metavar='<path>',
            help='Select the targets that own these files. '
            'This is the third target calculation strategy along with the --changed-* '
            'options and specifying the targets directly. These three types of target '
            'selection are mutually exclusive.')

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register('-d',
                 '--logdir',
                 advanced=True,
                 metavar='<dir>',
                 help='Write logs to files under this directory.')

        # This facilitates bootstrap-time configuration of pantsd usage such that we can
        # determine whether or not to use the Pailgun client to invoke a given pants run
        # without resorting to heavier options parsing.
        register(
            '--enable-pantsd',
            advanced=True,
            type=bool,
            default=False,
            help=
            'Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)'
        )

        # Whether or not to make necessary arrangements to have concurrent runs in pants.
        # In practice, this means that if this is set, a run will not even try to use pantsd.
        # NB: Eventually, we would like to deprecate this flag in favor of making pantsd runs parallelizable.
        register(
            '--concurrent',
            advanced=True,
            type=bool,
            default=False,
            daemon=False,
            help=
            'Enable concurrent runs of pants. Without this enabled, pants will '
            'start up all concurrent invocations (e.g. in other terminals) without pantsd. '
            'Enabling this option requires parallel pants invocations to block on the first'
        )

        # Shutdown pantsd after the current run.
        # This needs to be accessed at the same time as enable_pantsd,
        # so we register it at bootstrap time.
        register(
            '--shutdown-pantsd-after-run',
            advanced=True,
            type=bool,
            default=False,
            help=
            'Create a new pantsd server, and use it, and shut it down immediately after. '
            'If pantsd is already running, it will shut it down and spawn a new instance (Beta)'
        )

        # NB: We really don't want this option to invalidate the daemon, because different clients might have
        # different needs. For instance, an IDE might have a very long timeout because it only wants to refresh
        # a project in the background, while a user might want a shorter timeout for interactivity.
        register(
            '--pantsd-timeout-when-multiple-invocations',
            advanced=True,
            type=float,
            default=60.0,
            daemon=False,
            help=
            'The maximum amount of time to wait for the invocation to start until '
            'raising a timeout exception. '
            'Because pantsd currently does not support parallel runs, '
            'any prior running Pants command must be finished for the current one to start. '
            'To never timeout, use the value -1.')

        # These facilitate configuring the native engine.
        register(
            '--native-engine-visualize-to',
            advanced=True,
            default=None,
            type=dir_option,
            daemon=False,
            help=
            'A directory to write execution and rule graphs to as `dot` files. The contents '
            'of the directory will be overwritten if any filenames collide.')
        register(
            '--print-exception-stacktrace',
            advanced=True,
            type=bool,
            help=
            'Print to console the full exception stack trace if encountered.')

        # BinaryUtil options.
        register(
            '--binaries-baseurls',
            type=list,
            advanced=True,
            default=['https://binaries.pantsbuild.org'],
            help='List of URLs from which binary tools are downloaded. URLs are '
            'searched in order until the requested path is found.')
        register(
            '--binaries-fetch-timeout-secs',
            type=int,
            default=30,
            advanced=True,
            daemon=False,
            help=
            'Timeout in seconds for URL reads when fetching binary tools from the '
            'repos specified by --baseurls.')
        register(
            '--binaries-path-by-id',
            type=dict,
            advanced=True,
            help=
            ("Maps output of uname for a machine to a binary search path: "
             "(sysname, id) -> (os, arch), e.g. {('darwin', '15'): ('mac', '10.11'), "
             "('linux', 'arm32'): ('linux', 'arm32')}."))
        register(
            '--allow-external-binary-tool-downloads',
            type=bool,
            default=True,
            advanced=True,
            help=
            "If False, require BinaryTool subclasses to download their contents from urls "
            "generated from --binaries-baseurls, even if the tool has an external url "
            "generator. This can be necessary if using Pants in an environment which cannot "
            "contact the wider Internet.")

        # Pants Daemon options.
        register('--pantsd-pailgun-host',
                 advanced=True,
                 default='127.0.0.1',
                 help='The host to bind the pants nailgun server to.')
        register(
            '--pantsd-pailgun-port',
            advanced=True,
            type=int,
            default=0,
            help=
            'The port to bind the pants nailgun server to. Defaults to a random port.'
        )
        # TODO(#7514): Make this default to 1.0 seconds if stdin is a tty!
        register(
            '--pantsd-pailgun-quit-timeout',
            advanced=True,
            type=float,
            default=5.0,
            help=
            'The length of time (in seconds) to wait for further output after sending a '
            'signal to the remote pantsd process before killing it.')
        register('--pantsd-log-dir',
                 advanced=True,
                 default=None,
                 help='The directory to log pantsd output to.')
        register(
            '--pantsd-invalidation-globs',
            advanced=True,
            type=list,
            default=[],
            help=
            'Filesystem events matching any of these globs will trigger a daemon restart.'
        )

        # Watchman options.
        register('--watchman-version',
                 advanced=True,
                 default='4.9.0-pants1',
                 help='Watchman version.')
        register(
            '--watchman-supportdir',
            advanced=True,
            default='bin/watchman',
            help=
            'Find watchman binaries under this dir. Used as part of the path to lookup '
            'the binary with --binaries-baseurls and --pants-bootstrapdir.')
        register(
            '--watchman-startup-timeout',
            type=float,
            advanced=True,
            default=30.0,
            help=
            'The watchman socket timeout (in seconds) for the initial `watch-project` command. '
            'This may need to be set higher for larger repos due to watchman startup cost.'
        )
        register(
            '--watchman-socket-timeout',
            type=float,
            advanced=True,
            default=0.1,
            help=
            'The watchman client socket timeout in seconds. Setting this to too high a '
            'value can negatively impact the latency of runs forked by pantsd.'
        )
        register(
            '--watchman-socket-path',
            type=str,
            advanced=True,
            default=None,
            help=
            'The path to the watchman UNIX socket. This can be overridden if the default '
            'absolute path length exceeds the maximum allowed by the OS.')

        # This option changes the parser behavior in a fundamental way (which currently invalidates
        # all caches), and needs to be parsed out early, so we make it a bootstrap option.
        register('--build-file-imports',
                 choices=['allow', 'warn', 'error'],
                 default='warn',
                 advanced=True,
                 help='Whether to allow import statements in BUILD files')

        register(
            '--local-store-dir',
            advanced=True,
            help="Directory to use for engine's local file store.",
            # This default is also hard-coded into the engine's rust code in
            # fs::Store::default_path
            default=os.path.expanduser('~/.cache/pants/lmdb_store'))

        register(
            '--remote-execution',
            advanced=True,
            type=bool,
            default=DEFAULT_EXECUTION_OPTIONS.remote_execution,
            help="Enables remote workers for increased parallelism. (Alpha)")
        register(
            '--remote-store-server',
            advanced=True,
            type=list,
            default=[],
            help=
            'host:port of grpc server to use as remote execution file store.')
        register(
            '--remote-store-thread-count',
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_thread_count,
            help=
            'Thread count to use for the pool that interacts with the remote file store.'
        )
        register(
            '--remote-execution-server',
            advanced=True,
            help=
            'host:port of grpc server to use as remote execution scheduler.')
        register(
            '--remote-store-chunk-bytes',
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_chunk_bytes,
            help=
            'Size in bytes of chunks transferred to/from the remote file store.'
        )
        register(
            '--remote-store-chunk-upload-timeout-seconds',
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.
            remote_store_chunk_upload_timeout_seconds,
            help=
            'Timeout (in seconds) for uploads of individual chunks to the remote file store.'
        )
        register(
            '--remote-store-rpc-retries',
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_rpc_retries,
            help=
            'Number of times to retry any RPC to the remote store before giving up.'
        )
        register(
            '--remote-execution-process-cache-namespace',
            advanced=True,
            help="The cache namespace for remote process execution. "
            "Bump this to invalidate every artifact's remote execution. "
            "This is the remote execution equivalent of the legacy cache-key-gen-version "
            "flag.")
        register(
            '--remote-instance-name',
            advanced=True,
            help=
            'Name of the remote execution instance to use. Used for routing within '
            '--remote-execution-server and --remote-store-server.')
        register(
            '--remote-ca-certs-path',
            advanced=True,
            help=
            'Path to a PEM file containing CA certificates used for verifying secure '
            'connections to --remote-execution-server and --remote-store-server. '
            'If not specified, TLS will not be used.')
        register(
            '--remote-oauth-bearer-token-path',
            advanced=True,
            help=
            'Path to a file containing an oauth token to use for grpc connections to '
            '--remote-execution-server and --remote-store-server. If not specified, no '
            'authorization will be performed.')
        register(
            '--remote-execution-extra-platform-properties',
            advanced=True,
            help='Platform properties to set on remote execution requests. '
            'Format: property=value. Multiple values should be specified as multiple '
            'occurrences of this flag. Pants itself may add additional platform properties.',
            type=list,
            default=[])

        # This should eventually deprecate the RunTracker worker count, which is used for legacy cache
        # lookups via CacheSetup in TaskBase.
        register(
            '--process-execution-parallelism',
            type=int,
            dest='local_execution_parallelism',
            removal_version='1.20.0.dev2',
            advanced=True,
            removal_hint=
            'Use --process-execution-local-parallelism, and/or --process-execution-remote-parallelism instead.',
            help='Number of concurrent processes that may be executed locally.'
        )
        register(
            '--process-execution-local-parallelism',
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_local_parallelism,
            advanced=True,
            help='Number of concurrent processes that may be executed locally.'
        )
        register(
            '--process-execution-remote-parallelism',
            type=int,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_remote_parallelism,
            advanced=True,
            help='Number of concurrent processes that may be executed remotely.'
        )
        register(
            '--process-execution-cleanup-local-dirs',
            type=bool,
            default=True,
            advanced=True,
            help=
            'Whether or not to cleanup directories used for local process execution '
            '(primarily useful for e.g. debugging).')
        register(
            '--process-execution-speculation-delay',
            type=float,
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_speculation_delay,
            advanced=True,
            help=
            'Number of seconds to wait before speculating a second request for a slow process. '
            ' see `--process-execution-speculation-strategy`')
        register(
            '--process-execution-speculation-strategy',
            choices=['remote_first', 'local_first', 'none'],
            default=DEFAULT_EXECUTION_OPTIONS.
            process_execution_speculation_strategy,
            help=
            "Speculate a second request for an underlying process if the first one does not complete within "
            '`--process-execution-speculation-delay` seconds.\n'
            '`local_first` (default): Try to run the process locally first, '
            'and fall back to remote execution if available.\n'
            '`remote_first`: Run the process on the remote execution backend if available, '
            'and fall back to the local host if remote calls take longer than the speculation timeout.\n'
            '`none`: Do not speculate about long running processes.',
            advanced=True)
        register(
            '--process-execution-use-local-cache',
            type=bool,
            default=True,
            advanced=True,
            help=
            'Whether to keep process executions in a local cache persisted to disk.'
        )
Exemplo n.º 19
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
        buildroot = get_buildroot()

        # Although logging supports the WARN level, its not documented and could conceivably be yanked.
        # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
        # setup a 'WARN' logging level name that maps to 'WARNING'.
        logging.addLevelName(logging.WARNING, "WARN")
        register(
            "-l",
            "--level",
            choices=["debug", "info", "warn"],
            default="info",
            recursive=True,
            help="Set the logging level.",
        )
        register("-q", "--quiet", type=bool, recursive=True, help="Squelches most console output.")
        # Not really needed in bootstrap options, but putting it here means it displays right
        # after -l and -q in help output, which is conveniently contextual.
        register(
            "--colors", type=bool, default=True, recursive=True, help="Set whether log messages are displayed in color."
        )

        # Pants code uses this only to verify that we are of the requested version. However
        # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
        # and use it to select the right version.
        # Note that to print the version of the pants instance you're running, use -v, -V or --version.
        register("--pants-version", advanced=True, default=pants_version(), help="Use this pants version.")

        register("--plugins", advanced=True, type=list, help="Load these plugins.")
        register(
            "--plugin-cache-dir",
            advanced=True,
            default=os.path.join(get_pants_cachedir(), "plugins"),
            help="Cache resolved plugin requirements here.",
        )

        register(
            "--backend-packages",
            advanced=True,
            type=list,
            default=[
                "pants.backend.graph_info",
                "pants.backend.python",
                "pants.backend.jvm",
                "pants.backend.codegen",
                "pants.backend.project_info",
            ],
            help="Load backends from these packages that are already on the path. "
            "Add contrib and custom backends to this list.",
        )
        register(
            "--default-backend-packages",
            advanced=True,
            type=list,
            removal_version="1.3.0",
            removal_hint="All backends must be specified using the backend_packages option. "
            "That option has the same defaults as this one, and you can append"
            "and filter those using +[...] and -[...] syntax, as described here: "
            "http://www.pantsbuild.org/options.html#list-options.",
            default=[
                "pants.backend.graph_info",
                "pants.backend.python",
                "pants.backend.jvm",
                "pants.backend.codegen",
                "pants.backend.project_info",
            ],
            help="Load these backends by default.  These backends come distributed with Pants. "
            "Remove unused backends from this list to speed up execution. "
            "Use --backend-packages to configure additional backends with Pants.",
        )

        register(
            "--pants-bootstrapdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_cachedir(),
            help="Use this dir for global cache.",
        )
        register(
            "--pants-configdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_configdir(),
            help="Use this dir for global config files.",
        )
        register(
            "--pants-workdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, ".pants.d"),
            help="Write intermediate output files to this dir.",
        )
        register(
            "--pants-supportdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "build-support"),
            help="Use support files from this dir.",
        )
        register(
            "--pants-distdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "dist"),
            help="Write end-product artifacts to this dir.",
        )
        register(
            "--pants-subprocessdir",
            advanced=True,
            default=os.path.join(buildroot, ".pids"),
            help="The directory to use for tracking subprocess metadata, if any. This should "
            "live outside of the dir used by `--pants-workdir` to allow for tracking "
            "subprocesses that outlive the workdir data (e.g. `./pants server`).",
        )
        register(
            "--pants-config-files",
            advanced=True,
            type=list,
            default=[get_default_pants_config_file()],
            help="Paths to Pants config files.",
        )
        # TODO: Deprecate --config-override in favor of --pants-config-files.
        # But only once we're able to both append and override list-valued options, as there are
        # use-cases for both here.
        # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
        # to set extra config file locations in an initial bootstrap config file.
        register(
            "--config-override",
            advanced=True,
            type=list,
            metavar="<path>",
            help="A second config file, to override pants.ini.",
        )
        register("--pantsrc", advanced=True, type=bool, default=True, help="Use pantsrc files.")
        register(
            "--pantsrc-files",
            advanced=True,
            type=list,
            metavar="<path>",
            default=["/etc/pantsrc", "~/.pants.rc"],
            help="Override config with values from these files. " "Later files override earlier ones.",
        )
        register(
            "--pythonpath", advanced=True, type=list, help="Add these directories to PYTHONPATH to search for plugins."
        )
        register(
            "--target-spec-file",
            type=list,
            dest="target_spec_files",
            help="Read additional specs from this file, one per line",
        )
        register(
            "--verify-config",
            type=bool,
            default=True,
            help="Verify that all config file values correspond to known options.",
        )

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register("-d", "--logdir", advanced=True, metavar="<dir>", help="Write logs to files under this directory.")

        # This facilitates bootstrap-time configuration of pantsd usage such that we can
        # determine whether or not to use the Pailgun client to invoke a given pants run
        # without resorting to heavier options parsing.
        register(
            "--enable-pantsd",
            advanced=True,
            type=bool,
            default=False,
            help="Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)",
        )

        # This facilitates use of the v2 engine for BuildGraph construction, sans daemon.
        register(
            "--enable-v2-engine", advanced=True, type=bool, default=False, help="Enables use of the v2 engine. (Beta)"
        )
Exemplo n.º 20
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
        buildroot = get_buildroot()
        register('--plugins',
                 advanced=True,
                 type=Options.list,
                 help='Load these plugins.')
        register(
            '--backend-packages',
            advanced=True,
            type=Options.list,
            help=
            'Load backends from these packages that are already on the path.')

        register('--pants-bootstrapdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_cachedir(),
                 help='Use this dir for global cache.')
        register('--pants-configdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_configdir(),
                 help='Use this dir for global config files.')
        register('--pants-workdir',
                 metavar='<dir>',
                 default=os.path.join(buildroot, '.pants.d'),
                 help='Write intermediate output files to this dir.')
        register('--pants-supportdir',
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'build-support'),
                 help='Use support files from this dir.')
        register('--pants-distdir',
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'dist'),
                 help='Write end-product artifacts to this dir.')
        register('--config-override',
                 help='A second config file, to override pants.ini.')
        register('--pantsrc',
                 action='store_true',
                 default=True,
                 help='Use pantsrc files.')
        register('--pantsrc-files',
                 action='append',
                 metavar='<path>',
                 default=['/etc/pantsrc', '~/.pants.rc'],
                 help='Override config with values from these files. '
                 'Later files override earlier ones.')
        register(
            '--pythonpath',
            action='append',
            help='Add these directories to PYTHONPATH to search for plugins.')
        register('--target-spec-file',
                 action='append',
                 dest='target_spec_files',
                 help='Read additional specs from this file, one per line')

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register('-d',
                 '--logdir',
                 metavar='<dir>',
                 help='Write logs to files under this directory.')

        # Although logging supports the WARN level, its not documented and could conceivably be yanked.
        # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
        # setup a 'WARN' logging level name that maps to 'WARNING'.
        logging.addLevelName(logging.WARNING, 'WARN')
        register('-l',
                 '--level',
                 choices=['debug', 'info', 'warn'],
                 default='info',
                 recursive=True,
                 help='Set the logging level.')

        register('-q',
                 '--quiet',
                 action='store_true',
                 help='Squelches all console output apart from errors.')
Exemplo n.º 21
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
        buildroot = get_buildroot()
        default_distdir_name = 'dist'
        default_distdir = os.path.join(buildroot, default_distdir_name)
        default_rel_distdir = '/{}/'.format(default_distdir_name)

        # Although logging supports the WARN level, its not documented and could conceivably be yanked.
        # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
        # setup a 'WARN' logging level name that maps to 'WARNING'.
        logging.addLevelName(logging.WARNING, 'WARN')
        register('-l',
                 '--level',
                 choices=['debug', 'info', 'warn'],
                 default='info',
                 recursive=True,
                 help='Set the logging level.')
        register(
            '-q',
            '--quiet',
            type=bool,
            recursive=True,
            daemon=False,
            help=
            'Squelches most console output. NOTE: Some tasks default to behaving quietly: '
            'inverting this option supports making them noisier than they would be otherwise.'
        )
        # Not really needed in bootstrap options, but putting it here means it displays right
        # after -l and -q in help output, which is conveniently contextual.
        register('--colors',
                 type=bool,
                 default=sys.stdout.isatty(),
                 recursive=True,
                 daemon=False,
                 help='Set whether log messages are displayed in color.')

        # Pants code uses this only to verify that we are of the requested version. However
        # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
        # and use it to select the right version.
        # Note that to print the version of the pants instance you're running, use -v, -V or --version.
        register('--pants-version',
                 advanced=True,
                 default=pants_version(),
                 help='Use this pants version.')

        register('--plugins',
                 advanced=True,
                 type=list,
                 help='Load these plugins.')
        register('--plugin-cache-dir',
                 advanced=True,
                 default=os.path.join(get_pants_cachedir(), 'plugins'),
                 help='Cache resolved plugin requirements here.')

        register(
            '--backend-packages',
            advanced=True,
            type=list,
            default=[
                'pants.backend.graph_info', 'pants.backend.python',
                'pants.backend.jvm', 'pants.backend.native',
                'pants.backend.codegen.antlr.java',
                'pants.backend.codegen.antlr.python',
                'pants.backend.codegen.jaxb',
                'pants.backend.codegen.protobuf.java',
                'pants.backend.codegen.ragel.java',
                'pants.backend.codegen.thrift.java',
                'pants.backend.codegen.thrift.python',
                'pants.backend.codegen.wire.java', 'pants.backend.project_info'
            ],
            help=
            'Load backends from these packages that are already on the path. '
            'Add contrib and custom backends to this list.')

        register('--pants-bootstrapdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_cachedir(),
                 help='Use this dir for global cache.')
        register('--pants-configdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_configdir(),
                 help='Use this dir for global config files.')
        register('--pants-workdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, '.pants.d'),
                 help='Write intermediate output files to this dir.')
        register('--pants-supportdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'build-support'),
                 help='Use support files from this dir.')
        register(
            '--pants-distdir',
            advanced=True,
            metavar='<dir>',
            default=default_distdir,
            help=
            'Write end-product artifacts to this dir. If you modify this path, you '
            'should also update --build-ignore and --pants-ignore to include the '
            'custom dist dir path as well.')
        register(
            '--pants-subprocessdir',
            advanced=True,
            default=os.path.join(buildroot, '.pids'),
            help=
            'The directory to use for tracking subprocess metadata, if any. This should '
            'live outside of the dir used by `--pants-workdir` to allow for tracking '
            'subprocesses that outlive the workdir data (e.g. `./pants server`).'
        )
        register('--pants-config-files',
                 advanced=True,
                 type=list,
                 daemon=False,
                 default=[get_default_pants_config_file()],
                 help='Paths to Pants config files.')
        # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
        # to set extra config file locations in an initial bootstrap config file.
        register('--pantsrc',
                 advanced=True,
                 type=bool,
                 default=True,
                 help='Use pantsrc files.')
        register('--pantsrc-files',
                 advanced=True,
                 type=list,
                 metavar='<path>',
                 daemon=False,
                 default=['/etc/pantsrc', '~/.pants.rc'],
                 help='Override config with values from these files. '
                 'Later files override earlier ones.')
        register(
            '--pythonpath',
            advanced=True,
            type=list,
            help='Add these directories to PYTHONPATH to search for plugins.')
        register('--target-spec-file',
                 type=list,
                 dest='target_spec_files',
                 daemon=False,
                 help='Read additional specs from this file, one per line')
        register(
            '--verify-config',
            type=bool,
            default=True,
            daemon=False,
            help=
            'Verify that all config file values correspond to known options.')
        register(
            '--build-ignore',
            advanced=True,
            type=list,
            fromfile=True,
            default=[
                '.*/', default_rel_distdir, 'bower_components/',
                'node_modules/', '*.egg-info/'
            ],
            help='Paths to ignore when identifying BUILD files. '
            'This does not affect any other filesystem operations. '
            'Patterns use the gitignore pattern syntax (https://git-scm.com/docs/gitignore).'
        )
        register(
            '--pants-ignore',
            advanced=True,
            type=list,
            fromfile=True,
            default=['.*/', default_rel_distdir],
            help=
            'Paths to ignore for all filesystem operations performed by pants '
            '(e.g. BUILD file scanning, glob matching, etc). '
            'Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore).'
        )
        register('--exclude-target-regexp',
                 advanced=True,
                 type=list,
                 default=[],
                 daemon=False,
                 metavar='<regexp>',
                 help='Exclude target roots that match these regexes.')
        register(
            '--subproject-roots',
            type=list,
            advanced=True,
            fromfile=True,
            default=[],
            help=
            'Paths that correspond with build roots for any subproject that this '
            'project depends on.')

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register('-d',
                 '--logdir',
                 advanced=True,
                 metavar='<dir>',
                 help='Write logs to files under this directory.')

        # This facilitates bootstrap-time configuration of pantsd usage such that we can
        # determine whether or not to use the Pailgun client to invoke a given pants run
        # without resorting to heavier options parsing.
        register(
            '--enable-pantsd',
            advanced=True,
            type=bool,
            default=False,
            help=
            'Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)'
        )

        # These facilitate configuring the native engine.
        register(
            '--native-engine-visualize-to',
            advanced=True,
            default=None,
            type=dir_option,
            daemon=False,
            help=
            'A directory to write execution and rule graphs to as `dot` files. The contents '
            'of the directory will be overwritten if any filenames collide.')

        # BinaryUtil options.
        register(
            '--binaries-baseurls',
            type=list,
            advanced=True,
            default=['https://binaries.pantsbuild.org'],
            help='List of URLs from which binary tools are downloaded. URLs are '
            'searched in order until the requested path is found.')
        register(
            '--binaries-fetch-timeout-secs',
            type=int,
            default=30,
            advanced=True,
            daemon=False,
            help=
            'Timeout in seconds for URL reads when fetching binary tools from the '
            'repos specified by --baseurls.')
        register(
            '--binaries-path-by-id',
            type=dict,
            advanced=True,
            help=
            ("Maps output of uname for a machine to a binary search path: "
             "(sysname, id) -> (os, arch), e.g. {('darwin', '15'): ('mac', '10.11'), "
             "('linux', 'arm32'): ('linux', 'arm32')}."))
        register(
            '--allow-external-binary-tool-downloads',
            type=bool,
            default=True,
            advanced=True,
            help=
            "If False, require BinaryTool subclasses to download their contents from urls "
            "generated from --binaries-baseurls, even if the tool has an external url "
            "generator. This can be necessary if using Pants in an environment which cannot "
            "contact the wider Internet.")

        # Pants Daemon options.
        register('--pantsd-pailgun-host',
                 advanced=True,
                 default='127.0.0.1',
                 help='The host to bind the pants nailgun server to.')
        register(
            '--pantsd-pailgun-port',
            advanced=True,
            type=int,
            default=0,
            help=
            'The port to bind the pants nailgun server to. Defaults to a random port.'
        )
        register('--pantsd-log-dir',
                 advanced=True,
                 default=None,
                 help='The directory to log pantsd output to.')
        register(
            '--pantsd-fs-event-workers',
            advanced=True,
            type=int,
            default=4,
            help=
            'The number of workers to use for the filesystem event service executor pool.'
        )
        register(
            '--pantsd-invalidation-globs',
            advanced=True,
            type=list,
            fromfile=True,
            default=[],
            help=
            'Filesystem events matching any of these globs will trigger a daemon restart.'
        )

        # Watchman options.
        register('--watchman-version',
                 advanced=True,
                 default='4.9.0-pants1',
                 help='Watchman version.')
        register(
            '--watchman-supportdir',
            advanced=True,
            default='bin/watchman',
            help=
            'Find watchman binaries under this dir. Used as part of the path to lookup '
            'the binary with --binaries-baseurls and --pants-bootstrapdir.')
        register(
            '--watchman-startup-timeout',
            type=float,
            advanced=True,
            default=30.0,
            help=
            'The watchman socket timeout (in seconds) for the initial `watch-project` command. '
            'This may need to be set higher for larger repos due to watchman startup cost.'
        )
        register('--watchman-socket-timeout',
                 type=float,
                 advanced=True,
                 default=5.0,
                 help='The watchman client socket timeout in seconds.')
        register(
            '--watchman-socket-path',
            type=str,
            advanced=True,
            default=None,
            help=
            'The path to the watchman UNIX socket. This can be overridden if the default '
            'absolute path length exceeds the maximum allowed by the OS.')

        # This option changes the parser behavior in a fundamental way (which currently invalidates
        # all caches), and needs to be parsed out early, so we make it a bootstrap option.
        register('--build-file-imports',
                 choices=['allow', 'warn', 'error'],
                 default='warn',
                 help='Whether to allow import statements in BUILD files')
Exemplo n.º 22
0
 def __init__(self, *args, **kwargs):
   super(SignApkTask, self).__init__(*args, **kwargs)
   self._config_file = self.get_options().keystore_config_location
   self._distdir = self.get_options().pants_distdir
   self._configdir = get_pants_configdir()
   self._dist = None
Exemplo n.º 23
0
  def register_bootstrap_options(cls, register):
    """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
    buildroot = get_buildroot()

    # Although logging supports the WARN level, its not documented and could conceivably be yanked.
    # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
    # setup a 'WARN' logging level name that maps to 'WARNING'.
    logging.addLevelName(logging.WARNING, 'WARN')
    register('-l', '--level', choices=['debug', 'info', 'warn'], default='info', recursive=True,
             help='Set the logging level.')
    register('-q', '--quiet', type=bool, recursive=True,
             help='Squelches most console output.')
    # Not really needed in bootstrap options, but putting it here means it displays right
    # after -l and -q in help output, which is conveniently contextual.
    register('--colors', type=bool, default=True, recursive=True,
             help='Set whether log messages are displayed in color.')

    # Pants code uses this only to verify that we are of the requested version. However
    # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
    # and use it to select the right version.
    # Note that to print the version of the pants instance you're running, use -v, -V or --version.
    register('--pants-version', advanced=True, default=pants_version(),
             help='Use this pants version.')

    register('--plugins', advanced=True, type=list, help='Load these plugins.')
    register('--plugin-cache-dir', advanced=True,
             default=os.path.join(get_pants_cachedir(), 'plugins'),
             help='Cache resolved plugin requirements here.')

    register('--backend-packages', advanced=True, type=list,
             help='Load backends from these packages that are already on the path.')

    register('--pants-bootstrapdir', advanced=True, metavar='<dir>', default=get_pants_cachedir(),
             help='Use this dir for global cache.')
    register('--pants-configdir', advanced=True, metavar='<dir>', default=get_pants_configdir(),
             help='Use this dir for global config files.')
    register('--pants-workdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, '.pants.d'),
             help='Write intermediate output files to this dir.')
    register('--pants-supportdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'build-support'),
             help='Use support files from this dir.')
    register('--pants-distdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'dist'),
             help='Write end-product artifacts to this dir.')
    register('--pants-config-files', advanced=True, type=list,
             default=[get_default_pants_config_file()], help='Paths to Pants config files.')
    # TODO: Deprecate --config-override in favor of --pants-config-files.
    # But only once we're able to both append and override list-valued options, as there are
    # use-cases for both here.
    # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
    # to set extra config file locations in an initial bootstrap config file.
    register('--config-override', advanced=True, type=list, metavar='<path>',
             help='A second config file, to override pants.ini.')
    register('--pantsrc', advanced=True, type=bool, default=True,
             help='Use pantsrc files.')
    register('--pantsrc-files', advanced=True, type=list, metavar='<path>',
             default=['/etc/pantsrc', '~/.pants.rc'],
             help='Override config with values from these files. '
                  'Later files override earlier ones.')
    register('--pythonpath', advanced=True, type=list,
             help='Add these directories to PYTHONPATH to search for plugins.')
    register('--target-spec-file', type=list, dest='target_spec_files',
             help='Read additional specs from this file, one per line')
    register('--verify-config', type=bool, default=True,
             help='Verify that all config file values correspond to known options.')

    # These logging options are registered in the bootstrap phase so that plugins can log during
    # registration and not so that their values can be interpolated in configs.
    register('-d', '--logdir', advanced=True, metavar='<dir>',
             help='Write logs to files under this directory.')

    # This facilitates bootstrap-time configuration of pantsd usage such that we can
    # determine whether or not to use the Pailgun client to invoke a given pants run
    # without resorting to heavier options parsing.
    register('--enable-pantsd', advanced=True, type=bool, default=False,
             help='Enables use of the pants daemon. (Beta)')
Exemplo n.º 24
0
  def register_bootstrap_options(cls, register):
    """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
    buildroot = get_buildroot()

    # Although logging supports the WARN level, its not documented and could conceivably be yanked.
    # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
    # setup a 'WARN' logging level name that maps to 'WARNING'.
    logging.addLevelName(logging.WARNING, 'WARN')
    register('-l', '--level', choices=['debug', 'info', 'warn'], default='info', recursive=True,
             help='Set the logging level.')
    register('-q', '--quiet', type=bool, recursive=True,
             help='Squelches most console output.')
    # Not really needed in bootstrap options, but putting it here means it displays right
    # after -l and -q in help output, which is conveniently contextual.
    register('--colors', type=bool, default=sys.stdout.isatty(), recursive=True,
             help='Set whether log messages are displayed in color.')

    # Pants code uses this only to verify that we are of the requested version. However
    # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
    # and use it to select the right version.
    # Note that to print the version of the pants instance you're running, use -v, -V or --version.
    register('--pants-version', advanced=True, default=pants_version(),
             help='Use this pants version.')

    register('--plugins', advanced=True, type=list, help='Load these plugins.')
    register('--plugin-cache-dir', advanced=True,
             default=os.path.join(get_pants_cachedir(), 'plugins'),
             help='Cache resolved plugin requirements here.')

    register('--backend-packages', advanced=True, type=list,
             default=['pants.backend.graph_info',
                      'pants.backend.python',
                      'pants.backend.jvm',
                      'pants.backend.codegen.antlr.java',
                      'pants.backend.codegen.antlr.python',
                      'pants.backend.codegen.jaxb',
                      'pants.backend.codegen.protobuf.java',
                      'pants.backend.codegen.ragel.java',
                      'pants.backend.codegen.thrift.java',
                      'pants.backend.codegen.thrift.python',
                      'pants.backend.codegen.wire.java',
                      'pants.backend.project_info'],
             help='Load backends from these packages that are already on the path. '
                  'Add contrib and custom backends to this list.')

    register('--pants-bootstrapdir', advanced=True, metavar='<dir>', default=get_pants_cachedir(),
             help='Use this dir for global cache.')
    register('--pants-configdir', advanced=True, metavar='<dir>', default=get_pants_configdir(),
             help='Use this dir for global config files.')
    register('--pants-workdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, '.pants.d'),
             help='Write intermediate output files to this dir.')
    register('--pants-supportdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'build-support'),
             help='Use support files from this dir.')
    register('--pants-distdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'dist'),
             help='Write end-product artifacts to this dir.')
    register('--pants-subprocessdir', advanced=True, default=os.path.join(buildroot, '.pids'),
             help='The directory to use for tracking subprocess metadata, if any. This should '
                  'live outside of the dir used by `--pants-workdir` to allow for tracking '
                  'subprocesses that outlive the workdir data (e.g. `./pants server`).')
    register('--pants-config-files', advanced=True, type=list,
             default=[get_default_pants_config_file()], help='Paths to Pants config files.')
    # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
    # to set extra config file locations in an initial bootstrap config file.
    register('--config-override', advanced=True, type=list, metavar='<path>',
             removal_version='1.6.0.dev0',
             removal_hint='Use --pants-config-files=<second config file path> instead.',
             help='A second config file, to override pants.ini.')
    register('--pantsrc', advanced=True, type=bool, default=True,
             help='Use pantsrc files.')
    register('--pantsrc-files', advanced=True, type=list, metavar='<path>',
             default=['/etc/pantsrc', '~/.pants.rc'],
             help='Override config with values from these files. '
                  'Later files override earlier ones.')
    register('--pythonpath', advanced=True, type=list,
             help='Add these directories to PYTHONPATH to search for plugins.')
    register('--target-spec-file', type=list, dest='target_spec_files',
             help='Read additional specs from this file, one per line')
    register('--verify-config', type=bool, default=True,
             help='Verify that all config file values correspond to known options.')

    # These logging options are registered in the bootstrap phase so that plugins can log during
    # registration and not so that their values can be interpolated in configs.
    register('-d', '--logdir', advanced=True, metavar='<dir>',
             help='Write logs to files under this directory.')

    # This facilitates bootstrap-time configuration of pantsd usage such that we can
    # determine whether or not to use the Pailgun client to invoke a given pants run
    # without resorting to heavier options parsing.
    register('--enable-pantsd', advanced=True, type=bool, default=False,
             help='Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)')

    # This facilitates use of the v2 engine, sans daemon.
    # TODO: Add removal_version='1.5.0.dev0' before 1.4 lands.
    register('--enable-v2-engine', advanced=True, type=bool, default=True,
             help='Enables use of the v2 engine.')

    # These facilitate configuring the native engine.
    register('--native-engine-version', advanced=True,
             default=pkg_resources.resource_string('pants.engine', 'native_engine_version').strip(),
             help='Native engine version.')
    register('--native-engine-supportdir', advanced=True, default='bin/native-engine',
             help='Find native engine binaries under this dir. Used as part of the path to '
                  'lookup the binary with --binary-util-baseurls and --pants-bootstrapdir.')
    register('--native-engine-visualize-to', advanced=True, default=None, type=dir_option,
             help='A directory to write execution and rule graphs to as `dot` files. The contents '
                  'of the directory will be overwritten if any filenames collide.')
Exemplo n.º 25
0
 def test_set_configdir(self):
   with temporary_file() as temp:
     with environment_as(XDG_CONFIG_HOME=temp.name):
       self.assertEqual(os.path.join(temp.name, 'pants'),  get_pants_configdir())
Exemplo n.º 26
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
        buildroot = get_buildroot()
        default_distdir_name = 'dist'
        default_distdir = os.path.join(buildroot, default_distdir_name)
        default_rel_distdir = '/{}/'.format(default_distdir_name)

        register('-l',
                 '--level',
                 choices=['trace', 'debug', 'info', 'warn'],
                 default='info',
                 recursive=True,
                 help='Set the logging level.')
        register(
            '-q',
            '--quiet',
            type=bool,
            recursive=True,
            daemon=False,
            help=
            'Squelches most console output. NOTE: Some tasks default to behaving quietly: '
            'inverting this option supports making them noisier than they would be otherwise.'
        )

        # Not really needed in bootstrap options, but putting it here means it displays right
        # after -l and -q in help output, which is conveniently contextual.
        register('--colors',
                 type=bool,
                 default=sys.stdout.isatty(),
                 recursive=True,
                 daemon=False,
                 help='Set whether log messages are displayed in color.')

        # Pants code uses this only to verify that we are of the requested version. However
        # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
        # and use it to select the right version.
        # Note that to print the version of the pants instance you're running, use -v, -V or --version.
        register('--pants-version',
                 advanced=True,
                 default=pants_version(),
                 help='Use this pants version.')

        register('--plugins',
                 advanced=True,
                 type=list,
                 help='Load these plugins.')
        register('--plugin-cache-dir',
                 advanced=True,
                 default=os.path.join(get_pants_cachedir(), 'plugins'),
                 help='Cache resolved plugin requirements here.')

        register(
            '--backend-packages',
            advanced=True,
            type=list,
            default=[
                'pants.backend.graph_info',
                'pants.backend.python',
                'pants.backend.jvm',
                'pants.backend.native',
                # TODO: Move into the graph_info backend.
                'pants.rules.core',
                'pants.backend.codegen.antlr.java',
                'pants.backend.codegen.antlr.python',
                'pants.backend.codegen.jaxb',
                'pants.backend.codegen.protobuf.java',
                'pants.backend.codegen.ragel.java',
                'pants.backend.codegen.thrift.java',
                'pants.backend.codegen.thrift.python',
                'pants.backend.codegen.grpcio.python',
                'pants.backend.codegen.wire.java',
                'pants.backend.project_info'
            ],
            help=
            'Load backends from these packages that are already on the path. '
            'Add contrib and custom backends to this list.')

        register('--pants-bootstrapdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_cachedir(),
                 help='Use this dir for global cache.')
        register('--pants-configdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_configdir(),
                 help='Use this dir for global config files.')
        register('--pants-workdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, '.pants.d'),
                 help='Write intermediate output files to this dir.')
        register('--pants-supportdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'build-support'),
                 help='Use support files from this dir.')
        register(
            '--pants-distdir',
            advanced=True,
            metavar='<dir>',
            default=default_distdir,
            help=
            'Write end-product artifacts to this dir. If you modify this path, you '
            'should also update --build-ignore and --pants-ignore to include the '
            'custom dist dir path as well.')
        register(
            '--pants-subprocessdir',
            advanced=True,
            default=os.path.join(buildroot, '.pids'),
            help=
            'The directory to use for tracking subprocess metadata, if any. This should '
            'live outside of the dir used by `--pants-workdir` to allow for tracking '
            'subprocesses that outlive the workdir data (e.g. `./pants server`).'
        )
        register('--pants-config-files',
                 advanced=True,
                 type=list,
                 daemon=False,
                 default=[get_default_pants_config_file()],
                 help='Paths to Pants config files.')
        # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
        # to set extra config file locations in an initial bootstrap config file.
        register('--pantsrc',
                 advanced=True,
                 type=bool,
                 default=True,
                 help='Use pantsrc files.')
        register('--pantsrc-files',
                 advanced=True,
                 type=list,
                 metavar='<path>',
                 daemon=False,
                 default=['/etc/pantsrc', '~/.pants.rc'],
                 help='Override config with values from these files. '
                 'Later files override earlier ones.')
        register(
            '--pythonpath',
            advanced=True,
            type=list,
            help='Add these directories to PYTHONPATH to search for plugins.')
        register('--target-spec-file',
                 type=list,
                 dest='target_spec_files',
                 daemon=False,
                 help='Read additional specs from this file, one per line')
        register(
            '--verify-config',
            type=bool,
            default=True,
            daemon=False,
            advanced=True,
            help=
            'Verify that all config file values correspond to known options.')

        register(
            '--build-ignore',
            advanced=True,
            type=list,
            fromfile=True,
            default=[
                '.*/', default_rel_distdir, 'bower_components/',
                'node_modules/', '*.egg-info/'
            ],
            help='Paths to ignore when identifying BUILD files. '
            'This does not affect any other filesystem operations. '
            'Patterns use the gitignore pattern syntax (https://git-scm.com/docs/gitignore).'
        )
        register(
            '--pants-ignore',
            advanced=True,
            type=list,
            fromfile=True,
            default=['.*/', default_rel_distdir],
            help=
            'Paths to ignore for all filesystem operations performed by pants '
            '(e.g. BUILD file scanning, glob matching, etc). '
            'Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore).'
        )
        register(
            '--glob-expansion-failure',
            type=str,
            choices=GlobMatchErrorBehavior.allowed_values,
            default=GlobMatchErrorBehavior.default_option_value,
            advanced=True,
            help="Raise an exception if any targets declaring source files "
            "fail to match any glob provided in the 'sources' argument.")

        register('--exclude-target-regexp',
                 advanced=True,
                 type=list,
                 default=[],
                 daemon=False,
                 metavar='<regexp>',
                 help='Exclude target roots that match these regexes.')
        register(
            '--subproject-roots',
            type=list,
            advanced=True,
            fromfile=True,
            default=[],
            help=
            'Paths that correspond with build roots for any subproject that this '
            'project depends on.')
        register(
            '--owner-of',
            type=list,
            default=[],
            daemon=False,
            fromfile=True,
            metavar='<path>',
            help='Select the targets that own these files. '
            'This is the third target calculation strategy along with the --changed-* '
            'options and specifying the targets directly. These three types of target '
            'selection are mutually exclusive.')

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register('-d',
                 '--logdir',
                 advanced=True,
                 metavar='<dir>',
                 help='Write logs to files under this directory.')

        # This facilitates bootstrap-time configuration of pantsd usage such that we can
        # determine whether or not to use the Pailgun client to invoke a given pants run
        # without resorting to heavier options parsing.
        register(
            '--enable-pantsd',
            advanced=True,
            type=bool,
            default=False,
            help=
            'Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)'
        )

        # These facilitate configuring the native engine.
        register(
            '--native-engine-visualize-to',
            advanced=True,
            default=None,
            type=dir_option,
            daemon=False,
            help=
            'A directory to write execution and rule graphs to as `dot` files. The contents '
            'of the directory will be overwritten if any filenames collide.')
        register(
            '--print-exception-stacktrace',
            advanced=True,
            type=bool,
            help=
            'Print to console the full exception stack trace if encountered.')

        # BinaryUtil options.
        register(
            '--binaries-baseurls',
            type=list,
            advanced=True,
            default=['https://binaries.pantsbuild.org'],
            help='List of URLs from which binary tools are downloaded. URLs are '
            'searched in order until the requested path is found.')
        register(
            '--binaries-fetch-timeout-secs',
            type=int,
            default=30,
            advanced=True,
            daemon=False,
            help=
            'Timeout in seconds for URL reads when fetching binary tools from the '
            'repos specified by --baseurls.')
        register(
            '--binaries-path-by-id',
            type=dict,
            advanced=True,
            help=
            ("Maps output of uname for a machine to a binary search path: "
             "(sysname, id) -> (os, arch), e.g. {('darwin', '15'): ('mac', '10.11'), "
             "('linux', 'arm32'): ('linux', 'arm32')}."))
        register(
            '--allow-external-binary-tool-downloads',
            type=bool,
            default=True,
            advanced=True,
            help=
            "If False, require BinaryTool subclasses to download their contents from urls "
            "generated from --binaries-baseurls, even if the tool has an external url "
            "generator. This can be necessary if using Pants in an environment which cannot "
            "contact the wider Internet.")

        # Pants Daemon options.
        register('--pantsd-pailgun-host',
                 advanced=True,
                 default='127.0.0.1',
                 help='The host to bind the pants nailgun server to.')
        register(
            '--pantsd-pailgun-port',
            advanced=True,
            type=int,
            default=0,
            help=
            'The port to bind the pants nailgun server to. Defaults to a random port.'
        )
        register('--pantsd-log-dir',
                 advanced=True,
                 default=None,
                 help='The directory to log pantsd output to.')
        register(
            '--pantsd-fs-event-workers',
            advanced=True,
            type=int,
            default=4,
            removal_version='1.14.0.dev2',
            removal_hint=
            'Filesystem events are now handled by a single dedicated thread.',
            help=
            'The number of workers to use for the filesystem event service executor pool.'
        )
        register(
            '--pantsd-invalidation-globs',
            advanced=True,
            type=list,
            fromfile=True,
            default=[],
            help=
            'Filesystem events matching any of these globs will trigger a daemon restart.'
        )

        # Watchman options.
        register('--watchman-version',
                 advanced=True,
                 default='4.9.0-pants1',
                 help='Watchman version.')
        register(
            '--watchman-supportdir',
            advanced=True,
            default='bin/watchman',
            help=
            'Find watchman binaries under this dir. Used as part of the path to lookup '
            'the binary with --binaries-baseurls and --pants-bootstrapdir.')
        register(
            '--watchman-startup-timeout',
            type=float,
            advanced=True,
            default=30.0,
            help=
            'The watchman socket timeout (in seconds) for the initial `watch-project` command. '
            'This may need to be set higher for larger repos due to watchman startup cost.'
        )
        register(
            '--watchman-socket-timeout',
            type=float,
            advanced=True,
            default=0.1,
            help=
            'The watchman client socket timeout in seconds. Setting this to too high a '
            'value can negatively impact the latency of runs forked by pantsd.'
        )
        register(
            '--watchman-socket-path',
            type=str,
            advanced=True,
            default=None,
            help=
            'The path to the watchman UNIX socket. This can be overridden if the default '
            'absolute path length exceeds the maximum allowed by the OS.')

        # This option changes the parser behavior in a fundamental way (which currently invalidates
        # all caches), and needs to be parsed out early, so we make it a bootstrap option.
        register('--build-file-imports',
                 choices=['allow', 'warn', 'error'],
                 default='warn',
                 advanced=True,
                 help='Whether to allow import statements in BUILD files')

        register(
            '--local-store-dir',
            advanced=True,
            help="Directory to use for engine's local file store.",
            # This default is also hard-coded into the engine's rust code in
            # fs::Store::default_path
            default=os.path.expanduser('~/.cache/pants/lmdb_store'))
        register(
            '--remote-store-server',
            advanced=True,
            type=list,
            default=[],
            help=
            'host:port of grpc server to use as remote execution file store.')
        register(
            '--remote-store-thread-count',
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_thread_count,
            help=
            'Thread count to use for the pool that interacts with the remote file store.'
        )
        register(
            '--remote-execution-server',
            advanced=True,
            help=
            'host:port of grpc server to use as remote execution scheduler.')
        register(
            '--remote-store-chunk-bytes',
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_chunk_bytes,
            help=
            'Size in bytes of chunks transferred to/from the remote file store.'
        )
        register(
            '--remote-store-chunk-upload-timeout-seconds',
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.
            remote_store_chunk_upload_timeout_seconds,
            help=
            'Timeout (in seconds) for uploads of individual chunks to the remote file store.'
        )
        register(
            '--remote-store-rpc-retries',
            type=int,
            advanced=True,
            default=DEFAULT_EXECUTION_OPTIONS.remote_store_rpc_retries,
            help=
            'Number of times to retry any RPC to the remote store before giving up.'
        )
        register(
            '--remote-execution-process-cache-namespace',
            advanced=True,
            help="The cache namespace for remote process execution. "
            "Bump this to invalidate every artifact's remote execution. "
            "This is the remote execution equivalent of the legacy cache-key-gen-version "
            "flag.")
        register(
            '--remote-instance-name',
            advanced=True,
            help=
            'Name of the remote execution instance to use. Used for routing within '
            '--remote-execution-server and --remote-store-server.')
        register(
            '--remote-ca-certs-path',
            advanced=True,
            help=
            'Path to a PEM file containing CA certificates used for verifying secure '
            'connections to --remote-execution-server and --remote-store-server. '
            'If not specified, TLS will not be used.')
        register(
            '--remote-oauth-bearer-token-path',
            advanced=True,
            help=
            'Path to a file containing an oauth token to use for grpc connections to '
            '--remote-execution-server and --remote-store-server. If not specified, no '
            'authorization will be performed.')

        # This should eventually deprecate the RunTracker worker count, which is used for legacy cache
        # lookups via CacheSetup in TaskBase.
        register(
            '--process-execution-parallelism',
            type=int,
            default=multiprocessing.cpu_count(),
            advanced=True,
            help=
            'Number of concurrent processes that may be executed either locally and remotely.'
        )
        register(
            '--process-execution-cleanup-local-dirs',
            type=bool,
            default=True,
            advanced=True,
            help=
            'Whether or not to cleanup directories used for local process execution '
            '(primarily useful for e.g. debugging).')
Exemplo n.º 27
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
        buildroot = get_buildroot()

        # Although logging supports the WARN level, its not documented and could conceivably be yanked.
        # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
        # setup a 'WARN' logging level name that maps to 'WARNING'.
        logging.addLevelName(logging.WARNING, 'WARN')
        register('-l',
                 '--level',
                 choices=['debug', 'info', 'warn'],
                 default='info',
                 recursive=True,
                 help='Set the logging level.')
        register('-q',
                 '--quiet',
                 type=bool,
                 recursive=True,
                 help='Squelches most console output.')
        # Not really needed in bootstrap options, but putting it here means it displays right
        # after -l and -q in help output, which is conveniently contextual.
        register('--colors',
                 type=bool,
                 default=sys.stdout.isatty(),
                 recursive=True,
                 help='Set whether log messages are displayed in color.')

        # Pants code uses this only to verify that we are of the requested version. However
        # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
        # and use it to select the right version.
        # Note that to print the version of the pants instance you're running, use -v, -V or --version.
        register('--pants-version',
                 advanced=True,
                 default=pants_version(),
                 help='Use this pants version.')

        register('--plugins',
                 advanced=True,
                 type=list,
                 help='Load these plugins.')
        register('--plugin-cache-dir',
                 advanced=True,
                 default=os.path.join(get_pants_cachedir(), 'plugins'),
                 help='Cache resolved plugin requirements here.')

        register(
            '--backend-packages',
            advanced=True,
            type=list,
            default=[
                'pants.backend.graph_info', 'pants.backend.python',
                'pants.backend.jvm', 'pants.backend.codegen.antlr.java',
                'pants.backend.codegen.antlr.python',
                'pants.backend.codegen.jaxb',
                'pants.backend.codegen.protobuf.java',
                'pants.backend.codegen.ragel.java',
                'pants.backend.codegen.thrift.java',
                'pants.backend.codegen.thrift.python',
                'pants.backend.codegen.wire.java', 'pants.backend.project_info'
            ],
            help=
            'Load backends from these packages that are already on the path. '
            'Add contrib and custom backends to this list.')

        register('--pants-bootstrapdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_cachedir(),
                 help='Use this dir for global cache.')
        register('--pants-configdir',
                 advanced=True,
                 metavar='<dir>',
                 default=get_pants_configdir(),
                 help='Use this dir for global config files.')
        register('--pants-workdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, '.pants.d'),
                 help='Write intermediate output files to this dir.')
        register('--pants-supportdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'build-support'),
                 help='Use support files from this dir.')
        register('--pants-distdir',
                 advanced=True,
                 metavar='<dir>',
                 default=os.path.join(buildroot, 'dist'),
                 help='Write end-product artifacts to this dir.')
        register(
            '--pants-subprocessdir',
            advanced=True,
            default=os.path.join(buildroot, '.pids'),
            help=
            'The directory to use for tracking subprocess metadata, if any. This should '
            'live outside of the dir used by `--pants-workdir` to allow for tracking '
            'subprocesses that outlive the workdir data (e.g. `./pants server`).'
        )
        register('--pants-config-files',
                 advanced=True,
                 type=list,
                 default=[get_default_pants_config_file()],
                 help='Paths to Pants config files.')
        # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
        # to set extra config file locations in an initial bootstrap config file.
        register('--config-override',
                 advanced=True,
                 type=list,
                 metavar='<path>',
                 removal_version='1.6.0.dev0',
                 removal_hint=
                 'Use --pants-config-files=<second config file path> instead.',
                 help='A second config file, to override pants.ini.')
        register('--pantsrc',
                 advanced=True,
                 type=bool,
                 default=True,
                 help='Use pantsrc files.')
        register('--pantsrc-files',
                 advanced=True,
                 type=list,
                 metavar='<path>',
                 default=['/etc/pantsrc', '~/.pants.rc'],
                 help='Override config with values from these files. '
                 'Later files override earlier ones.')
        register(
            '--pythonpath',
            advanced=True,
            type=list,
            help='Add these directories to PYTHONPATH to search for plugins.')
        register('--target-spec-file',
                 type=list,
                 dest='target_spec_files',
                 help='Read additional specs from this file, one per line')
        register(
            '--verify-config',
            type=bool,
            default=True,
            help=
            'Verify that all config file values correspond to known options.')

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register('-d',
                 '--logdir',
                 advanced=True,
                 metavar='<dir>',
                 help='Write logs to files under this directory.')

        # This facilitates bootstrap-time configuration of pantsd usage such that we can
        # determine whether or not to use the Pailgun client to invoke a given pants run
        # without resorting to heavier options parsing.
        register(
            '--enable-pantsd',
            advanced=True,
            type=bool,
            default=False,
            help=
            'Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)'
        )

        # This facilitates use of the v2 engine, sans daemon.
        # TODO: Add removal_version='1.5.0.dev0' before 1.4 lands.
        register('--enable-v2-engine',
                 advanced=True,
                 type=bool,
                 default=True,
                 help='Enables use of the v2 engine.')

        # These facilitate configuring the native engine.
        register('--native-engine-version',
                 advanced=True,
                 default=pkg_resources.resource_string(
                     'pants.engine', 'native_engine_version').strip(),
                 help='Native engine version.')
        register(
            '--native-engine-supportdir',
            advanced=True,
            default='bin/native-engine',
            help=
            'Find native engine binaries under this dir. Used as part of the path to '
            'lookup the binary with --binary-util-baseurls and --pants-bootstrapdir.'
        )
        register(
            '--native-engine-visualize-to',
            advanced=True,
            default=None,
            type=dir_option,
            help=
            'A directory to write execution and rule graphs to as `dot` files. The contents '
            'of the directory will be overwritten if any filenames collide.')

        # BinaryUtil options.
        register(
            '--binaries-baseurls',
            type=list,
            advanced=True,
            default=['https://binaries.pantsbuild.org'],
            help=
            'List of URLs from which binary tools are downloaded. URLs are searched in '
            'order until the requested path is found.')
        register(
            '--binaries-fetch-timeout-secs',
            type=int,
            default=30,
            advanced=True,
            help=
            'Timeout in seconds for URL reads when fetching binary tools from the '
            'repos specified by --baseurls.')
        register(
            '--binaries-path-by-id',
            type=dict,
            advanced=True,
            help=
            ('Maps output of uname for a machine to a binary search path. e.g. '
             '{("darwin", "15"): ["mac", "10.11"]), ("linux", "arm32"): ["linux", "arm32"]}'
             ))
Exemplo n.º 28
0
  def register_bootstrap_options(cls, register):
    """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
    buildroot = get_buildroot()
    default_distdir_name = 'dist'
    default_distdir = os.path.join(buildroot, default_distdir_name)
    default_rel_distdir = '/{}/'.format(default_distdir_name)

    # Although logging supports the WARN level, its not documented and could conceivably be yanked.
    # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
    # setup a 'WARN' logging level name that maps to 'WARNING'.
    logging.addLevelName(logging.WARNING, 'WARN')
    register('-l', '--level', choices=['debug', 'info', 'warn'], default='info', recursive=True,
             help='Set the logging level.')
    register('-q', '--quiet', type=bool, recursive=True, daemon=False,
             help='Squelches most console output. NOTE: Some tasks default to behaving quietly: '
                  'inverting this option supports making them noisier than they would be otherwise.')
    # Not really needed in bootstrap options, but putting it here means it displays right
    # after -l and -q in help output, which is conveniently contextual.
    register('--colors', type=bool, default=sys.stdout.isatty(), recursive=True, daemon=False,
             help='Set whether log messages are displayed in color.')

    # Pants code uses this only to verify that we are of the requested version. However
    # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
    # and use it to select the right version.
    # Note that to print the version of the pants instance you're running, use -v, -V or --version.
    register('--pants-version', advanced=True, default=pants_version(),
             help='Use this pants version.')

    register('--plugins', advanced=True, type=list, help='Load these plugins.')
    register('--plugin-cache-dir', advanced=True,
             default=os.path.join(get_pants_cachedir(), 'plugins'),
             help='Cache resolved plugin requirements here.')

    register('--backend-packages', advanced=True, type=list,
             default=['pants.backend.graph_info',
                      'pants.backend.python',
                      'pants.backend.jvm',
                      'pants.backend.native',
                      'pants.backend.codegen.antlr.java',
                      'pants.backend.codegen.antlr.python',
                      'pants.backend.codegen.jaxb',
                      'pants.backend.codegen.protobuf.java',
                      'pants.backend.codegen.ragel.java',
                      'pants.backend.codegen.thrift.java',
                      'pants.backend.codegen.thrift.python',
                      'pants.backend.codegen.wire.java',
                      'pants.backend.project_info'],
             help='Load backends from these packages that are already on the path. '
                  'Add contrib and custom backends to this list.')

    register('--pants-bootstrapdir', advanced=True, metavar='<dir>', default=get_pants_cachedir(),
             help='Use this dir for global cache.')
    register('--pants-configdir', advanced=True, metavar='<dir>', default=get_pants_configdir(),
             help='Use this dir for global config files.')
    register('--pants-workdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, '.pants.d'),
             help='Write intermediate output files to this dir.')
    register('--pants-supportdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'build-support'),
             help='Use support files from this dir.')
    register('--pants-distdir', advanced=True, metavar='<dir>',
             default=default_distdir,
             help='Write end-product artifacts to this dir. If you modify this path, you '
                  'should also update --build-ignore and --pants-ignore to include the '
                  'custom dist dir path as well.')
    register('--pants-subprocessdir', advanced=True, default=os.path.join(buildroot, '.pids'),
             help='The directory to use for tracking subprocess metadata, if any. This should '
                  'live outside of the dir used by `--pants-workdir` to allow for tracking '
                  'subprocesses that outlive the workdir data (e.g. `./pants server`).')
    register('--pants-config-files', advanced=True, type=list, daemon=False,
             default=[get_default_pants_config_file()], help='Paths to Pants config files.')
    # TODO: Deprecate the --pantsrc/--pantsrc-files options?  This would require being able
    # to set extra config file locations in an initial bootstrap config file.
    register('--pantsrc', advanced=True, type=bool, default=True,
             help='Use pantsrc files.')
    register('--pantsrc-files', advanced=True, type=list, metavar='<path>', daemon=False,
             default=['/etc/pantsrc', '~/.pants.rc'],
             help='Override config with values from these files. '
                  'Later files override earlier ones.')
    register('--pythonpath', advanced=True, type=list,
             help='Add these directories to PYTHONPATH to search for plugins.')
    register('--target-spec-file', type=list, dest='target_spec_files', daemon=False,
             help='Read additional specs from this file, one per line')
    register('--verify-config', type=bool, default=True, daemon=False,
             help='Verify that all config file values correspond to known options.')

    register('--build-ignore', advanced=True, type=list, fromfile=True,
             default=['.*/', default_rel_distdir, 'bower_components/',
                      'node_modules/', '*.egg-info/'],
             help='Paths to ignore when identifying BUILD files. '
                  'This does not affect any other filesystem operations. '
                  'Patterns use the gitignore pattern syntax (https://git-scm.com/docs/gitignore).')
    register('--pants-ignore', advanced=True, type=list, fromfile=True,
             default=['.*/', default_rel_distdir],
             help='Paths to ignore for all filesystem operations performed by pants '
                  '(e.g. BUILD file scanning, glob matching, etc). '
                  'Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore).')
    register('--glob-expansion-failure', type=str,
             choices=GlobMatchErrorBehavior.allowed_values,
             default=GlobMatchErrorBehavior.default_option_value,
             help="Raise an exception if any targets declaring source files "
                  "fail to match any glob provided in the 'sources' argument.")

    register('--exclude-target-regexp', advanced=True, type=list, default=[], daemon=False,
             metavar='<regexp>', help='Exclude target roots that match these regexes.')
    register('--subproject-roots', type=list, advanced=True, fromfile=True, default=[],
             help='Paths that correspond with build roots for any subproject that this '
                  'project depends on.')
    register('--owner-of', type=list, default=[], metavar='<path>',
             help='Select the targets that own these files. '
                  'This is the third target calculation strategy along with the --changed '
                  'options and specifying the targets directly. These three types of target '
                  'selection are mutually exclusive.')

    # These logging options are registered in the bootstrap phase so that plugins can log during
    # registration and not so that their values can be interpolated in configs.
    register('-d', '--logdir', advanced=True, metavar='<dir>',
             help='Write logs to files under this directory.')

    # This facilitates bootstrap-time configuration of pantsd usage such that we can
    # determine whether or not to use the Pailgun client to invoke a given pants run
    # without resorting to heavier options parsing.
    register('--enable-pantsd', advanced=True, type=bool, default=False,
             help='Enables use of the pants daemon (and implicitly, the v2 engine). (Beta)')

    # These facilitate configuring the native engine.
    register('--native-engine-visualize-to', advanced=True, default=None, type=dir_option, daemon=False,
             help='A directory to write execution and rule graphs to as `dot` files. The contents '
                  'of the directory will be overwritten if any filenames collide.')
    register('--print-exception-stacktrace', advanced=True, type=bool,
             help='Print to console the full exception stack trace if encountered.')

    # BinaryUtil options.
    register('--binaries-baseurls', type=list, advanced=True,
             default=['https://binaries.pantsbuild.org'],
             help='List of URLs from which binary tools are downloaded. URLs are '
                  'searched in order until the requested path is found.')
    register('--binaries-fetch-timeout-secs', type=int, default=30, advanced=True, daemon=False,
             help='Timeout in seconds for URL reads when fetching binary tools from the '
                  'repos specified by --baseurls.')
    register('--binaries-path-by-id', type=dict, advanced=True,
             help=("Maps output of uname for a machine to a binary search path: "
                   "(sysname, id) -> (os, arch), e.g. {('darwin', '15'): ('mac', '10.11'), "
                   "('linux', 'arm32'): ('linux', 'arm32')}."))
    register('--allow-external-binary-tool-downloads', type=bool, default=True, advanced=True,
             help="If False, require BinaryTool subclasses to download their contents from urls "
                  "generated from --binaries-baseurls, even if the tool has an external url "
                  "generator. This can be necessary if using Pants in an environment which cannot "
                  "contact the wider Internet.")

    # Pants Daemon options.
    register('--pantsd-pailgun-host', advanced=True, default='127.0.0.1',
             help='The host to bind the pants nailgun server to.')
    register('--pantsd-pailgun-port', advanced=True, type=int, default=0,
             help='The port to bind the pants nailgun server to. Defaults to a random port.')
    register('--pantsd-log-dir', advanced=True, default=None,
             help='The directory to log pantsd output to.')
    register('--pantsd-fs-event-workers', advanced=True, type=int, default=4,
             help='The number of workers to use for the filesystem event service executor pool.')
    register('--pantsd-invalidation-globs', advanced=True, type=list, fromfile=True, default=[],
             help='Filesystem events matching any of these globs will trigger a daemon restart.')

    # Watchman options.
    register('--watchman-version', advanced=True, default='4.9.0-pants1', help='Watchman version.')
    register('--watchman-supportdir', advanced=True, default='bin/watchman',
             help='Find watchman binaries under this dir. Used as part of the path to lookup '
                  'the binary with --binaries-baseurls and --pants-bootstrapdir.')
    register('--watchman-startup-timeout', type=float, advanced=True, default=30.0,
             help='The watchman socket timeout (in seconds) for the initial `watch-project` command. '
                  'This may need to be set higher for larger repos due to watchman startup cost.')
    register('--watchman-socket-timeout', type=float, advanced=True, default=5.0,
             help='The watchman client socket timeout in seconds.')
    register('--watchman-socket-path', type=str, advanced=True, default=None,
             help='The path to the watchman UNIX socket. This can be overridden if the default '
                  'absolute path length exceeds the maximum allowed by the OS.')

    # This option changes the parser behavior in a fundamental way (which currently invalidates
    # all caches), and needs to be parsed out early, so we make it a bootstrap option.
    register('--build-file-imports', choices=['allow', 'warn', 'error'], default='warn',
      help='Whether to allow import statements in BUILD files')

    register('--remote-store-server',
             help='host:port of grpc server to use as remote execution file store')
    register('--remote-execution-server',
             help='host:port of grpc server to use as remote execution scheduler')
Exemplo n.º 29
0
  def register_bootstrap_options(cls, register):
    """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
    buildroot = get_buildroot()

    # Although logging supports the WARN level, its not documented and could conceivably be yanked.
    # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
    # setup a 'WARN' logging level name that maps to 'WARNING'.
    logging.addLevelName(logging.WARNING, 'WARN')
    register('-l', '--level', choices=['debug', 'info', 'warn'], default='info', recursive=True,
             help='Set the logging level.')
    register('-q', '--quiet', action='store_true',
             help='Squelches all console output apart from errors.')
    # Not really needed in bootstrap options, but putting it here means it displays right
    # after -l and -q in help output, which is conveniently contextual.
    register('--colors', action='store_true', default=True, recursive=True,
             help='Set whether log messages are displayed in color.')

    # NB: Right now this option is a placeholder that is unused within pants itself except when
    # specified on the command line to print the OSS pants version.  Both the IntelliJ Pants plugin
    # and the pantsbuild/setup bootstrap script grep for pants_version though so this option
    # registration serves in part as documentation of the dependency.
    # TODO(John Sirois): Move pantsbuild.pants bootstrapping into pants itself and have it use this
    # version option directly.
    register('-V', '--pants-version', '--version',  # NB: pants_version is the 1st long option
                                                    # since that's the one read from pants.ini;
                                                    # the version form only works from the CLI.
             nargs='?',  # Allows using the flag with no args on the CLI to print version as well
                         # as setting the version in pants.ini
             default=pants_version(),  # Displays the current version correctly in `./pants -h`.
             const=pants_version(),  # Displays the current version via `./pants -V`.
             help="Prints pants' version number and exits.")

    register('--plugins', advanced=True, type=list_option, help='Load these plugins.')
    register('--plugin-cache-dir', advanced=True,
             default=os.path.join(get_pants_cachedir(), 'plugins'),
             help='Cache resolved plugin requirements here.')

    register('--backend-packages', advanced=True, type=list_option,
             help='Load backends from these packages that are already on the path.')

    register('--pants-bootstrapdir', advanced=True, metavar='<dir>', default=get_pants_cachedir(),
             help='Use this dir for global cache.')
    register('--pants-configdir', advanced=True, metavar='<dir>', default=get_pants_configdir(),
             help='Use this dir for global config files.')
    register('--pants-workdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, '.pants.d'),
             help='Write intermediate output files to this dir.')
    register('--pants-supportdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'build-support'),
             help='Use support files from this dir.')
    register('--pants-distdir', advanced=True, metavar='<dir>',
             default=os.path.join(buildroot, 'dist'),
             help='Write end-product artifacts to this dir.')
    register('--config-override', advanced=True, action='append', metavar='<path>',
             help='A second config file, to override pants.ini.')
    register('--pantsrc', advanced=True, action='store_true', default=True,
             help='Use pantsrc files.')
    register('--pantsrc-files', advanced=True, action='append', metavar='<path>',
             default=['/etc/pantsrc', '~/.pants.rc'],
             help='Override config with values from these files. '
                  'Later files override earlier ones.')
    register('--pythonpath', advanced=True, action='append',
             help='Add these directories to PYTHONPATH to search for plugins.')
    register('--target-spec-file', action='append', dest='target_spec_files',
             help='Read additional specs from this file, one per line')

    # These logging options are registered in the bootstrap phase so that plugins can log during
    # registration and not so that their values can be interpolated in configs.
    register('-d', '--logdir', advanced=True, metavar='<dir>',
             help='Write logs to files under this directory.')
Exemplo n.º 30
0
    def register_bootstrap_options(cls, register):
        """Register bootstrap options.

    "Bootstrap options" are a small set of options whose values are useful when registering other
    options. Therefore we must bootstrap them early, before other options are registered, let
    alone parsed.

    Bootstrap option values can be interpolated into the config file, and can be referenced
    programatically in registration code, e.g., as register.bootstrap.pants_workdir.

    Note that regular code can also access these options as normal global-scope options. Their
    status as "bootstrap options" is only pertinent during option registration.
    """
        buildroot = get_buildroot()

        # Although logging supports the WARN level, its not documented and could conceivably be yanked.
        # Since pants has supported 'warn' since inception, leave the 'warn' choice as-is but explicitly
        # setup a 'WARN' logging level name that maps to 'WARNING'.
        logging.addLevelName(logging.WARNING, "WARN")
        register(
            "-l",
            "--level",
            choices=["debug", "info", "warn"],
            default="info",
            recursive=True,
            help="Set the logging level.",
        )
        register("-q", "--quiet", action="store_true", recursive=True, help="Squelches most console output.")
        # Not really needed in bootstrap options, but putting it here means it displays right
        # after -l and -q in help output, which is conveniently contextual.
        register(
            "--colors",
            action="store_true",
            default=True,
            recursive=True,
            help="Set whether log messages are displayed in color.",
        )

        # Pants code uses this only to verify that we are of the requested version. However
        # setup scripts, runner scripts, IDE plugins, etc., may grep this out of pants.ini
        # and use it to select the right version.
        # Note that to print the version of the pants instance you're running, use -v, -V or --version.
        register("--pants-version", advanced=True, default=pants_version(), help="Use this pants version.")

        register("--plugins", advanced=True, type=list_option, help="Load these plugins.")
        register(
            "--plugin-cache-dir",
            advanced=True,
            default=os.path.join(get_pants_cachedir(), "plugins"),
            help="Cache resolved plugin requirements here.",
        )

        register(
            "--backend-packages",
            advanced=True,
            type=list_option,
            help="Load backends from these packages that are already on the path.",
        )

        register(
            "--pants-bootstrapdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_cachedir(),
            help="Use this dir for global cache.",
        )
        register(
            "--pants-configdir",
            advanced=True,
            metavar="<dir>",
            default=get_pants_configdir(),
            help="Use this dir for global config files.",
        )
        register(
            "--pants-workdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, ".pants.d"),
            help="Write intermediate output files to this dir.",
        )
        register(
            "--pants-supportdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "build-support"),
            help="Use support files from this dir.",
        )
        register(
            "--pants-distdir",
            advanced=True,
            metavar="<dir>",
            default=os.path.join(buildroot, "dist"),
            help="Write end-product artifacts to this dir.",
        )
        register(
            "--config-override",
            advanced=True,
            action="append",
            metavar="<path>",
            help="A second config file, to override pants.ini.",
        )
        register("--pantsrc", advanced=True, action="store_true", default=True, help="Use pantsrc files.")
        register(
            "--pantsrc-files",
            advanced=True,
            action="append",
            metavar="<path>",
            default=["/etc/pantsrc", "~/.pants.rc"],
            help="Override config with values from these files. " "Later files override earlier ones.",
        )
        register(
            "--pythonpath",
            advanced=True,
            action="append",
            help="Add these directories to PYTHONPATH to search for plugins.",
        )
        register(
            "--target-spec-file",
            action="append",
            dest="target_spec_files",
            help="Read additional specs from this file, one per line",
        )

        # These logging options are registered in the bootstrap phase so that plugins can log during
        # registration and not so that their values can be interpolated in configs.
        register("-d", "--logdir", advanced=True, metavar="<dir>", help="Write logs to files under this directory.")

        # This facilitates bootstrap-time configuration of pantsd usage such that we can
        # determine whether or not to use the Pailgun client to invoke a given pants run
        # without resorting to heavier options parsing.
        register(
            "--enable-pantsd",
            advanced=True,
            action="store_true",
            default=False,
            help="Enables use of the pants daemon. (Beta)",
        )