Exemplo n.º 1
0
 def returncode(self) -> int:
     warn_or_error(
         removal_version="2.1.0.dev0",
         deprecated_entity_description="the property PantsResult.returncode",
         hint="Use `PantsResult.exit_code` instead.",
     )
     return self.exit_code
Exemplo n.º 2
0
    def generate_lockfiles_with_pex(self) -> bool:
        """Else, generate with Poetry."""
        if self.options.is_default("lockfile_generator"):
            warn_or_error(
                "2.12.0.dev0",
                "`[python].lockfile_generator` defaulting to 'poetry'",
                softwrap(f"""
                    In Pants 2.12, Pants will default to using Pex to generate lockfiles
                    with the `generate-lockfiles` goal, rather than Poetry. Run
                    `{bin_name()} help-advanced python` for more information on the benefits and
                    possible issues with switching to Pex.

                    To keep using Poetry, set `[python].lockfile_generator = 'poetry'` in
                    pants.toml. To try Pex, set to 'pex'.

                    Note that you can incrementally switch to Pex lockfiles if you want to reduce
                    risk while migrating. The option `[python].lockfile_generator` only impacts
                    how Pants generates new lockfiles; you can continue to use
                    requirements.txt-style lockfiles (i.e. those generated by Poetry) even if
                    new lockfiles are generated in Pex's JSON format. For example, you can run
                    `{bin_name()} --python-lockfile-generator=pex generate-lockfiles
                    --resolve=isort` to only regenerate the isort lockfile.
                    """),
            )

        return self._lockfile_generator == LockfileGenerator.PEX
Exemplo n.º 3
0
 def stderr_data(self) -> str:
     warn_or_error(
         removal_version="2.1.0.dev0",
         deprecated_entity_description="the property PantsResult.stderr_data",
         hint="Use `PantsResult.stderr` instead.",
     )
     return self.stderr
Exemplo n.º 4
0
    def test_deprecation_start_period(self):
        with self.assertRaises(CodeRemovedError):
            warn_or_error(
                removal_version=_FAKE_CUR_VERSION,
                deprecated_entity_description="dummy",
                deprecation_start_version="1.0.0.dev0",
            )

        with self.warnings_catcher() as w:
            warn_or_error(
                removal_version="999.999.999.dev999",
                deprecated_entity_description="dummy",
                deprecation_start_version=_FAKE_CUR_VERSION,
            )
            self.assertWarning(
                w,
                DeprecationWarning,
                "DEPRECATED: dummy will be removed in version 999.999.999.dev999.",
            )

        self.assertIsNone(
            warn_or_error(
                removal_version="999.999.999.dev999",
                deprecated_entity_description="dummy",
                deprecation_start_version="500.0.0.dev0",
            ))
 def run_pants(
     self,
     command: Command,
     *,
     config: Optional[Mapping] = None,
     extra_env: Optional[Mapping[str, str]] = None,
     stdin_data: Optional[Union[bytes, str]] = None,
     **kwargs: Any,
 ) -> PantsResult:
     warn_or_error(
         removal_version="2.1.0.dev0",
         deprecated_entity_description="PantsIntegrationTest.run_pants()",
         hint=
         ("Use the top-level function `run_pants()`. `PantsIntegrationTest` is deprecated."
          ),
     )
     return run_pants(
         command,
         hermetic=self.hermetic,
         use_pantsd=self.use_pantsd,
         config=config,
         extra_env=extra_env,
         stdin_data=stdin_data,
         **kwargs,
     )
