-
-
Notifications
You must be signed in to change notification settings - Fork 618
/
target.py
2928 lines (2360 loc) · 114 KB
/
target.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import collections.abc
import dataclasses
import enum
import glob as glob_stdlib
import itertools
import logging
import os.path
import textwrap
import zlib
from abc import ABC, ABCMeta, abstractmethod
from collections import deque
from dataclasses import dataclass
from enum import Enum
from pathlib import PurePath
from typing import (
Any,
ClassVar,
Dict,
Generic,
Iterable,
Iterator,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
cast,
get_type_hints,
)
from typing_extensions import Protocol, final
from pants.base.deprecated import warn_or_error
from pants.engine.addresses import Address, Addresses, UnparsedAddressInputs, assert_single_address
from pants.engine.collection import Collection
from pants.engine.engine_aware import EngineAwareParameter
from pants.engine.fs import (
GlobExpansionConjunction,
GlobMatchErrorBehavior,
PathGlobs,
Paths,
Snapshot,
)
from pants.engine.unions import UnionMembership, UnionRule, union
from pants.option.global_options import UnmatchedBuildFileGlobs
from pants.source.filespec import Filespec, FilespecMatcher
from pants.util.collections import ensure_list, ensure_str_list
from pants.util.dirutil import fast_relpath
from pants.util.docutil import bin_name, doc_url
from pants.util.frozendict import FrozenDict
from pants.util.memo import memoized_classproperty, memoized_method, memoized_property
from pants.util.meta import frozen_after_init
from pants.util.ordered_set import FrozenOrderedSet
from pants.util.strutil import bullet_list, pluralize, softwrap
logger = logging.getLogger(__name__)
# -----------------------------------------------------------------------------------------------
# Core Field abstractions
# -----------------------------------------------------------------------------------------------
# Type alias to express the intent that the type should be immutable and hashable. There's nothing
# to actually enforce this, outside of convention. Maybe we could develop a MyPy plugin?
ImmutableValue = Any
@frozen_after_init
class Field:
"""A Field.
The majority of fields should use field templates like `BoolField`, `StringField`, and
`StringSequenceField`. These subclasses will provide sensible type hints and validation
automatically.
If you are directly subclassing `Field`, you should likely override `compute_value()`
to perform any custom hydration and/or validation, such as converting unhashable types to
hashable types or checking for banned values. The returned value must be hashable
(and should be immutable) so that this Field may be used by the engine. This means, for
example, using tuples rather than lists and using `FrozenOrderedSet` rather than `set`.
If you plan to use the engine to fully hydrate the value, you can also inherit
`AsyncFieldMixin`, which will store an `address: Address` property on the `Field` instance.
Subclasses should also override the type hints for `value` and `raw_value` to be more precise
than `Any`. The type hint for `raw_value` is used to generate documentation, e.g. for
`./pants help $target_type`.
Set the `help` class property with a description, which will be used in `./pants help`. For the
best rendering, use soft wrapping (e.g. implicit string concatenation) within paragraphs, but
hard wrapping (`\n`) to separate distinct paragraphs and/or lists.
Example:
# NB: Really, this should subclass IntField. We only use Field as an example.
class Timeout(Field):
alias = "timeout"
value: Optional[int]
default = None
help = "A timeout field.\n\nMore information."
@classmethod
def compute_value(cls, raw_value: Optional[int], address: Address) -> Optional[int]:
value_or_default = super().compute_value(raw_value, address=address)
if value_or_default is not None and not isinstance(value_or_default, int):
raise ValueError(
"The `timeout` field expects an integer, but was given"
f"{value_or_default} for target {address}."
)
return value_or_default
"""
# Subclasses must define these.
alias: ClassVar[str]
help: ClassVar[str]
# Subclasses must define at least one of these two.
default: ClassVar[ImmutableValue]
required: ClassVar[bool] = False
# Subclasses may define these.
removal_version: ClassVar[str | None] = None
removal_hint: ClassVar[str | None] = None
deprecated_alias: ClassVar[str | None] = None
deprecated_alias_removal_version: ClassVar[str | None] = None
@final
def __init__(self, raw_value: Optional[Any], address: Address) -> None:
self._check_deprecated(raw_value, address)
self.value: Optional[ImmutableValue] = self.compute_value(raw_value, address)
@classmethod
def compute_value(cls, raw_value: Optional[Any], address: Address) -> ImmutableValue:
"""Convert the `raw_value` into `self.value`.
You should perform any optional validation and/or hydration here. For example, you may want
to check that an integer is > 0 or convert an `Iterable[str]` to `List[str]`.
The resulting value must be hashable (and should be immutable).
"""
if raw_value is None:
if cls.required:
raise RequiredFieldMissingException(address, cls.alias)
return cls.default
return raw_value
@classmethod
def _check_deprecated(cls, raw_value: Optional[Any], address: Address) -> None:
if not cls.removal_version or address.is_generated_target or raw_value is None:
return
if not cls.removal_hint:
raise ValueError(
f"You specified `removal_version` for {cls}, but not the class property "
"`removal_hint`."
)
warn_or_error(
cls.removal_version,
entity=f"the {repr(cls.alias)} field",
hint=(f"Using the `{cls.alias}` field in the target {address}. {cls.removal_hint}"),
)
def __repr__(self) -> str:
return (
f"{self.__class__}(alias={repr(self.alias)}, value={repr(self.value)}, "
f"default={repr(self.default)})"
)
def __str__(self) -> str:
return f"{self.alias}={self.value}"
def __hash__(self) -> int:
return hash((self.__class__, self.value))
def __eq__(self, other: Union[Any, Field]) -> bool:
if not isinstance(other, Field):
return NotImplemented
return (self.__class__, self.value) == (other.__class__, other.value)
# NB: By subclassing `Field`, MyPy understands our type hints, and it means it doesn't matter which
# order you use for inheriting the field template vs. the mixin.
class AsyncFieldMixin(Field):
"""A mixin to store the field's original `Address` for use during hydration by the engine.
Typically, you should also create a dataclass representing the hydrated value and another for
the request, then a rule to go from the request to the hydrated value. The request class should
store the async field as a property.
(Why use the request class as the rule input, rather than the field itself? It's a wrapper so
that subclasses of the async field work properly, given that the engine uses exact type IDs.
This is like WrappedTarget.)
For example:
class Sources(StringSequenceField, AsyncFieldMixin):
alias = "sources"
# Often, async fields will want to define entry points like this to allow subclasses to
# change behavior.
def validate_resolved_files(self, files: Sequence[str]) -> None:
pass
@dataclass(frozen=True)
class HydrateSourcesRequest:
field: Sources
@dataclass(frozen=True)
class HydratedSources:
snapshot: Snapshot
@rule
def hydrate_sources(request: HydrateSourcesRequest) -> HydratedSources:
result = await Get(Snapshot, PathGlobs(request.field.value))
request.field.validate_resolved_files(result.files)
...
return HydratedSources(result)
Then, call sites can `await Get` if they need to hydrate the field, even if they subclassed
the original async field to have custom behavior:
sources1 = await Get(HydratedSources, HydrateSourcesRequest(my_tgt.get(Sources)))
sources2 = await Get(HydratedSources, HydrateSourcesRequest(custom_tgt.get(CustomSources)))
"""
@final # type: ignore[misc]
def __init__(self, raw_value: Optional[Any], address: Address) -> None:
super().__init__(raw_value, address)
# We must temporarily unfreeze the field, but then we refreeze to continue avoiding
# subclasses from adding arbitrary fields.
self._unfreeze_instance() # type: ignore[attr-defined]
# N.B.: We store the address here and not in the Field base class, because the memory usage
# of storing this value in every field was shown to be excessive / lead to performance
# issues.
self.address = address
self._freeze_instance() # type: ignore[attr-defined]
def __repr__(self) -> str:
return (
f"{self.__class__}(alias={repr(self.alias)}, address={self.address}, "
f"value={repr(self.value)}, default={repr(self.default)})"
)
def __hash__(self) -> int:
return hash((self.__class__, self.value, self.address))
def __eq__(self, other: Union[Any, AsyncFieldMixin]) -> bool:
if not isinstance(other, AsyncFieldMixin):
return NotImplemented
return (self.__class__, self.value, self.address) == (
other.__class__,
other.value,
other.address,
)
@union
@dataclass(frozen=True)
class FieldDefaultFactoryRequest:
"""Registers a dynamic default for a Field.
See `FieldDefaults`.
"""
field_type: ClassVar[type[Field]]
# TODO: Workaround for https://github.com/python/mypy/issues/5485, because we cannot directly use
# a Callable.
class FieldDefaultFactory(Protocol):
def __call__(self, field: Field) -> Any:
pass
@dataclass(frozen=True)
class FieldDefaultFactoryResult:
"""A wrapper for a function which computes the default value of a Field."""
default_factory: FieldDefaultFactory
@dataclass(frozen=True)
class FieldDefaults:
"""Generic Field default values. To install a default, see `FieldDefaultFactoryRequest`.
TODO: This is to work around the fact that Field value defaulting cannot have arbitrary
subsystem requirements, and so e.g. `JvmResolveField` and `PythonResolveField` have methods
which compute the true value of the field given a subsytem argument. Consumers need to
be type aware, and `@rules` cannot have dynamic requirements.
Additionally, `__defaults__` should mean that computed default Field values should become
more rare: i.e. `JvmResolveField` and `PythonResolveField` could potentially move to
hardcoded default values which users override with `__defaults__` if they'd like to change
the default resolve names.
See https://github.com/pantsbuild/pants/issues/12934 about potentially allowing unions
(including Field registrations) to have `@rule_helper` methods, which would allow the
computation of an AsyncField to directly require a subsystem.
"""
_factories: FrozenDict[type[Field], FieldDefaultFactory]
@memoized_method
def factory(self, field_type: type[Field]) -> FieldDefaultFactory:
"""Looks up a Field default factory in a subclass-aware way."""
factory = self._factories.get(field_type, None)
if factory is not None:
return factory
for ft, factory in self._factories.items():
if issubclass(field_type, ft):
return factory
return lambda f: f.value
def value_or_default(self, field: Field) -> Any:
return (self.factory(type(field)))(field)
# -----------------------------------------------------------------------------------------------
# Core Target abstractions
# -----------------------------------------------------------------------------------------------
# NB: This TypeVar is what allows `Target.get()` to properly work with MyPy so that MyPy knows
# the precise Field returned.
_F = TypeVar("_F", bound=Field)
@frozen_after_init
class Target:
"""A Target represents an addressable set of metadata.
Set the `help` class property with a description, which will be used in `./pants help`. For the
best rendering, use soft wrapping (e.g. implicit string concatenation) within paragraphs, but
hard wrapping (`\n`) to separate distinct paragraphs and/or lists.
"""
# Subclasses must define these
alias: ClassVar[str]
core_fields: ClassVar[Tuple[Type[Field], ...]]
help: ClassVar[str]
removal_version: ClassVar[str | None] = None
removal_hint: ClassVar[str | None] = None
deprecated_alias: ClassVar[str | None] = None
deprecated_alias_removal_version: ClassVar[str | None] = None
# These get calculated in the constructor
address: Address
plugin_fields: tuple[type[Field], ...]
field_values: FrozenDict[type[Field], Field]
residence_dir: str
name_explicitly_set: bool
@final
def __init__(
self,
unhydrated_values: dict[str, Any],
address: Address,
# NB: `union_membership` is only optional to facilitate tests. In production, we should
# always provide this parameter. This should be safe to do because production code should
# rarely directly instantiate Targets and should instead use the engine to request them.
union_membership: UnionMembership | None = None,
*,
name_explicitly_set: bool = True,
residence_dir: str | None = None,
) -> None:
"""Create a target.
:param unhydrated_values: A mapping of field aliases to their raw values. Any left off
fields will either use their default or error if required=True.
:param address: How to uniquely identify this target.
:param union_membership: Used to determine plugin fields. This must be set in production!
:param residence_dir: Where this target "lives". If unspecified, will be the `spec_path`
of the `address`, i.e. where the target was either explicitly defined or where its
target generator was explicitly defined. Target generators can, however, set this to
the directory where the generated target provides metadata for. For example, a
file-based target like `python_source` should set this to the parent directory of
its file. A file-less target like `go_third_party_package` should keep the default of
`address.spec_path`. This field impacts how command line specs work, so that globs
like `dir:` know whether to match the target or not.
"""
if self.removal_version and not address.is_generated_target:
if not self.removal_hint:
raise ValueError(
f"You specified `removal_version` for {self.__class__}, but not "
"the class property `removal_hint`."
)
warn_or_error(
self.removal_version,
entity=f"the {repr(self.alias)} target type",
hint=f"Using the `{self.alias}` target type for {address}. {self.removal_hint}",
)
self.address = address
self.plugin_fields = self._find_plugin_fields(union_membership or UnionMembership({}))
self.residence_dir = residence_dir if residence_dir is not None else address.spec_path
self.name_explicitly_set = name_explicitly_set
self.field_values = self._calculate_field_values(unhydrated_values, address)
self.validate()
@final
def _calculate_field_values(
self, unhydrated_values: dict[str, Any], address: Address
) -> FrozenDict[type[Field], Field]:
field_values = {}
aliases_to_field_types = self._get_field_aliases_to_field_types(self.field_types)
for alias, value in unhydrated_values.items():
if alias not in aliases_to_field_types:
valid_aliases = set(aliases_to_field_types.keys())
if isinstance(self, TargetGenerator):
# Even though moved_fields don't live on the target generator, they are valid
# for users to specify. It's intentional that these are only used for
# `InvalidFieldException` and are not stored as normal fields with
# `aliases_to_field_types`.
for field_type in self.moved_fields:
valid_aliases.add(field_type.alias)
if field_type.deprecated_alias is not None:
valid_aliases.add(field_type.deprecated_alias)
raise InvalidFieldException(
f"Unrecognized field `{alias}={value}` in target {address}. Valid fields for "
f"the target type `{self.alias}`: {sorted(valid_aliases)}.",
)
field_type = aliases_to_field_types[alias]
field_values[field_type] = field_type(value, address)
# For undefined fields, mark the raw value as None.
for field_type in set(self.field_types) - set(field_values.keys()):
field_values[field_type] = field_type(None, address)
return FrozenDict(
sorted(
field_values.items(),
key=lambda field_type_to_val_pair: field_type_to_val_pair[0].alias,
)
)
@final
@classmethod
def _get_field_aliases_to_field_types(
cls, field_types: tuple[type[Field], ...]
) -> dict[str, type[Field]]:
aliases_to_field_types = {}
for field_type in field_types:
aliases_to_field_types[field_type.alias] = field_type
if field_type.deprecated_alias is not None:
aliases_to_field_types[field_type.deprecated_alias] = field_type
return aliases_to_field_types
@final
@property
def field_types(self) -> Tuple[Type[Field], ...]:
return (*self.core_fields, *self.plugin_fields)
@final
@memoized_classproperty
def _plugin_field_cls(cls) -> type:
# Use the `PluginField` of the first `Target`-subclass ancestor as a base to ours, so that
# we inherit the registered fields. E.g. If I inherit from `PythonSourceTarget`, I want all
# the registered fields on `PythonSourceTarget` to also be registered for me.
baseclass = (
object
if cast("Type[Target]", cls) is Target
else next(
base for base in cast("Type[Target]", cls).__bases__ if issubclass(base, Target)
)._plugin_field_cls
)
@union
class PluginField(baseclass): # type: ignore[misc, valid-type]
pass
return PluginField
def __repr__(self) -> str:
fields = ", ".join(str(field) for field in self.field_values.values())
return (
f"{self.__class__}("
f"address={self.address}, "
f"alias={repr(self.alias)}, "
f"residence_dir={repr(self.residence_dir)}, "
f"{fields})"
)
def __str__(self) -> str:
fields = ", ".join(str(field) for field in self.field_values.values())
address = f"address=\"{self.address}\"{', ' if fields else ''}"
return f"{self.alias}({address}{fields})"
def __hash__(self) -> int:
return hash((self.__class__, self.address, self.residence_dir, self.field_values))
def __eq__(self, other: Union[Target, Any]) -> bool:
if not isinstance(other, Target):
return NotImplemented
return (self.__class__, self.address, self.residence_dir, self.field_values) == (
other.__class__,
other.address,
other.residence_dir,
other.field_values,
)
@final
@classmethod
def _find_plugin_fields(cls, union_membership: UnionMembership) -> tuple[type[Field], ...]:
return cast(Tuple[Type[Field], ...], tuple(union_membership.get(cls._plugin_field_cls)))
@final
@classmethod
def _find_registered_field_subclass(
cls, requested_field: Type[_F], *, registered_fields: Iterable[Type[Field]]
) -> Optional[Type[_F]]:
"""Check if the Target has registered a subclass of the requested Field.
This is necessary to allow targets to override the functionality of common fields. For
example, you could subclass `Tags` to define `CustomTags` with a different default. At the
same time, we still want to be able to call `tgt.get(Tags)`, in addition to
`tgt.get(CustomTags)`.
"""
subclass = next(
(
registered_field
for registered_field in registered_fields
if issubclass(registered_field, requested_field)
),
None,
)
return subclass
@final
def _maybe_get(self, field: Type[_F]) -> Optional[_F]:
result = self.field_values.get(field, None)
if result is not None:
return cast(_F, result)
field_subclass = self._find_registered_field_subclass(
field, registered_fields=self.field_types
)
if field_subclass is not None:
return cast(_F, self.field_values[field_subclass])
return None
@final
def __getitem__(self, field: Type[_F]) -> _F:
"""Get the requested `Field` instance belonging to this target.
If the `Field` is not registered on this `Target` type, this method will raise a
`KeyError`. To avoid this, you should first call `tgt.has_field()` or `tgt.has_fields()`
to ensure that the field is registered, or, alternatively, use `Target.get()`.
See the docstring for `Target.get()` for how this method handles subclasses of the
requested Field and for tips on how to use the returned value.
"""
result = self._maybe_get(field)
if result is not None:
return result
raise KeyError(
f"The target `{self}` does not have a field `{field.__name__}`. Before calling "
f"`my_tgt[{field.__name__}]`, call `my_tgt.has_field({field.__name__})` to "
f"filter out any irrelevant Targets or call `my_tgt.get({field.__name__})` to use the "
f"default Field value."
)
@final
def get(self, field: Type[_F], *, default_raw_value: Optional[Any] = None) -> _F:
"""Get the requested `Field` instance belonging to this target.
This will return an instance of the requested field type, e.g. an instance of
`InterpreterConstraints`, `SourcesField`, `EntryPoint`, etc. Usually, you will want to
grab the `Field`'s inner value, e.g. `tgt.get(Compatibility).value`. (For async fields like
`SourcesField`, you may need to hydrate the value.).
This works with subclasses of `Field`s. For example, if you subclass `Tags`
to define a custom subclass `CustomTags`, both `tgt.get(Tags)` and
`tgt.get(CustomTags)` will return the same `CustomTags` instance.
If the `Field` is not registered on this `Target` type, this will return an instance of
the requested Field by using `default_raw_value` to create the instance. Alternatively,
first call `tgt.has_field()` or `tgt.has_fields()` to ensure that the field is registered,
or, alternatively, use indexing (e.g. `tgt[Compatibility]`) to raise a KeyError when the
field is not registered.
"""
result = self._maybe_get(field)
if result is not None:
return result
return field(default_raw_value, self.address)
@final
@classmethod
def _has_fields(
cls, fields: Iterable[Type[Field]], *, registered_fields: Iterable[Type[Field]]
) -> bool:
unrecognized_fields = [field for field in fields if field not in registered_fields]
if not unrecognized_fields:
return True
for unrecognized_field in unrecognized_fields:
maybe_subclass = cls._find_registered_field_subclass(
unrecognized_field, registered_fields=registered_fields
)
if maybe_subclass is None:
return False
return True
@final
def has_field(self, field: Type[Field]) -> bool:
"""Check that this target has registered the requested field.
This works with subclasses of `Field`s. For example, if you subclass `Tags` to define a
custom subclass `CustomTags`, both `tgt.has_field(Tags)` and
`python_tgt.has_field(CustomTags)` will return True.
"""
return self.has_fields([field])
@final
def has_fields(self, fields: Iterable[Type[Field]]) -> bool:
"""Check that this target has registered all of the requested fields.
This works with subclasses of `Field`s. For example, if you subclass `Tags` to define a
custom subclass `CustomTags`, both `tgt.has_fields([Tags])` and
`python_tgt.has_fields([CustomTags])` will return True.
"""
return self._has_fields(fields, registered_fields=self.field_types)
@final
@classmethod
def class_field_types(cls, union_membership: UnionMembership) -> Tuple[Type[Field], ...]:
"""Return all registered Fields belonging to this target type.
You can also use the instance property `tgt.field_types` to avoid having to pass the
parameter UnionMembership.
"""
return (*cls.core_fields, *cls._find_plugin_fields(union_membership))
@final
@classmethod
def class_has_field(cls, field: Type[Field], union_membership: UnionMembership) -> bool:
"""Behaves like `Target.has_field()`, but works as a classmethod rather than an instance
method."""
return cls.class_has_fields([field], union_membership)
@final
@classmethod
def class_has_fields(
cls, fields: Iterable[Type[Field]], union_membership: UnionMembership
) -> bool:
"""Behaves like `Target.has_fields()`, but works as a classmethod rather than an instance
method."""
return cls._has_fields(fields, registered_fields=cls.class_field_types(union_membership))
@final
@classmethod
def class_get_field(cls, field: Type[_F], union_membership: UnionMembership) -> Type[_F]:
"""Get the requested Field type registered with this target type.
This will error if the field is not registered, so you should call Target.class_has_field()
first.
"""
class_fields = cls.class_field_types(union_membership)
result = next(
(
registered_field
for registered_field in class_fields
if issubclass(registered_field, field)
),
None,
)
if result is None:
raise KeyError(
f"The target type `{cls.alias}` does not have a field `{field.__name__}`. Before "
f"calling `TargetType.class_get_field({field.__name__})`, call "
f"`TargetType.class_has_field({field.__name__})`."
)
return result
@final
@classmethod
def register_plugin_field(cls, field: Type[Field]) -> UnionRule:
"""Register a new field on the target type.
In the `rules()` register.py entry-point, include
`MyTarget.register_plugin_field(NewField)`. This will register `NewField` as a first-class
citizen. Plugins can use this new field like any other.
"""
return UnionRule(cls._plugin_field_cls, field)
def validate(self) -> None:
"""Validate the target, such as checking for mutually exclusive fields.
N.B.: The validation should only be of properties intrinsic to the associated files in any
context. If the validation only makes sense for certain goals acting on targets; those
validations should be done in the associated rules.
"""
@dataclass(frozen=True)
class WrappedTargetRequest:
"""Used with `WrappedTarget` to get the Target corresponding to an address.
`description_of_origin` is used for error messages when the address does not actually exist. If
you are confident this cannot happen, set the string to something like `<infallible>`.
"""
address: Address
description_of_origin: str = dataclasses.field(hash=False, compare=False)
@dataclass(frozen=True)
class WrappedTarget:
"""A light wrapper to encapsulate all the distinct `Target` subclasses into a single type.
This is necessary when using a single target in a rule because the engine expects exact types
and does not work with subtypes.
"""
target: Target
class Targets(Collection[Target]):
"""A heterogeneous collection of instances of Target subclasses.
While every element will be a subclass of `Target`, there may be many different `Target` types
in this collection, e.g. some `FileTarget` and some `PythonTestTarget`.
Often, you will want to filter out the relevant targets by looking at what fields they have
registered, e.g.:
valid_tgts = [tgt for tgt in tgts if tgt.has_fields([Compatibility, PythonSources])]
You should not check the Target's actual type because this breaks custom target types;
for example, prefer `tgt.has_field(PythonTestsSourcesField)` to
`isinstance(tgt, PythonTestsTarget)`.
"""
def expect_single(self) -> Target:
assert_single_address([tgt.address for tgt in self])
return self[0]
# This distinct type is necessary because of https://github.com/pantsbuild/pants/issues/14977.
#
# NB: We still proactively apply filtering inside `AddressSpecs` and `FilesystemSpecs`, which is
# earlier in the rule pipeline of `RawSpecs -> Addresses -> UnexpandedTargets -> Targets ->
# FilteredTargets`. That is necessary so that project-introspection goals like `list` which don't
# use `FilteredTargets` still have filtering applied.
class FilteredTargets(Collection[Target]):
"""A heterogenous collection of Target instances that have been filtered with the global options
`--tag` and `--exclude-target-regexp`.
Outside of the extra filtering, this type is identical to `Targets`, including its handling of
target generators.
"""
def expect_single(self) -> Target:
assert_single_address([tgt.address for tgt in self])
return self[0]
class UnexpandedTargets(Collection[Target]):
"""Like `Targets`, but will not replace target generators with their generated targets (e.g.
replace `python_sources` "BUILD targets" with generated `python_source` "file targets")."""
def expect_single(self) -> Target:
assert_single_address([tgt.address for tgt in self])
return self[0]
class CoarsenedTarget(EngineAwareParameter):
def __init__(self, members: Iterable[Target], dependencies: Iterable[CoarsenedTarget]) -> None:
"""A set of Targets which cyclicly reach one another, and are thus indivisible.
Instances of this class form a structure-shared DAG, and so a hashcode is pre-computed for the
recursive portion.
:param members: The members of the cycle.
:param dependencies: The deduped direct (not transitive) dependencies of all Targets in
the cycle. Dependencies between members of the cycle are excluded.
"""
self.members = FrozenOrderedSet(members)
self.dependencies = FrozenOrderedSet(dependencies)
self._hashcode = hash((self.members, self.dependencies))
def debug_hint(self) -> str:
return str(self)
def metadata(self) -> Dict[str, Any]:
return {"addresses": [t.address.spec for t in self.members]}
@property
def representative(self) -> Target:
"""A stable "representative" target in the cycle."""
return next(iter(self.members))
def bullet_list(self) -> str:
"""The addresses and type aliases of all members of the cycle."""
return bullet_list(sorted(f"{t.address.spec}\t({type(t).alias})" for t in self.members))
def closure(self, visited: Set[CoarsenedTarget] | None = None) -> Iterator[Target]:
"""All Targets reachable from this root."""
return (t for ct in self.coarsened_closure(visited) for t in ct.members)
def coarsened_closure(
self, visited: Set[CoarsenedTarget] | None = None
) -> Iterator[CoarsenedTarget]:
"""All CoarsenedTargets reachable from this root."""
visited = visited or set()
queue = deque([self])
while queue:
ct = queue.popleft()
if ct in visited:
continue
visited.add(ct)
yield ct
queue.extend(ct.dependencies)
def __hash__(self) -> int:
return self._hashcode
def _eq_helper(self, other: CoarsenedTarget, equal_items: set[tuple[int, int]]) -> bool:
key = (id(self), id(other))
if key[0] == key[1] or key in equal_items:
return True
is_eq = (
self._hashcode == other._hashcode
and self.members == other.members
and len(self.dependencies) == len(other.dependencies)
and all(
l._eq_helper(r, equal_items) for l, r in zip(self.dependencies, other.dependencies)
)
)
# NB: We only track equal items because any non-equal item will cause the entire
# operation to shortcircuit.
if is_eq:
equal_items.add(key)
return is_eq
def __eq__(self, other: Any) -> bool:
if not isinstance(other, CoarsenedTarget):
return NotImplemented
return self._eq_helper(other, set())
def __str__(self) -> str:
if len(self.members) > 1:
others = len(self.members) - 1
return f"{self.representative.address.spec} (and {others} more)"
return self.representative.address.spec
def __repr__(self) -> str:
return f"{self.__class__.__name__}({str(self)})"
class CoarsenedTargets(Collection[CoarsenedTarget]):
"""The CoarsenedTarget roots of a transitive graph walk for some addresses.
To collect all reachable CoarsenedTarget members, use `def closure`.
"""
def by_address(self) -> dict[Address, CoarsenedTarget]:
"""Compute a mapping from Address to containing CoarsenedTarget."""
return {t.address: ct for ct in self for t in ct.members}
def closure(self) -> Iterator[Target]:
"""All Targets reachable from these CoarsenedTarget roots."""
visited: Set[CoarsenedTarget] = set()
return (t for root in self for t in root.closure(visited))
def coarsened_closure(self) -> Iterator[CoarsenedTarget]:
"""All CoarsenedTargets reachable from these CoarsenedTarget roots."""
visited: Set[CoarsenedTarget] = set()
return (ct for root in self for ct in root.coarsened_closure(visited))
def __eq__(self, other: Any) -> bool:
if not isinstance(other, CoarsenedTargets):
return NotImplemented
equal_items: set[tuple[int, int]] = set()
return len(self) == len(other) and all(
l._eq_helper(r, equal_items) for l, r in zip(self, other)
)
__hash__ = Tuple.__hash__
@frozen_after_init
@dataclass(unsafe_hash=True)
class CoarsenedTargetsRequest:
"""A request to get CoarsenedTargets for input roots."""
roots: Tuple[Address, ...]
expanded_targets: bool
include_special_cased_deps: bool
def __init__(
self,
roots: Iterable[Address],
*,
expanded_targets: bool = False,
include_special_cased_deps: bool = False,
) -> None:
self.roots = tuple(roots)
self.expanded_targets = expanded_targets
self.include_special_cased_deps = include_special_cased_deps
@dataclass(frozen=True)
class TransitiveTargets:
"""A set of Target roots, and their transitive, flattened, de-duped dependencies.
If a target root is a dependency of another target root, then it will show up both in `roots`
and in `dependencies`.
"""
roots: Tuple[Target, ...]
dependencies: FrozenOrderedSet[Target]
@memoized_property
def closure(self) -> FrozenOrderedSet[Target]:
"""The roots and the dependencies combined."""
return FrozenOrderedSet([*self.roots, *self.dependencies])
@frozen_after_init
@dataclass(unsafe_hash=True)
class TransitiveTargetsRequest:
"""A request to get the transitive dependencies of the input roots.
Resolve the transitive targets with `await Get(TransitiveTargets,
TransitiveTargetsRequest([addr1, addr2])`.
"""
roots: Tuple[Address, ...]
include_special_cased_deps: bool
def __init__(
self, roots: Iterable[Address], *, include_special_cased_deps: bool = False
) -> None:
self.roots = tuple(roots)
self.include_special_cased_deps = include_special_cased_deps
@frozen_after_init
@dataclass(unsafe_hash=True)
class RegisteredTargetTypes:
aliases_to_types: FrozenDict[str, Type[Target]]
def __init__(self, aliases_to_types: Mapping[str, Type[Target]]) -> None:
self.aliases_to_types = FrozenDict(aliases_to_types)
@classmethod
def create(cls, target_types: Iterable[Type[Target]]) -> RegisteredTargetTypes:
result = {}
for target_type in sorted(target_types, key=lambda tt: tt.alias):
result[target_type.alias] = target_type
if target_type.deprecated_alias is not None:
result[target_type.deprecated_alias] = target_type
return cls(result)
@property
def aliases(self) -> FrozenOrderedSet[str]:
return FrozenOrderedSet(self.aliases_to_types.keys())
@property
def types(self) -> FrozenOrderedSet[type[Target]]:
return FrozenOrderedSet(self.aliases_to_types.values())
class AllTargets(Collection[Target]):
"""All targets in the project, but with target generators replaced by their generated targets,
unlike `AllUnexpandedTargets`."""
class AllUnexpandedTargets(Collection[Target]):
"""All targets in the project, including generated targets.
This should generally be avoided because it is relatively expensive to compute and is frequently
invalidated, but it can be necessary for things like dependency inference to build a global
mapping of imports to targets.
"""
@dataclass(frozen=True)
class AllTargetsRequest:
"""Find all targets in the project.
Use with either `AllUnexpandedTargets` or `AllTargets`.
"""