Extending pre-existing targets
Adding new fields to target types.
This feature isn't working correctly
The new field will not actually register. This is fixed in 2.0.0.
When to add new fields?
Adding new fields is useful when you are already using a target type, but need to store additional metadata for your plugin.
For example, if you're writing a codegen plugin to convert a protobuf_library
into Java source files, you may want to add a jdk_version
field to protobuf_library
.
If you are instead adding support for a new language, create a new target type.
If you want to reduce boilerplate in BUILD files, such as changing default values, use macros.
How to add new fields
First, define the field. Then, register it by using UnionRule(OriginalTarget.PluginField, CustomField)
, like this:
from pants.backend.codegen.protobuf.target_types import ProtobufLibrary
from pants.engine.target import BoolField
from pants.engine.unions import UnionRule
class ProtobufJdkVersion(IntField):
"""Which JDK protobuf should target."""
alias = "jdk_version"
default = 11
def rules():
return [UnionRule(ProtobufLibrary.PluginField, ProtobufJdkVersion)]
To confirm this worked, run <<pantscmd>> target-types --details=python_tests
, and you should see your new field.
Adding fields to pre-existing target types will break V1
Unfortunately, V1 does not allow you to add new fields to pre-existing target types. V1 will fail to parse your new target and will cause Pants to fail.
If you are still using V1, you must either instead create a new target type or use the
tags
field if your data can be expressed through a string value.
Updated over 3 years ago