Exemplo n.º 6
0
    def compute_dependency_specs(cls, kwargs=None, payload=None):
        """Given either pre-Target.__init__() kwargs or a post-Target.__init__() payload, compute the
    full set of dependency specs in the same vein as the prior `traversable_dependency_specs`.

    N.B. This is a temporary bridge to span the gap between v2 "Fields" products vs v1 `BuildGraph`
    `Target` object representations. See:

      https://github.com/pantsbuild/pants/issues/3560
      https://github.com/pantsbuild/pants/issues/3561

    :API: public

    :param dict kwargs: The pre-Target.__init__() kwargs dict.
    :param Payload payload: The post-Target.__init__() Payload object.
    :yields: AddressSpec strings representing dependencies of this target.
    """
        warn_or_error(
            removal_version="1.27.0.dev0",
            deprecated_entity_description="Target.compute_dependency_specs()",
            hint=
            "Use `Target.compute_dependency_address_specs()` instead. The API is the same as "
            "before. This change is to prepare for Pants eventually supporting file system specs, "
            "e.g. `./pants cloc foo.py`. In preparation, we renamed `Spec` to `AddressSpec`."
        )
        cls.compute_dependency_address_specs(kwargs=kwargs, payload=payload)
 def run_pants_with_workdir_without_waiting(
     self,
     command: Command,
     *,
     workdir: str,
     config: Optional[Mapping] = None,
     extra_env: Optional[Mapping[str, str]] = None,
     print_exception_stacktrace: bool = True,
     **kwargs: Any,
 ) -> PantsJoinHandle:
     warn_or_error(
         removal_version="2.1.0.dev0",
         deprecated_entity_description=
         "PantsIntegrationTest.run_pants_with_workdir_without_waiting()",
         hint=
         ("Use the top-level function `run_pants_with_workdir_without_waiting()`. "
          "`PantsIntegrationTest` is deprecated."),
     )
     return run_pants_with_workdir_without_waiting(
         command,
         workdir=workdir,
         hermetic=self.hermetic,
         use_pantsd=self.use_pantsd,
         config=config,
         extra_env=extra_env,
         print_exception_stacktrace=print_exception_stacktrace,
         **kwargs,
     )
 def run_pants_with_workdir(
     self,
     command: Command,
     *,
     workdir: str,
     config: Optional[Mapping] = None,
     stdin_data: Optional[Union[bytes, str]] = None,
     tee_output: bool = False,
     **kwargs: Any,
 ) -> PantsResult:
     warn_or_error(
         removal_version="2.1.0.dev0",
         deprecated_entity_description=
         "PantsIntegrationTest.run_pants_with_workdir()",
         hint=("Use the top-level function `run_pants_with_workdir()`. "
               "`PantsIntegrationTest` is deprecated."),
     )
     return run_pants_with_workdir(
         command,
         workdir=workdir,
         hermetic=self.hermetic,
         use_pantsd=self.use_pantsd,
         config=config,
         stdin_data=stdin_data,
         tee_output=tee_output,
         **kwargs,
     )
Exemplo n.º 9
0
def warn_deprecated_target_type(tgt_type: type[Target]) -> None:
    assert tgt_type.deprecated_alias_removal_version is not None
    warn_or_error(
        removal_version=tgt_type.deprecated_alias_removal_version,
        entity=f"using `filter --target-type={tgt_type.deprecated_alias}`",
        hint=f"Use `filter --target-type={tgt_type.alias}` instead.",
    )
Exemplo n.º 10
0
 def __init__(self, *args, **kwargs):
     super(DeprecatedJavaTests, self).__init__(*args, **kwargs)
     warn_or_error(
         "1.4.0",
         "java_tests(...) target type",
         "Use junit_tests(...) instead for target {}.".format(self.address.spec),
     )
Exemplo n.º 11
0
    def __init__(self, payload=None, packages=None, **kwargs):
        """
    :param list packages: the `ConanRequirement`s to resolve into a `packaged_native_library()` target.
    """
        payload = payload or Payload()

        try:
            assert_list(packages,
                        key_arg='packages',
                        expected_type=ConanRequirement,
                        raise_type=self._DeprecatedStringPackage)
        except self._DeprecatedStringPackage as e:
            warn_or_error(
                '1.16.0.dev1',
                'Raw strings as conan package descriptors',
                hint='Use conan_requirement(...) instead! Error was: {}'.
                format(str(e)),
                stacklevel=2,
                context=0)
            packages = [
                ConanRequirement(s)
                if not isinstance(s, ConanRequirement) else s for s in packages
            ]

        payload.add_fields({
            'packages': ConanRequirementSetField(packages),
        })
        super(ExternalNativeLibrary, self).__init__(payload=payload, **kwargs)
