forked from pantsbuild/pants
-
Notifications
You must be signed in to change notification settings - Fork 0
/
target.py
1508 lines (1187 loc) · 57 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).
import dataclasses
import itertools
import os.path
from abc import ABC, ABCMeta, abstractmethod
from dataclasses import dataclass
from enum import Enum
from pathlib import PurePath
from typing import (
Any,
ClassVar,
Dict,
Generic,
Iterable,
Mapping,
Optional,
Tuple,
Type,
TypeVar,
Union,
cast,
)
from typing_extensions import final
from pants.base.specs import OriginSpec
from pants.engine.addresses import Address, assert_single_address
from pants.engine.collection import Collection, DeduplicatedCollection
from pants.engine.fs import Snapshot
from pants.engine.unions import UnionMembership, UnionRule, union
from pants.source.filespec import Filespec
from pants.util.collections import ensure_list, ensure_str_list
from pants.util.frozendict import FrozenDict
from pants.util.memo import memoized_classproperty, memoized_property
from pants.util.meta import frozen_after_init
from pants.util.ordered_set import FrozenOrderedSet
from pants.util.strutil import pluralize
# -----------------------------------------------------------------------------------------------
# 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
class Field(ABC):
# Subclasses must define these.
alias: ClassVar[str]
default: ClassVar[ImmutableValue]
# Subclasses may define these.
required: ClassVar[bool] = False
# This is a little weird to have an abstract __init__(). We do this to ensure that all
# subclasses have this exact type signature for their constructor.
#
# Normally, with dataclasses, each constructor parameter would instead be specified via a
# dataclass field declaration. But, we don't want to declare either `address` or `raw_value` as
# attributes because we make no assumptions whether the subclasses actually store those values
# on each instance. All that we care about is a common constructor interface.
@abstractmethod
def __init__(self, raw_value: Optional[Any], *, address: Address) -> None:
pass
@frozen_after_init
@dataclass(unsafe_hash=True)
class PrimitiveField(Field, metaclass=ABCMeta):
"""A Field that does not need the engine in order to be hydrated.
The majority of fields should use subclasses of `PrimitiveField`, e.g. use `BoolField`,
`StringField`, or `StringSequenceField`. These subclasses will provide sane type hints and
hydration/validation automatically.
If you are directly subclassing `PrimitiveField`, 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 V2 engine. This means, for
example, using tuples rather than lists and using `FrozenOrderedSet` rather than `set`.
All hydration and/or validation happens eagerly in the constructor. If the
hydration is particularly expensive, use `AsyncField` instead to get the benefits of the
engine's caching.
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 target-types`. If the field is required, do not use `Optional` for the type hint of
`raw_value`.
Example:
# NB: Really, this should subclass IntField. We only use PrimitiveField as an example.
class Timeout(PrimitiveField):
alias = "timeout"
value: Optional[int]
default = None
@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
"""
value: ImmutableValue
@final
def __init__(self, raw_value: Optional[Any], *, address: Address) -> None:
# NB: We neither store the `address` or `raw_value` as attributes on this dataclass:
# * Don't store `raw_value` because it very often is mutable and/or unhashable, which means
# this Field could not be passed around in the engine.
# * Don't store `address` to avoid the cost in memory of storing `Address` on every single
# field encountered by Pants in a run.
self.value = self.compute_value(raw_value, address=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
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}"
@frozen_after_init
@dataclass(unsafe_hash=True)
class AsyncField(Field, metaclass=ABCMeta):
"""A field that needs the engine in order to be hydrated.
You should implement `sanitize_raw_value()` to convert the `raw_value` into a type that is
immutable and hashable so that this Field may be used by the V2 engine. This means, for example,
using tuples rather than lists and using `FrozenOrderedSet` rather than `set`.
You should also create corresponding HydratedField and HydrateFieldRequest classes and define a
rule to go from this HydrateFieldRequest to HydratedField. The HydrateFieldRequest type should
have an attribute storing the underlying AsyncField; it also must be registered as a RootRule.
For example:
class Sources(AsyncField):
alias: ClassVar = "sources"
sanitized_raw_value: Optional[Tuple[str, ...]]
def sanitize_raw_value(
raw_value: Optional[List[str]], *, address: Address
) -> Optional[Tuple[str, ...]]:
...
# Example extension point provided by this field. Subclasses can override this to do
# whatever validation they'd like. Each AsyncField must define its own entry points
# like this to allow subclasses to change behavior.
def validate_snapshot(self, snapshot: Snapshot) -> 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.sanitized_raw_value))
request.field.validate_snapshot(result)
...
return HydratedSources(result)
def rules():
return [hydrate_sources, RootRule(HydrateSourcesRequest)]
Then, call sites can `await Get` if they need to hydrate the field, even if they subclassed
the original `AsyncField` to have custom behavior:
sources1 = await Get(HydratedSources, HydrateSourcesRequest(my_tgt.get(Sources)))
sources2 = await Get(HydratedSources, HydrateSourcesRequest(custom_tgt.get(CustomSources)))
"""
address: Address
sanitized_raw_value: ImmutableValue
@final
def __init__(self, raw_value: Optional[Any], *, address: Address) -> None:
self.address = address
self.sanitized_raw_value = self.sanitize_raw_value(raw_value, address=address)
@classmethod
def sanitize_raw_value(cls, raw_value: Optional[Any], *, address: Address) -> ImmutableValue:
"""Sanitize the `raw_value` into a type that is safe for the V2 engine to use.
The resulting type should be immutable and hashable.
You may also do light-weight validation in this method, such as ensuring that all
elements of a list are strings.
"""
if raw_value is None:
if cls.required:
raise RequiredFieldMissingException(address, cls.alias)
return cls.default
return raw_value
def __repr__(self) -> str:
return (
f"{self.__class__}(alias={repr(self.alias)}, "
f"sanitized_raw_value={repr(self.sanitized_raw_value)}, default={repr(self.default)})"
)
def __str__(self) -> str:
return f"{self.alias}={self.sanitized_raw_value}"
# -----------------------------------------------------------------------------------------------
# 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
@dataclass(unsafe_hash=True)
class Target(ABC):
"""A Target represents a combination of fields that are valid _together_."""
# Subclasses must define these
alias: ClassVar[str]
core_fields: ClassVar[Tuple[Type[Field], ...]]
# These get calculated in the constructor
address: Address
plugin_fields: Tuple[Type[Field], ...]
field_values: FrozenDict[Type[Field], Field]
@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: Optional[UnionMembership] = None,
) -> None:
self.address = address
self.plugin_fields = self._find_plugin_fields(union_membership or UnionMembership({}))
field_values = {}
aliases_to_field_types = {field_type.alias: field_type for field_type in self.field_types}
for alias, value in unhydrated_values.items():
if alias not in aliases_to_field_types:
raise InvalidFieldException(
f"Unrecognized field `{alias}={value}` in target {address}. Valid fields for "
f"the target type `{self.alias}`: {sorted(aliases_to_field_types.keys())}.",
)
field_type = aliases_to_field_types[alias]
field_values[field_type] = field_type(value, address=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(raw_value=None, address=address)
self.field_values = FrozenDict(field_values)
@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:
# NB: We ensure that each Target subtype has its own `PluginField` class so that
# registering a plugin field doesn't leak across target types.
@union
class PluginField:
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"{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})"
@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 like
`Sources`. For example, Python targets may want to have `PythonSources` to add extra
validation that every source file ends in `*.py`. At the same time, we still want to be able
to call `my_python_tgt.get(Sources)`, in addition to `my_python_tgt.get(PythonSources)`.
"""
subclass = next(
(
registered_field
for registered_field in registered_fields
if issubclass(registered_field, requested_field)
),
None,
)
return cast(Optional[Type[_F]], 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
`Compatibility`, `Sources`, `EntryPoint`, etc. Usually, you will want to grab the
`Field`'s inner value, e.g. `tgt.get(Compatibility).value`. (For `AsyncField`s, you would
call `await Get(SourcesResult, SourcesRequest, tgt.get(Sources).request)`).
This works with subclasses of `Field`s. For example, if you subclass `Sources` to define a
custom subclass `PythonSources`, both `python_tgt.get(PythonSources)` and
`python_tgt.get(Sources)` will return the same `PythonSources` 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(raw_value=default_raw_value, address=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 `Sources` to define a
custom subclass `PythonSources`, both `python_tgt.has_field(PythonSources)` and
`python_tgt.has_field(Sources)` 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 `Sources` to define a
custom subclass `PythonSources`, both `python_tgt.has_fields([PythonSources])` and
`python_tgt.has_fields([Sources])` 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=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=union_membership)
)
@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)
@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
@dataclass(frozen=True)
class TargetWithOrigin:
target: Target
origin: OriginSpec
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 `Files` targets and some `PythonLibrary` targets.
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(PythonTestsSources)` to `isinstance(tgt, PythonTests)`.
"""
def expect_single(self) -> Target:
assert_single_address([tgt.address for tgt in self])
return self[0]
class TargetsWithOrigins(Collection[TargetWithOrigin]):
"""A heterogeneous collection of instances of Target subclasses with the original Spec used to
resolve the target.
See the docstring for `Targets` for an explanation of the `Target`s being heterogeneous and how
you should filter out the targets you care about.
"""
def expect_single(self) -> TargetWithOrigin:
assert_single_address([tgt_with_origin.target.address for tgt_with_origin in self])
return self[0]
@memoized_property
def targets(self) -> Tuple[Target, ...]:
return tuple(tgt_with_origin.target for tgt_with_origin in self)
@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 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":
return cls(
{
target_type.alias: target_type
for target_type in sorted(target_types, key=lambda target_type: target_type.alias)
}
)
@property
def aliases(self) -> Tuple[str, ...]:
return tuple(self.aliases_to_types.keys())
@property
def types(self) -> Tuple[Type[Target], ...]:
return tuple(self.aliases_to_types.values())
# -----------------------------------------------------------------------------------------------
# Generated subtargets
# -----------------------------------------------------------------------------------------------
def generate_subtarget_address(base_target_address: Address, *, full_file_name: str) -> Address:
"""Return the address for a new target based on the original target, but with a more precise
`sources` field.
The address's target name will be the relativized file, such as `:app.json`, or `:subdir/f.txt`.
See generate_subtarget().
"""
original_spec_path = base_target_address.spec_path
relativized_file_name = PurePath(full_file_name).relative_to(original_spec_path).as_posix()
return Address(
spec_path=original_spec_path,
target_name=relativized_file_name,
generated_base_target_name=base_target_address.target_name,
)
_Tgt = TypeVar("_Tgt", bound=Target)
def generate_subtarget(base_target: _Tgt, *, full_file_name: str) -> _Tgt:
"""Generate a new target with the exact same metadata as the original, except for the `sources`
field only referring to the single file `full_file_name` and with a new address.
This is used for greater precision when using dependency inference and file arguments. When we
are able to deduce specifically which files are being used, we can use only the files we care
about, rather than the entire `sources` field.
"""
relativized_file_name = (
PurePath(full_file_name).relative_to(base_target.address.spec_path).as_posix()
)
base_target_field_values = {
field.alias: (
field.value
if isinstance(field, PrimitiveField)
else field.sanitized_raw_value # type: ignore[attr-defined]
)
for field in base_target.field_values.values()
}
generated_target_fields = (
{**base_target_field_values, Sources.alias: (relativized_file_name,)}
if base_target.has_field(Sources)
else base_target_field_values
)
target_cls = type(base_target)
return target_cls(
generated_target_fields,
address=generate_subtarget_address(base_target.address, full_file_name=full_file_name),
)
# -----------------------------------------------------------------------------------------------
# FieldSet
# -----------------------------------------------------------------------------------------------
@dataclass(frozen=True)
class _AbstractFieldSet(ABC):
required_fields: ClassVar[Tuple[Type[Field], ...]]
address: Address
@final
@classmethod
def is_valid(cls, tgt: Target) -> bool:
return tgt.has_fields(cls.required_fields)
@final
@classmethod
def valid_target_types(
cls, target_types: Iterable[Type[Target]], *, union_membership: UnionMembership
) -> Tuple[Type[Target], ...]:
return tuple(
target_type
for target_type in target_types
if target_type.class_has_fields(cls.required_fields, union_membership=union_membership)
)
def _get_field_set_fields_from_target(
field_set: Type[_AbstractFieldSet], target: Target
) -> Dict[str, Field]:
all_expected_fields: Dict[str, Type[Field]] = {
dataclass_field.name: dataclass_field.type
for dataclass_field in dataclasses.fields(field_set)
if isinstance(dataclass_field.type, type) and issubclass(dataclass_field.type, Field) # type: ignore[unreachable]
}
return {
dataclass_field_name: (
target[field_cls] if field_cls in field_set.required_fields else target.get(field_cls)
)
for dataclass_field_name, field_cls in all_expected_fields.items()
}
_FS = TypeVar("_FS", bound="FieldSet")
class FieldSet(_AbstractFieldSet, metaclass=ABCMeta):
"""An ad hoc set of fields from a target which are used by rules.
Subclasses should declare all the fields they consume as dataclass attributes. They should also
indicate which of these are required, rather than optional, through the class property
`required_fields`. When a field is optional, the default constructor for the field will be used
for any targets that do not have that field registered.
Subclasses must set `@dataclass(frozen=True)` for their declared fields to be recognized.
For example:
@dataclass(frozen=True)
class FortranTestFieldSet(FieldSet):
required_fields = (FortranSources,)
sources: FortranSources
fortran_version: FortranVersion
This field set may then created from a `Target` through the `is_valid()` and `create()`
class methods:
field_sets = [
FortranTestFieldSet.create(tgt) for tgt in targets
if FortranTestFieldSet.is_valid(tgt)
]
FieldSets are consumed like any normal dataclass:
print(field_set.address)
print(field_set.sources)
"""
@classmethod
def create(cls: Type[_FS], tgt: Target) -> _FS:
return cls( # type: ignore[call-arg]
address=tgt.address, **_get_field_set_fields_from_target(cls, tgt)
)
_FSWO = TypeVar("_FSWO", bound="FieldSetWithOrigin")
@dataclass(frozen=True)
class FieldSetWithOrigin(_AbstractFieldSet, metaclass=ABCMeta):
"""An ad hoc set of fields from a target which are used by rules, along with the original spec
used to find the original target.
See FieldSet for documentation on how subclasses should use this base class.
"""
origin: OriginSpec
@classmethod
def create(cls: Type[_FSWO], target_with_origin: TargetWithOrigin) -> _FSWO:
tgt = target_with_origin.target
return cls( # type: ignore[call-arg]
address=tgt.address,
origin=target_with_origin.origin,
**_get_field_set_fields_from_target(cls, tgt),
)
_AFS = TypeVar("_AFS", bound=_AbstractFieldSet)
@frozen_after_init
@dataclass(unsafe_hash=True)
class TargetsToValidFieldSets(Generic[_AFS]):
mapping: FrozenDict[TargetWithOrigin, Tuple[_AFS, ...]]
def __init__(self, mapping: Mapping[TargetWithOrigin, Iterable[_AFS]]) -> None:
self.mapping = FrozenDict(
{tgt_with_origin: tuple(field_sets) for tgt_with_origin, field_sets in mapping.items()}
)
@memoized_property
def field_sets(self) -> Tuple[_AFS, ...]:
return tuple(
itertools.chain.from_iterable(
field_sets_per_target for field_sets_per_target in self.mapping.values()
)
)
@memoized_property
def targets(self) -> Tuple[Target, ...]:
return tuple(tgt_with_origin.target for tgt_with_origin in self.targets_with_origins)
@memoized_property
def targets_with_origins(self) -> Tuple[TargetWithOrigin, ...]:
return tuple(self.mapping.keys())
@frozen_after_init
@dataclass(unsafe_hash=True)
class TargetsToValidFieldSetsRequest(Generic[_AFS]):
field_set_superclass: Type[_AFS]
goal_description: str
error_if_no_valid_targets: bool
expect_single_field_set: bool
# TODO: Add a `require_sources` field. To do this, figure out the dependency cycle with
# `util_rules/filter_empty_sources.py`.
def __init__(
self,
field_set_superclass: Type[_AFS],
*,
goal_description: str,
error_if_no_valid_targets: bool,
expect_single_field_set: bool = False,
) -> None:
self.field_set_superclass = field_set_superclass
self.goal_description = goal_description
self.error_if_no_valid_targets = error_if_no_valid_targets
self.expect_single_field_set = expect_single_field_set
# -----------------------------------------------------------------------------------------------
# Exception messages
# -----------------------------------------------------------------------------------------------
class InvalidFieldException(Exception):
"""Use when there's an issue with a particular field.
Suggested template:
f"The {repr(alias)} field in target {address} must ..., but ..."
"""
class InvalidFieldTypeException(InvalidFieldException):
"""This is used to ensure that the field's value conforms with the expected type for the field,
e.g. `a boolean` or `a string` or `an iterable of strings and integers`."""
def __init__(
self, address: Address, field_alias: str, raw_value: Optional[Any], *, expected_type: str
) -> None:
super().__init__(
f"The {repr(field_alias)} field in target {address} must be {expected_type}, but was "
f"`{repr(raw_value)}` with type `{type(raw_value).__name__}`."
)
class RequiredFieldMissingException(InvalidFieldException):
def __init__(self, address: Address, field_alias: str) -> None:
super().__init__(f"The {repr(field_alias)} field in target {address} must be defined.")
class InvalidFieldChoiceException(InvalidFieldException):
def __init__(
self,
address: Address,
field_alias: str,
raw_value: Optional[Any],
*,
valid_choices: Iterable[Any],
) -> None:
super().__init__(
f"The {repr(field_alias)} field in target {address} must be one of "
f"{sorted(valid_choices)}, but was {repr(raw_value)}."
)
class UnrecognizedTargetTypeException(Exception):
def __init__(
self,
target_type: str,
registered_target_types: RegisteredTargetTypes,
*,
address: Optional[Address] = None,
) -> None:
for_address = f" for address {address}" if address else ""
super().__init__(
f"Target type {repr(target_type)} is not registered{for_address}.\n\nAll valid target "
f"types: {sorted(registered_target_types.aliases)}\n\n(If {repr(target_type)} is a "
"custom target type, refer to "
"https://groups.google.com/forum/#!topic/pants-devel/WsRFODRLVZI for instructions on "
"writing a light-weight Target API binding.)"
)
# -----------------------------------------------------------------------------------------------
# Field templates
# -----------------------------------------------------------------------------------------------
T = TypeVar("T")
class ScalarField(Generic[T], PrimitiveField, metaclass=ABCMeta):
"""A field with a scalar value (vs. a compound value like a sequence or dict).
Subclasses must define the class properties `expected_type` and `expected_type_description`.
They should also override the type hints for the classmethod `compute_value` so that we use the
correct type annotation in generated documentation.
class Example(ScalarField):
alias = "example"
expected_type = MyPluginObject
expected_type_description = "a `my_plugin` object"
@classmethod
def compute_value(
cls, raw_value: Optional[MyPluginObject], *, address: Address
) -> Optional[MyPluginObject]:
return super().compute_value(raw_value, address=address)
"""
expected_type: ClassVar[Type[T]]
expected_type_description: ClassVar[str]
value: Optional[T]
default: ClassVar[Optional[T]] = None
@classmethod
def compute_value(cls, raw_value: Optional[Any], *, address: Address) -> Optional[T]:
value_or_default = super().compute_value(raw_value, address=address)
if value_or_default is not None and not isinstance(value_or_default, cls.expected_type):
raise InvalidFieldTypeException(
address, cls.alias, raw_value, expected_type=cls.expected_type_description,
)
return value_or_default
class BoolField(PrimitiveField, metaclass=ABCMeta):
"""A field whose value is a boolean.
If subclasses do not set the class property `required = True` or `default`, the value will
default to None. This can be useful to represent three states: unspecified, False, and True.
class ZipSafe(BoolField):
alias = "zip_safe"
default = True
"""
value: Optional[bool]
default: ClassVar[Optional[bool]] = None
@classmethod
def compute_value(cls, raw_value: Optional[bool], *, address: Address) -> Optional[bool]:
value_or_default = super().compute_value(raw_value, address=address)
if value_or_default is not None and not isinstance(value_or_default, bool):
raise InvalidFieldTypeException(
address, cls.alias, raw_value, expected_type="a boolean",
)
return value_or_default
class IntField(ScalarField, metaclass=ABCMeta):
expected_type = int
expected_type_description = "an integer"
@classmethod
def compute_value(cls, raw_value: Optional[int], *, address: Address) -> Optional[int]:
return super().compute_value(raw_value, address=address)
class FloatField(ScalarField, metaclass=ABCMeta):
expected_type = float
expected_type_description = "a float"
@classmethod
def compute_value(cls, raw_value: Optional[float], *, address: Address) -> Optional[float]:
return super().compute_value(raw_value, address=address)
class StringField(ScalarField, metaclass=ABCMeta):
"""A field whose value is a string.
If you expect the string to only be one of several values, set the class property
`valid_choices`.
"""
expected_type = str
expected_type_description = "a string"
valid_choices: ClassVar[Optional[Union[Type[Enum], Tuple[str, ...]]]] = None
@classmethod
def compute_value(cls, raw_value: Optional[str], *, address: Address) -> Optional[str]:
value_or_default = super().compute_value(raw_value, address=address)
if value_or_default is not None and cls.valid_choices is not None:
valid_choices = set(
cls.valid_choices
if isinstance(cls.valid_choices, tuple)
else (choice.value for choice in cls.valid_choices)
)
if value_or_default not in valid_choices:
raise InvalidFieldChoiceException(
address, cls.alias, value_or_default, valid_choices=valid_choices
)
return value_or_default
class SequenceField(Generic[T], PrimitiveField, metaclass=ABCMeta):
"""A field whose value is a homogeneous sequence.
Subclasses must define the class properties `expected_element_type` and
`expected_type_description`. They should also override the type hints for the classmethod
`compute_value` so that we use the correct type annotation in generated documentation.
class Example(SequenceField):
alias = "example"
expected_element_type = MyPluginObject
expected_type_description = "an iterable of `my_plugin` objects"
@classmethod
def compute_value(
cls, raw_value: Optional[Iterable[MyPluginObject]], *, address: Address
) -> Optional[Tuple[MyPluginObject, ...]]:
return super().compute_value(raw_value, address=address)
"""
expected_element_type: ClassVar[Type[T]]
expected_type_description: ClassVar[str]
value: Optional[Tuple[T, ...]]
default: ClassVar[Optional[Tuple[T, ...]]] = None