Exemplo n.º 12
0
def filter_targets(
    addresses: Addresses, filter_subsystem: FilterSubsystem, console: Console
) -> FilterGoal:
    warn_or_error(
        "2.14.0.dev0",
        "using `filter` as a goal",
        softwrap(
            f"""
            You can now specify `filter` arguments with any goal, e.g. `{bin_name()}
            --filter-target-type=python_test test ::`.

            This means that the `filter` goal is now identical to `list`. For example, rather than
            `{bin_name()} filter --target-type=python_test ::`, use
            `{bin_name()} --filter-target-type=python_test list ::`.

            Often, the `filter` goal was combined with `xargs` to build pipelines of commands. You
            can often now simplify those to a single command. Rather than `{bin_name()} filter
            --target-type=python_test filter :: | xargs {bin_name()} test`, simply use
            `{bin_name()} --filter-target-type=python_test test ::`.
            """
        ),
    )
    # `SpecsFilter` will have already filtered for us. There isn't much reason for this goal to
    # exist anymore.
    with filter_subsystem.line_oriented(console) as print_stdout:
        for address in sorted(addresses):
            print_stdout(address.spec)
    return FilterGoal(exit_code=0)
Exemplo n.º 13
0
 def _check_deprecated(self, dest, kwargs):
   """Checks option for deprecation and issues a warning/error if necessary."""
   removal_version = kwargs.get('removal_version', None)
   if removal_version is not None:
     warn_or_error(removal_version,
                   "option '{}' in {}".format(dest, self._scope_str()),
                   kwargs.get('removal_hint', ''),
                   stacklevel=9999)  # Out of range stacklevel to suppress printing src line.
Exemplo n.º 14
0
 def _compute_dependency_specs_warn_or_error(cls):
   warn_or_error(
     removal_version="1.27.0.dev0",
     deprecated_entity_description="Target.compute_dependency_specs()",
     hint="Use `Target.compute_dependency_address_specs()` instead. The API is the same as "
          "before. This change is to prepare for Pants eventually supporting file system specs, "
          "e.g. `./pants cloc foo.py`. In preparation, we renamed `Spec` to `AddressSpec`."
   )
Exemplo n.º 15
0
def test_deprecation_start_version_validation() -> None:
    with pytest.raises(BadSemanticVersionError):
        warn_or_error(removal_version="1.0.0.dev0", entity="fake", hint=None, start_version="1.a.0")

    with pytest.raises(InvalidSemanticVersionOrderingError):
        warn_or_error(
            removal_version="0.0.0.dev0", entity="fake", hint=None, start_version="1.0.0.dev0"
        )
Exemplo n.º 16
0
 def _check_deprecated(self, dest, kwargs):
   """Checks option for deprecation and issues a warning/error if necessary."""
   removal_version = kwargs.get('removal_version', None)
   if removal_version is not None:
     warn_or_error(removal_version,
                   "option '{}' in {}".format(dest, self._scope_str()),
                   kwargs.get('removal_hint', ''),
                   stacklevel=9999)  # Out of range stacklevel to suppress printing src line.
Exemplo n.º 17
0
    def target_specs(self):
        """The targets to operate on.

    :API: public
    """
        warn_or_error('1.25.0.dev2', '.target_specs',
                      'Use .positional_args instead')
        return self._positional_args
Exemplo n.º 18
0
    def for_scope(self, scope, inherit_from_enclosing_scope=True):
        """Return the option values for the given scope.

    Values are attributes of the returned object, e.g., options.foo.
    Computed lazily per scope.

    :API: public
    """
        # Short-circuit, if already computed.
        if scope in self._values_by_scope:
            return self._values_by_scope[scope]

        # First get enclosing scope's option values, if any.
        if scope == GLOBAL_SCOPE or not inherit_from_enclosing_scope:
            values = OptionValueContainer()
        else:
            values = copy.copy(self.for_scope(enclosing_scope(scope)))

        # Now add our values.
        flags_in_scope = self._scope_to_flags.get(scope, [])
        self._parser_hierarchy.get_parser_by_scope(scope).parse_args(
            flags_in_scope, values)

        # If we're the new name of a deprecated scope, also get values from that scope.
        deprecated_scope = self.known_scope_to_info[scope].deprecated_scope
        # Note that deprecated_scope and scope share the same Optionable class, so deprecated_scope's
        # Optionable has a deprecated_options_scope equal to deprecated_scope. Therefore we must
        # check that scope != deprecated_scope to prevent infinite recursion.
        if deprecated_scope is not None and scope != deprecated_scope:
            # Do the deprecation check only on keys that were explicitly set on the deprecated scope
            # (and not on its enclosing scopes).
            explicit_keys = self.for_scope(
                deprecated_scope,
                inherit_from_enclosing_scope=False).get_explicit_keys()
            if explicit_keys:
                warn_or_error(
                    self.known_scope_to_info[scope].
                    deprecated_scope_removal_version,
                    'scope {}'.format(deprecated_scope),
                    'Use scope {} instead (options: {})'.format(
                        scope, ', '.join(explicit_keys)))
                # Update our values with those of the deprecated scope (now including values inherited
                # from its enclosing scope).
                # Note that a deprecated val will take precedence over a val of equal rank.
                # This makes the code a bit neater.
                values.update(self.for_scope(deprecated_scope))

        # Record the value derivation.
        for option in values:
            self._option_tracker.record_option(scope=scope,
                                               option=option,
                                               value=values[option],
                                               rank=values.get_rank(option))

        # Cache the values.
        self._values_by_scope[scope] = values

        return values
Exemplo n.º 19
0
 def __init__(self, addresses, rel_path):
     self.addresses = addresses
     self.rel_path = rel_path
     warn_or_error(
         removal_version="1.31.0.dev0",
         deprecated_entity_description="build_graph.address.Addresses",
         hint=
         "To store a collection of Addresses, use engine.addresses.Addresses instead.",
     )
Exemplo n.º 20
0
def warn_deprecated_field_type(field_type: type[Field]) -> None:
    assert field_type.deprecated_alias_removal_version is not None
    warn_or_error(
        removal_version=field_type.deprecated_alias_removal_version,
        entity=f"the field name {field_type.deprecated_alias}",
        hint=
        (f"Instead, use `{field_type.alias}`, which behaves the same. Run `{bin_name()} "
         "update-build-files` to automatically fix your BUILD files."),
    )
Exemplo n.º 21
0
  def test_removal_version_same(self):
    with self.assertRaises(CodeRemovedError):
      warn_or_error(VERSION, 'dummy description')

    @deprecated(VERSION)
    def test_func():
      pass
    with self.assertRaises(CodeRemovedError):
      test_func()
Exemplo n.º 22
0
def test_removal_version_lower():
  with pytest.raises(CodeRemovedError):
    warn_or_error('0.0.27', 'dummy description')

  @deprecated('0.0.27')
  def test_func():
    pass
  with pytest.raises(CodeRemovedError):
    test_func()
Exemplo n.º 23
0
  def test_removal_version_lower(self):
    with self.assertRaises(CodeRemovedError):
      warn_or_error('0.0.27.dev0', 'dummy description')

    @deprecated('0.0.27.dev0')
    def test_func():
      pass
    with self.assertRaises(CodeRemovedError):
      test_func()
Exemplo n.º 24
0
def __getattr__(name):
    if name == "__path__":
        raise AttributeError()
    warn_or_error(
        "2.10.0.dev0",
        f"the {name} class",
        f"{name} moved to the {setup.__name__} module.",
    )
    return getattr(setup, name)
 def assert_failure(pants_run: PantsResult,
                    msg: Optional[str] = None) -> None:
     warn_or_error(
         removal_version="2.1.0.dev0",
         deprecated_entity_description=
         "PantsIntegrationTest.assert_failure()",
         hint=
         "Use `PantsResult.assert_failure()`. `PantsIntegrationTest` is deprecated.",
     )
     pants_run.assert_failure(msg)
Exemplo n.º 26
0
def test_removal_version_lower():
    with pytest.raises(CodeRemovedError):
        warn_or_error("0.0.27.dev0", "dummy description")

    @deprecated("0.0.27.dev0")
    def test_func():
        pass

    with pytest.raises(CodeRemovedError):
        test_func()
Exemplo n.º 27
0
def test_removal_version_same():
    with pytest.raises(CodeRemovedError):
        warn_or_error(_FAKE_CUR_VERSION, "dummy description")

    @deprecated(_FAKE_CUR_VERSION)
    def test_func():
        pass

    with pytest.raises(CodeRemovedError):
        test_func()
Exemplo n.º 28
0
def test_removal_version_lower():
    with pytest.raises(CodeRemovedError):
        warn_or_error('0.0.27', 'dummy description')

    @deprecated('0.0.27')
    def test_func():
        pass

    with pytest.raises(CodeRemovedError):
        test_func()
Exemplo n.º 29
0
 def setUpClass(cls) -> None:
     super().setUpClass()
     warn_or_error(
         removal_version="2.1.0.dev0",
         deprecated_entity_description="pants.testutil.test_base.TestBase",
         hint=
         ("Use `pants.testutil.rule_runner.RuleRunner` instead, which uses a Pytest fixture "
          "style. See https://www.pantsbuild.org/v2.0/docs/rules-api-testing."
          ),
     )
Exemplo n.º 30
0
  def test_deprecation_start_version_validation(self):
    with self.assertRaises(BadSemanticVersionError):
      warn_or_error(removal_version='1.0.0.dev0',
                    deprecated_entity_description='dummy',
                    deprecation_start_version='1.a.0')

    with self.assertRaises(InvalidSemanticVersionOrderingError):
      warn_or_error(removal_version='0.0.0.dev0',
                    deprecated_entity_description='dummy',
                    deprecation_start_version='1.0.0.dev0')
 def temporary_workdir(cleanup: bool = True):
     warn_or_error(
         removal_version="2.1.0.dev0",
         deprecated_entity_description=
         "PantsIntegrationTest.temporary_workdir()",
         hint=
         ("Use the top-level function `temporary_workdir`. `PantsIntegrationTest` is "
          "deprecated."),
     )
     return temporary_workdir(cleanup=cleanup)
Exemplo n.º 32
0
    def _check_deprecations(self, scope, flags, values):
        for flag_matcher in self.flag_matchers:
            maybe_deprecation_warning_kwargs = flag_matcher(
                scope, flags, values)

            if maybe_deprecation_warning_kwargs is not None:
                if not isinstance(maybe_deprecation_warning_kwargs, dict):
                    raise TypeError(
                        "scope_flags_fun must return a dict, or None (was: {!r})"
                        .format(maybe_deprecation_warning_kwargs))
                warn_or_error(**maybe_deprecation_warning_kwargs)
Exemplo n.º 33
0
 def find_deferred_sources_fields(target):
     for name, payload_field in target.payload.fields:
         if isinstance(payload_field, DeferredSourcesField):
             if not self.get_options().allow_from_target:
                 raise TargetDefinitionException(target, from_target_deprecation_hint)
             warn_or_error(
                 removal_version="1.3.0",
                 deprecated_entity_description="DeferredSourcesField",
                 hint=from_target_deprecation_hint,
             )
             deferred_sources_fields.append((target, name, payload_field))
Exemplo n.º 34
0
    def get_sources(self) -> Optional["GlobsWithConjunction"]:
        """Returns target's non-deferred sources if exists or the default sources if defined.

        NB: once ivy is implemented in the engine, we can fetch sources natively here, and/or
        refactor how deferred sources are implemented.
          see: https://github.com/pantsbuild/pants/issues/2997
        """
        source = getattr(self, "source", None)
        sources = getattr(self, "sources", None)

        if source is not None and sources is not None:
            raise Target.IllegalArgument(
                self.address.spec,
                "Cannot specify both source and sources attribute.")

        if source is not None:
            if not isinstance(source, str):
                raise Target.IllegalArgument(
                    self.address.spec,
                    f"source must be a str containing a path relative to the target, but got {source} of "
                    f"type {type(source)}",
                )
            script_instructions = (
                "curl -L -o convert_source_to_sources.py 'https://git.io/JvbN3' && chmod +x "
                "convert_source_to_sources.py && ./convert_source_to_sources.py "
                f"root_folder1/ root_folder2/")
            warn_or_error(
                deprecated_entity_description=
                "using `source` instead of `sources` in a BUILD file",
                removal_version="1.29.0.dev0",
                hint=
                (f"Instead of `source={repr(source)}`, use `sources=[{repr(source)}]`. We "
                 "recommend using our migration script to automate fixing your entire "
                 f"repository by running `{script_instructions}`."),
            )
            sources = [source]

        # N.B. Here we check specifically for `sources is None`, as it's possible for sources
        # to be e.g. an explicit empty list (sources=[]).
        if sources is None:
            if self.default_sources_globs is None:
                return None
            default_sources = SourceGlobs(
                *(
                    *self.default_sources_globs,
                    *(f"!{glob}"
                      for glob in self.default_sources_exclude_globs or []),
                ), )
            return GlobsWithConjunction(default_sources,
                                        GlobExpansionConjunction.any_match)

        source_globs = SourceGlobs.from_sources_field(sources)
        return GlobsWithConjunction(source_globs,
                                    GlobExpansionConjunction.all_match)
Exemplo n.º 35
0
  def for_scope(self, scope, inherit_from_enclosing_scope=True):
    """Return the option values for the given scope.

    Values are attributes of the returned object, e.g., options.foo.
    Computed lazily per scope.

    :API: public
    """
    # Short-circuit, if already computed.
    if scope in self._values_by_scope:
      return self._values_by_scope[scope]

    # First get enclosing scope's option values, if any.
    if scope == GLOBAL_SCOPE or not inherit_from_enclosing_scope:
      values = OptionValueContainer()
    else:
      values = copy.copy(self.for_scope(enclosing_scope(scope)))

    # Now add our values.
    flags_in_scope = self._scope_to_flags.get(scope, [])
    self._parser_hierarchy.get_parser_by_scope(scope).parse_args(flags_in_scope, values)

    # If we're the new name of a deprecated scope, also get values from that scope.
    deprecated_scope = self.known_scope_to_info[scope].deprecated_scope
    # Note that deprecated_scope and scope share the same Optionable class, so deprecated_scope's
    # Optionable has a deprecated_options_scope equal to deprecated_scope. Therefore we must
    # check that scope != deprecated_scope to prevent infinite recursion.
    if deprecated_scope is not None and scope != deprecated_scope:
      # Do the deprecation check only on keys that were explicitly set on the deprecated scope
      # (and not on its enclosing scopes).
      explicit_keys = self.for_scope(deprecated_scope,
                                     inherit_from_enclosing_scope=False).get_explicit_keys()
      if explicit_keys:
        warn_or_error(self.known_scope_to_info[scope].deprecated_scope_removal_version,
                      'scope {}'.format(deprecated_scope),
                      'Use scope {} instead (options: {})'.format(scope, ', '.join(explicit_keys)))
        # Update our values with those of the deprecated scope (now including values inherited
        # from its enclosing scope).
        # Note that a deprecated val will take precedence over a val of equal rank.
        # This makes the code a bit neater.
        values.update(self.for_scope(deprecated_scope))

    # Record the value derivation.
    for option in values:
      self._option_tracker.record_option(scope=scope, option=option, value=values[option],
                                         rank=values.get_rank(option))

    # Cache the values.
    self._values_by_scope[scope] = values

    return values
Exemplo n.º 36
0
  def __init__(self, address=None, payload=None, prep_executable=None, prep_args=None,
               prep_environ=False, goal=None, goals=None, **kwargs):
    """
    :API: public

    :param prep_executable: The path to the executable that should be run.
    :param prep_args: A list of command-line args to the excutable.
    :param prep_environ: If True, the output of the command will be treated as
      a \\\\0-separated list of key=value pairs to insert into the environment.
      Note that this will pollute the environment for all future tests, so
      avoid it if at all possible.
    :param goal: (deprecated) Pants goal to run this command in [test, binary or compile]. If not
      specified, runs in the 'test' goal.
    :param goals: One or more pants goals to run this command in [test, binary or compile]. If not
      specified, runs in the 'test' goal.
    """
    def raise_bad_target(msg):
      raise TargetDefinitionException(address.spec, msg)

    if not prep_executable:
      raise_bad_target('prep_executable must be specified.')
    if goal and goals:
      raise_bad_target('Either `goal` or `goals` (preferred) should be specified, but not both.')

    if goals:
      goals = sorted(goals)
    elif goal:
      warn_or_error('1.5.0', 'goal', hint='Use `goals=[{!r}]` instead.'.format(goal))
      goals = [goal]
    else:
      goals = ['test']

    bad_goals = set(goals) - self.allowed_goals()
    if bad_goals:
      raise_bad_target('Got unrecognized goal{maybe_pluralize} {unrecognized}. '
                       'Goal must be one of {allowed}.'
                       .format(maybe_pluralize='' if len(bad_goals) == 1 else 's',
                               unrecognized=', '.join(sorted(bad_goals)),
                               allowed=self.allowed_goals()))

    payload = payload or Payload()
    payload.add_fields({
      'goals': PrimitiveField(goals),
      'prep_command_executable': PrimitiveField(prep_executable),
      'prep_command_args': PrimitiveField(prep_args or []),
      'prep_environ': PrimitiveField(prep_environ),
    })
    super(PrepCommand, self).__init__(address=address, payload=payload, **kwargs)
Exemplo n.º 37
0
def test_removal_version_bad():
  with pytest.raises(BadRemovalVersionError):
    warn_or_error(1.0, 'dummy description')

  with pytest.raises(BadRemovalVersionError):
    @deprecated(1.0)
    def test_func1():
      pass

  with pytest.raises(BadRemovalVersionError):
    warn_or_error('1.a.0', 'dummy description')

  with pytest.raises(BadRemovalVersionError):
    @deprecated('1.a.0')
    def test_func1a():
      pass
Exemplo n.º 38
0
  def _check_and_apply_deprecations(self, scope, values):
    """Checks whether a ScopeInfo has options specified in a deprecated scope.

    There are two related cases here. Either:
      1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated
         scope, meaning that the options temporarily live in two locations.
      2) The entire ScopeInfo is deprecated (as in the case of deprecated SubsystemDependencies),
         meaning that the options live in one location.

    In the first case, this method has the sideeffect of merging options values from deprecated
    scopes into the given values.
    """
    si = self.known_scope_to_info[scope]

    # If this Scope is itself deprecated, report that.
    if si.removal_version:
      explicit_keys = self.for_scope(scope, inherit_from_enclosing_scope=False).get_explicit_keys()
      if explicit_keys:
        warn_or_error(
            removal_version=si.removal_version,
            deprecated_entity_description='scope {}'.format(scope),
            hint=si.removal_hint,
          )

    # Check if we're the new name of a deprecated scope, and clone values from that scope.
    # Note that deprecated_scope and scope share the same Optionable class, so deprecated_scope's
    # Optionable has a deprecated_options_scope equal to deprecated_scope. Therefore we must
    # check that scope != deprecated_scope to prevent infinite recursion.
    deprecated_scope = si.deprecated_scope
    if deprecated_scope is not None and scope != deprecated_scope:
      # Do the deprecation check only on keys that were explicitly set on the deprecated scope
      # (and not on its enclosing scopes).
      explicit_keys = self.for_scope(deprecated_scope,
                                     inherit_from_enclosing_scope=False).get_explicit_keys()
      if explicit_keys:
        # Update our values with those of the deprecated scope (now including values inherited
        # from its enclosing scope).
        # Note that a deprecated val will take precedence over a val of equal rank.
        # This makes the code a bit neater.
        values.update(self.for_scope(deprecated_scope))

        warn_or_error(
            removal_version=self.known_scope_to_info[scope].deprecated_scope_removal_version,
            deprecated_entity_description='scope {}'.format(deprecated_scope),
            hint='Use scope {} instead (options: {})'.format(scope, ', '.join(explicit_keys))
          )
Exemplo n.º 39
0
  def test_deprecation_start_period(self):
    with self.assertRaises(CodeRemovedError):
      warn_or_error(removal_version=_FAKE_CUR_VERSION,
                    deprecated_entity_description='dummy',
                    deprecation_start_version='1.0.0.dev0')

    with self.warnings_catcher() as w:
      warn_or_error(removal_version='999.999.999.dev999',
                    deprecated_entity_description='dummy',
                    deprecation_start_version=_FAKE_CUR_VERSION)
      self.assertWarning(w, DeprecationWarning,
                         'DEPRECATED: dummy will be removed in version 999.999.999.dev999.')

    self.assertIsNone(
      warn_or_error(removal_version='999.999.999.dev999',
                    deprecated_entity_description='dummy',
                    deprecation_start_version='500.0.0.dev0'))
Exemplo n.º 40
0
  def test_removal_version_bad(self):
    with self.assertRaises(BadRemovalVersionError):
      warn_or_error('a.a.a', 'dummy description')

    with self.assertRaises(BadRemovalVersionError):
      @deprecated('a.a.a')
      def test_func0():
        pass

    with self.assertRaises(BadRemovalVersionError):
      warn_or_error(1.0, 'dummy description')

    with self.assertRaises(BadRemovalVersionError):
      @deprecated(1.0)
      def test_func1():
        pass

    with self.assertRaises(BadRemovalVersionError):
      warn_or_error('1.a.0', 'dummy description')

    with self.assertRaises(BadRemovalVersionError):
      @deprecated('1.a.0')
      def test_func1a():
        pass
Exemplo n.º 41
0
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

from pants.backend.jvm.targets.junit_tests import DeprecatedJavaTestsAlias
from pants.base.deprecated import warn_or_error


# Warn if any code imports this module.
# There's a separate deprecation warning in register.py for targets that use the old alias.
warn_or_error('1.4.0.dev0',
              'pants.backend.jvm.targets.java_tests.JavaTests',
              'Use pants.backend.jvm.targets.junit_tests.JUnitTests instead.')

JavaTests = DeprecatedJavaTestsAlias
Exemplo n.º 42
0
 def __init__(self, *args, **kwargs):
   super(DeprecatedJavaTests, self).__init__(*args, **kwargs)
   warn_or_error('1.4.0.dev0',
                 'java_tests(...) target type',
                 'Use junit_tests(...) instead for target {}.'.format(self.address.spec))