-
-
Notifications
You must be signed in to change notification settings - Fork 607
/
target_types.py
1300 lines (1076 loc) · 51.7 KB
/
target_types.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 logging
import os.path
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from textwrap import dedent
from typing import (
TYPE_CHECKING,
ClassVar,
Iterable,
Iterator,
Mapping,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from packaging.utils import canonicalize_name as canonicalize_project_name
from pants.backend.python.macros.python_artifact import PythonArtifact
from pants.backend.python.pip_requirement import PipRequirement
from pants.backend.python.subsystems.setup import PythonSetup
from pants.core.goals.package import OutputPathField
from pants.core.goals.run import RestartableField
from pants.core.goals.test import RuntimePackageDependenciesField
from pants.engine.addresses import Address, Addresses
from pants.engine.target import (
COMMON_TARGET_FIELDS,
AsyncFieldMixin,
BoolField,
Dependencies,
DictStringToStringSequenceField,
Field,
IntField,
InvalidFieldException,
InvalidFieldTypeException,
InvalidTargetException,
MultipleSourcesField,
NestedDictStringToStringField,
OverridesField,
ScalarField,
SecondaryOwnerMixin,
SingleSourceField,
StringField,
StringSequenceField,
Target,
TriBoolField,
ValidNumbers,
generate_file_based_overrides_field_help_message,
)
from pants.option.subsystem import Subsystem
from pants.source.filespec import Filespec
from pants.util.docutil import doc_url, git_url
from pants.util.frozendict import FrozenDict
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from pants.backend.python.subsystems.pytest import PyTest
# -----------------------------------------------------------------------------------------------
# Common fields
# -----------------------------------------------------------------------------------------------
class PythonSourceField(SingleSourceField):
# Note that Python scripts often have no file ending.
expected_file_extensions: ClassVar[tuple[str, ...]] = ("", ".py", ".pyi")
class PythonGeneratingSourcesBase(MultipleSourcesField):
expected_file_extensions: ClassVar[tuple[str, ...]] = ("", ".py", ".pyi")
class InterpreterConstraintsField(StringSequenceField):
alias = "interpreter_constraints"
help = (
"The Python interpreters this code is compatible with.\n\nEach element should be written "
"in pip-style format, e.g. `CPython==2.7.*` or `CPython>=3.6,<4`. You can leave off "
"`CPython` as a shorthand, e.g. `>=2.7` will be expanded to `CPython>=2.7`.\n\nSpecify "
"more than one element to OR the constraints, e.g. `['PyPy==3.7.*', 'CPython==3.7.*']` "
"means either PyPy 3.7 _or_ CPython 3.7.\n\nIf the field is not set, it will default to "
"the option `[python].interpreter_constraints`.\n\n"
f"See {doc_url('python-interpreter-compatibility')} for how these interpreter "
"constraints are merged with the constraints of dependencies."
)
def value_or_global_default(self, python_setup: PythonSetup) -> Tuple[str, ...]:
"""Return either the given `compatibility` field or the global interpreter constraints.
If interpreter constraints are supplied by the CLI flag, return those only.
"""
return python_setup.compatibility_or_constraints(self.value)
class UnrecognizedResolveNamesError(Exception):
def __init__(
self,
unrecognized_resolve_names: list[str],
all_valid_names: Iterable[str],
*,
description_of_origin: str,
) -> None:
# TODO(#12314): maybe implement "Did you mean?"
if len(unrecognized_resolve_names) == 1:
unrecognized_str = unrecognized_resolve_names[0]
name_description = "name"
else:
unrecognized_str = str(sorted(unrecognized_resolve_names))
name_description = "names"
super().__init__(
f"Unrecognized resolve {name_description} from {description_of_origin}: "
f"{unrecognized_str}\n\nAll valid resolve names: {sorted(all_valid_names)}"
)
class PythonResolveField(StringField, AsyncFieldMixin):
alias = "experimental_resolve"
required = False
help = (
"The resolve from `[python].experimental_resolves` to use.\n\n"
"If not defined, will default to `[python].default_resolve`.\n\n"
"Only applies if `[python].enable_resolves` is true.\n\n"
"This field is experimental and may change without the normal deprecation policy."
# TODO: Document expectations for dependencies once we validate that.
)
def value_or_default(self, python_setup: PythonSetup) -> str:
return self.value or python_setup.default_resolve
def validate(self, python_setup: PythonSetup) -> None:
"""Check that the resolve name is recognized."""
resolve = self.value_or_default(python_setup)
if resolve not in python_setup.resolves:
raise UnrecognizedResolveNamesError(
[resolve],
python_setup.resolves.keys(),
description_of_origin=f"the field `{self.alias}` in the target {self.address}",
)
def resolve_and_lockfile(self, python_setup: PythonSetup) -> tuple[str, str] | None:
"""If configured, return the resolve name with its lockfile.
Error if the resolve name is invalid.
"""
if not python_setup.enable_resolves:
return None
self.validate(python_setup)
resolve = self.value_or_default(python_setup)
return (resolve, python_setup.resolves[resolve])
class PythonCompatibleResolvesField(StringSequenceField, AsyncFieldMixin):
alias = "experimental_compatible_resolves"
required = False
help = (
"The set of resolves from `[python].experimental_resolves` that this target is "
"compatible with.\n\n"
"If not defined, will default to `[python].default_resolve`.\n\n"
"Only applies if `[python].enable_resolves` is true.\n\n"
"This field is experimental and may change without the normal deprecation policy."
# TODO: Document expectations for dependencies once we validate that.
)
def value_or_default(self, python_setup: PythonSetup) -> tuple[str, ...]:
return self.value or (python_setup.default_resolve,)
def validate(self, python_setup: PythonSetup) -> None:
"""Check that the resolve names are recognized."""
invalid_resolves = set(self.value_or_default(python_setup)) - set(python_setup.resolves)
if invalid_resolves:
raise UnrecognizedResolveNamesError(
sorted(invalid_resolves),
python_setup.resolves.keys(),
description_of_origin=f"the field `{self.alias}` in the target {self.address}",
)
# -----------------------------------------------------------------------------------------------
# `pex_binary` and `pex_binaries` target
# -----------------------------------------------------------------------------------------------
class PexBinaryDefaults(Subsystem):
options_scope = "pex-binary-defaults"
help = "Default settings for creating PEX executables."
@classmethod
def register_options(cls, register):
super().register_options(register)
register(
"--emit-warnings",
advanced=True,
type=bool,
default=True,
help=(
"Whether built PEX binaries should emit PEX warnings at runtime by default."
"\n\nCan be overridden by specifying the `emit_warnings` parameter of individual "
"`pex_binary` targets"
),
)
register(
"--resolve-local-platforms",
advanced=True,
type=bool,
default=False,
help=(
f"For each of the `{PexPlatformsField.alias}` specified for a `{PexBinary.alias}` "
"target, attempt to find a local interpreter that matches.\n\nIf a matching "
"interpreter is found, use the interpreter to resolve distributions and build any "
"that are only available in source distribution form. If no matching interpreter "
"is found (or if this option is `False`), resolve for the platform by accepting "
"only pre-built binary distributions (wheels)."
),
)
@property
def emit_warnings(self) -> bool:
return cast(bool, self.options.emit_warnings)
@property
def resolve_local_platforms(self) -> bool:
return cast(bool, self.options.resolve_local_platforms)
# See `target_types_rules.py` for a dependency injection rule.
class PexBinaryDependenciesField(Dependencies):
supports_transitive_excludes = True
class MainSpecification(ABC):
@abstractmethod
def iter_pex_args(self) -> Iterator[str]:
...
@property
@abstractmethod
def spec(self) -> str:
...
@dataclass(frozen=True)
class EntryPoint(MainSpecification):
module: str
function: str | None = None
@classmethod
def parse(cls, value: str, provenance: str | None = None) -> EntryPoint:
given = f"entry point {provenance}" if provenance else "entry point"
entry_point = value.strip()
if not entry_point:
raise ValueError(
f"The {given} cannot be blank. It must indicate a Python module by name or path "
f"and an optional nullary function in that module separated by a colon, i.e.: "
f"module_name_or_path(':'function_name)?"
)
module_or_path, sep, func = entry_point.partition(":")
if not module_or_path:
raise ValueError(f"The {given} must specify a module; given: {value!r}")
if ":" in func:
raise ValueError(
f"The {given} can only contain one colon separating the entry point's module from "
f"the entry point function in that module; given: {value!r}"
)
if sep and not func:
logger.warning(
f"Assuming no entry point function and stripping trailing ':' from the {given}: "
f"{value!r}. Consider deleting it to make it clear no entry point function is "
f"intended."
)
return cls(module=module_or_path, function=func if func else None)
def __post_init__(self):
if ":" in self.module:
raise ValueError(
"The `:` character is not valid in a module name. Given an entry point module of "
f"{self.module}. Did you mean to use EntryPoint.parse?"
)
if self.function and ":" in self.function:
raise ValueError(
"The `:` character is not valid in a function name. Given an entry point function"
f" of {self.function}."
)
def iter_pex_args(self) -> Iterator[str]:
yield "--entry-point"
yield self.spec
@property
def spec(self) -> str:
return self.module if self.function is None else f"{self.module}:{self.function}"
@dataclass(frozen=True)
class ConsoleScript(MainSpecification):
name: str
def iter_pex_args(self) -> Iterator[str]:
yield "--console-script"
yield self.name
@property
def spec(self) -> str:
return self.name
class PexEntryPointField(AsyncFieldMixin, SecondaryOwnerMixin, Field):
alias = "entry_point"
default = None
help = (
"Set the entry point, i.e. what gets run when executing `./my_app.pex`, to a module.\n\n"
"You can specify a full module like 'path.to.module' and 'path.to.module:func', or use a "
"shorthand to specify a file name, using the same syntax as the `sources` field:\n\n"
" 1) 'app.py', Pants will convert into the module `path.to.app`;\n"
" 2) 'app.py:func', Pants will convert into `path.to.app:func`.\n\n"
"You must use the file name shorthand for file arguments to work with this target.\n\n"
"You may either set this field or the `script` field, but not both. Leave off both fields "
"to have no entry point."
)
value: EntryPoint | None
@classmethod
def compute_value(cls, raw_value: Optional[str], address: Address) -> Optional[EntryPoint]:
value = super().compute_value(raw_value, address)
if value is None:
return None
if not isinstance(value, str):
raise InvalidFieldTypeException(address, cls.alias, value, expected_type="a string")
try:
return EntryPoint.parse(value, provenance=f"for {address}")
except ValueError as e:
raise InvalidFieldException(str(e))
@property
def filespec(self) -> Filespec:
if self.value is None or not self.value.module.endswith(".py"):
return {"includes": []}
full_glob = os.path.join(self.address.spec_path, self.value.module)
return {"includes": [full_glob]}
# See `target_types_rules.py` for the `ResolvePexEntryPointRequest -> ResolvedPexEntryPoint` rule.
@dataclass(frozen=True)
class ResolvedPexEntryPoint:
val: EntryPoint | None
file_name_used: bool
@dataclass(frozen=True)
class ResolvePexEntryPointRequest:
"""Determine the `entry_point` for a `pex_binary` after applying all syntactic sugar."""
entry_point_field: PexEntryPointField
class PexScriptField(Field):
alias = "script"
default = None
help = (
"Set the entry point, i.e. what gets run when executing `./my_app.pex`, to a script or "
"console_script as defined by any of the distributions in the PEX.\n\n"
"You may either set this field or the `entry_point` field, but not both. Leave off both "
"fields to have no entry point."
)
value: ConsoleScript | None
@classmethod
def compute_value(cls, raw_value: Optional[str], address: Address) -> Optional[ConsoleScript]:
value = super().compute_value(raw_value, address)
if value is None:
return None
if not isinstance(value, str):
raise InvalidFieldTypeException(address, cls.alias, value, expected_type="a string")
return ConsoleScript(value)
class PexPlatformsField(StringSequenceField):
alias = "platforms"
help = (
"The platforms the built PEX should be compatible with.\n\nThis defaults to the current "
"platform, but can be overridden to different platforms. There must be built wheels "
"available for all of the foreign platforms, rather than sdists.\n\n"
"You can give a list of multiple platforms to create a multiplatform PEX, "
"meaning that the PEX will be executable in all of the supported environments.\n\n"
"Platforms should be in the format defined by Pex "
"(https://pex.readthedocs.io/en/latest/buildingpex.html#platform), i.e. "
'PLATFORM-IMPL-PYVER-ABI (e.g. "linux_x86_64-cp-27-cp27mu", '
'"macosx_10.12_x86_64-cp-36-cp36m"):\n\n'
" - PLATFORM: the host platform, e.g. "
'"linux-x86_64", "macosx-10.12-x86_64".\n - IMPL: the Python implementation '
'abbreviation, e.g. "cp", "pp", "jp".\n - PYVER: a two-digit string representing '
'the Python version, e.g. "27", "36".\n - ABI: the ABI tag, e.g. "cp36m", '
'"cp27mu", "abi3", "none".'
)
class PexInheritPathField(StringField):
alias = "inherit_path"
valid_choices = ("false", "fallback", "prefer")
help = (
"Whether to inherit the `sys.path` (aka PYTHONPATH) of the environment that the binary "
"runs in.\n\nUse `false` to not inherit `sys.path`; use `fallback` to inherit `sys.path` "
"after packaged dependencies; and use `prefer` to inherit `sys.path` before packaged "
"dependencies."
)
# TODO(#9388): deprecate allowing this to be a `bool`.
@classmethod
def compute_value(
cls, raw_value: Optional[Union[str, bool]], address: Address
) -> Optional[str]:
if isinstance(raw_value, bool):
return "prefer" if raw_value else "false"
return super().compute_value(raw_value, address)
class PexStripEnvField(BoolField):
alias = "strip_pex_env"
default = True
help = (
"Whether or not to strip the PEX runtime environment of `PEX*` environment variables.\n\n"
"Most applications have no need for the `PEX*` environment variables that are used to "
"control PEX startup; so these variables are scrubbed from the environment by Pex before "
"transferring control to the application by default. This prevents any subprocesses that "
"happen to execute other PEX files from inheriting these control knob values since most "
"would be undesired; e.g.: PEX_MODULE or PEX_PATH."
)
class PexIgnoreErrorsField(BoolField):
alias = "ignore_errors"
default = False
help = "Should PEX ignore when it cannot resolve dependencies?"
class PexShebangField(StringField):
alias = "shebang"
help = (
"Set the generated PEX to use this shebang, rather than the default of PEX choosing a "
"shebang based on the interpreter constraints.\n\nThis influences the behavior of running "
"`./result.pex`. You can ignore the shebang by instead running "
"`/path/to/python_interpreter ./result.pex`."
)
class PexEmitWarningsField(TriBoolField):
alias = "emit_warnings"
help = (
"Whether or not to emit PEX warnings at runtime.\n\nThe default is determined by the "
"option `emit_warnings` in the `[pex-binary-defaults]` scope."
)
def value_or_global_default(self, pex_binary_defaults: PexBinaryDefaults) -> bool:
if self.value is None:
return pex_binary_defaults.emit_warnings
return self.value
class PexResolveLocalPlatformsField(TriBoolField):
alias = "resolve_local_platforms"
help = (
f"For each of the `{PexPlatformsField.alias}` specified, attempt to find a local "
"interpreter that matches.\n\nIf a matching interpreter is found, use the interpreter to "
"resolve distributions and build any that are only available in source distribution form. "
"If no matching interpreter is found (or if this option is `False`), resolve for the "
"platform by accepting only pre-built binary distributions (wheels)."
)
def value_or_global_default(self, pex_binary_defaults: PexBinaryDefaults) -> bool:
if self.value is None:
return pex_binary_defaults.resolve_local_platforms
return self.value
class PexExecutionMode(Enum):
ZIPAPP = "zipapp"
VENV = "venv"
class PexExecutionModeField(StringField):
alias = "execution_mode"
valid_choices = PexExecutionMode
expected_type = str
default = PexExecutionMode.ZIPAPP.value
help = (
"The mode the generated PEX file will run in.\n\nThe traditional PEX file runs in a "
f"modified {PexExecutionMode.ZIPAPP.value!r} mode (See: "
"https://www.python.org/dev/peps/pep-0441/) where zipped internal code and dependencies "
"are first unpacked to disk. This mode achieves the fastest cold start times and may, for "
"example be the best choice for cloud lambda functions.\n\nThe fastest execution mode in "
f"the steady state is {PexExecutionMode.VENV.value!r}, which generates a virtual "
"environment from the PEX file on first run, but then achieves near native virtual "
"environment start times. This mode also benefits from a traditional virtual environment "
"`sys.path`, giving maximum compatibility with stdlib and third party APIs."
)
class PexLayout(Enum):
ZIPAPP = "zipapp"
PACKED = "packed"
LOOSE = "loose"
class PexLayoutField(StringField):
alias = "layout"
valid_choices = PexLayout
expected_type = str
default = PexLayout.ZIPAPP.value
help = (
"The layout used for the PEX binary.\n\nBy default, a PEX is created as a single file "
"zipapp, but either a packed or loose directory tree based layout can be chosen instead."
"\n\nA packed layout PEX is an executable directory structure designed to have "
"cache-friendly characteristics for syncing incremental updates to PEXed applications over "
"a network. At the top level of the packed directory tree there is an executable "
"`__main__.py` script. The directory can also be executed by passing its path to a Python "
"executable; e.g: `python packed-pex-dir/`. The Pex bootstrap code and all dependency code "
"are packed into individual zip files for efficient caching and syncing.\n\nA loose layout "
"PEX is similar to a packed PEX, except that neither the Pex bootstrap code nor the "
"dependency code are packed into zip files, but are instead present as collections of "
"loose files in the directory tree providing different caching and syncing tradeoffs.\n\n"
"Both zipapp and packed layouts install themselves in the `$PEX_ROOT` as loose apps by "
"default before executing, but these layouts compose with "
f"`{PexExecutionModeField.alias}='{PexExecutionMode.ZIPAPP.value}'` as well."
)
class PexIncludeRequirementsField(BoolField):
alias = "include_requirements"
default = True
help = (
"Whether to include the third party requirements the binary depends on in the "
"packaged PEX file."
)
class PexIncludeToolsField(BoolField):
alias = "include_tools"
default = False
help = (
"Whether to include Pex tools in the PEX bootstrap code.\n\nWith tools included, the "
"generated PEX file can be executed with `PEX_TOOLS=1 <pex file> --help` to gain access "
"to all the available tools."
)
_PEX_BINARY_COMMON_FIELDS = (
*COMMON_TARGET_FIELDS,
InterpreterConstraintsField,
PythonResolveField,
PexBinaryDependenciesField,
PexPlatformsField,
PexResolveLocalPlatformsField,
PexInheritPathField,
PexStripEnvField,
PexIgnoreErrorsField,
PexShebangField,
PexEmitWarningsField,
PexLayoutField,
PexExecutionModeField,
PexIncludeRequirementsField,
PexIncludeToolsField,
RestartableField,
)
class PexBinary(Target):
alias = "pex_binary"
core_fields = (
*_PEX_BINARY_COMMON_FIELDS,
PexEntryPointField,
PexScriptField,
OutputPathField,
)
help = (
"A Python target that can be converted into an executable PEX file.\n\nPEX files are "
"self-contained executable files that contain a complete Python environment capable of "
f"running the target. For more information, see {doc_url('pex-files')}."
)
def validate(self) -> None:
if self[PexEntryPointField].value is not None and self[PexScriptField].value is not None:
raise InvalidTargetException(
f"The `{self.alias}` target {self.address} cannot set both the "
f"`{self[PexEntryPointField].alias}` and `{self[PexScriptField].alias}` fields at "
"the same time. To fix, please remove one."
)
class PexEntryPointsField(StringSequenceField, AsyncFieldMixin):
alias = "entry_points"
default = None
help = (
"The entry points for each binary, i.e. what gets run when when executing `./my_app.pex.`"
"\n\n"
"Use a file name, relative to the BUILD file, like `app.py`. You can also set the "
"function to run, like `app.py:func`. Pants will convert these file names into well-formed "
"entry points, like `app.py:func` into `path.to.app:func.`"
"\n\n"
"If you want the entry point to be for a third-party dependency or to use a console "
"script, use the `pex_binary` target directly."
)
class PexBinariesOverrideField(OverridesField):
help = (
f"Override the field values for generated `{PexBinary.alias}` targets.\n\n"
"Expects a dictionary mapping values from the `entry_points` field to a dictionary for "
"their overrides. You may either use a single string or a tuple of strings to override "
"multiple targets.\n\n"
"For example:\n\n```\n"
"overrides={\n"
' "foo.py": {"execution_mode": "venv"]},\n'
' "bar.py:main": {"restartable": True]},\n'
' ("foo.py", "bar.py:main"): {"tags": ["legacy"]},\n'
"}"
"\n```\n\n"
"Every key is validated to belong to this target's `entry_points` field.\n\n"
f"If you'd like to override a field's value for every `{PexBinary.alias}` target "
"generated by this target, change the field directly on this target rather than using the "
"`overrides` field.\n\n"
"You can specify the same entry_point in multiple keys, so long as you don't override the "
"same field more than one time for the entry_point."
)
class PexBinariesGeneratorTarget(Target):
alias = "pex_binaries"
core_fields = (
*_PEX_BINARY_COMMON_FIELDS,
PexEntryPointsField,
PexBinariesOverrideField,
)
help = (
"Generate a `pex_binary` target for each entry_point in the `entry_points` field."
"\n\n"
"This is solely meant to reduce duplication when you have multiple scripts in the same "
"directory; it's valid to use a distinct `pex_binary` target for each script/binary "
"instead."
"\n\n"
"This target generator does not work well to generate `pex_binary` targets where the entry "
"point is for a third-party dependency. Dependency inference will not work for those, so "
"you will have to set lots of custom metadata for each binary; prefer an explicit "
"`pex_binary` target in that case. This target generator works best when the entry point "
"is a first-party file, like `app.py` or `app.py:main`."
)
# -----------------------------------------------------------------------------------------------
# `python_test` and `python_tests` targets
# -----------------------------------------------------------------------------------------------
class PythonTestSourceField(PythonSourceField):
expected_file_extensions = (".py", "") # Note that this does not include `.pyi`.
def validate_resolved_files(self, files: Sequence[str]) -> None:
super().validate_resolved_files(files)
file = files[0]
file_name = os.path.basename(file)
if file_name == "conftest.py":
raise InvalidFieldException(
f"The {repr(self.alias)} field in target {self.address} should not be set to the "
f"file 'conftest.py', but was set to {repr(self.value)}.\n\nInstead, use a "
"`python_source` target or the target generator `python_test_utils`. You can run "
f"`./pants tailor` after removing this target ({self.address}) to autogenerate a "
"`python_test_utils` target."
)
class PythonTestsDependenciesField(Dependencies):
supports_transitive_excludes = True
class PythonTestsTimeoutField(IntField):
alias = "timeout"
help = (
"A timeout (in seconds) used by each test file belonging to this target.\n\n"
"If unset, will default to `[pytest].timeout_default`; if that option is also unset, "
"then the test will never time out. Will never exceed `[pytest].timeout_maximum`. Only "
"applies if the option `--pytest-timeouts` is set to true (the default)."
)
valid_numbers = ValidNumbers.positive_only
def calculate_from_global_options(self, pytest: PyTest) -> Optional[int]:
"""Determine the timeout (in seconds) after applying global `pytest` options."""
if not pytest.timeouts_enabled:
return None
if self.value is None:
if pytest.timeout_default is None:
return None
result = pytest.timeout_default
else:
result = self.value
if pytest.timeout_maximum is not None:
return min(result, pytest.timeout_maximum)
return result
class PythonTestsExtraEnvVarsField(StringSequenceField):
alias = "extra_env_vars"
help = (
"Additional environment variables to include in test processes. "
"Entries are strings in the form `ENV_VAR=value` to use explicitly; or just "
"`ENV_VAR` to copy the value of a variable in Pants's own environment. "
"This will be merged with and override values from [test].extra_env_vars."
)
class SkipPythonTestsField(BoolField):
alias = "skip_tests"
default = False
help = "If true, don't run this target's tests."
_PYTHON_TEST_COMMON_FIELDS = (
*COMMON_TARGET_FIELDS,
InterpreterConstraintsField,
PythonResolveField,
PythonTestsDependenciesField,
PythonTestsTimeoutField,
RuntimePackageDependenciesField,
PythonTestsExtraEnvVarsField,
SkipPythonTestsField,
)
class PythonTestTarget(Target):
alias = "python_test"
core_fields = (*_PYTHON_TEST_COMMON_FIELDS, PythonTestSourceField)
help = (
"A single Python test file, written in either Pytest style or unittest style.\n\n"
"All test util code, including `conftest.py`, should go into a dedicated `python_source` "
"target and then be included in the `dependencies` field. (You can use the "
"`python_test_utils` target to generate these `python_source` targets.)\n\n"
f"See {doc_url('python-test-goal')}"
)
class PythonTestsGeneratingSourcesField(PythonGeneratingSourcesBase):
expected_file_extensions = (".py", "") # Note that this does not include `.pyi`.
default = ("test_*.py", "*_test.py", "tests.py")
def validate_resolved_files(self, files: Sequence[str]) -> None:
super().validate_resolved_files(files)
# We don't technically need to error for `conftest.py` here because `PythonTestSourceField`
# already validates this, but we get a better error message this way so that users don't
# have to reason about generated targets.
conftest_files = [fp for fp in files if os.path.basename(fp) == "conftest.py"]
if conftest_files:
raise InvalidFieldException(
f"The {repr(self.alias)} field in target {self.address} should not include the "
f"file 'conftest.py', but included these: {conftest_files}.\n\nInstead, use a "
"`python_source` target or the target generator `python_test_utils`. You can run "
f"`./pants tailor` after removing the files from the {repr(self.alias)} field of "
f"this target ({self.address}) to autogenerate a `python_test_utils` target."
)
class PythonTestsOverrideField(OverridesField):
help = generate_file_based_overrides_field_help_message(
PythonTestTarget.alias,
(
"overrides={\n"
' "foo_test.py": {"timeout": 120]},\n'
' "bar_test.py": {"timeout": 200]},\n'
' ("foo_test.py", "bar_test.py"): {"tags": ["slow_tests"]},\n'
"}"
),
)
class PythonTestsGeneratorTarget(Target):
alias = "python_tests"
core_fields = (
*_PYTHON_TEST_COMMON_FIELDS,
PythonTestsGeneratingSourcesField,
PythonTestsOverrideField,
)
help = "Generate a `python_test` target for each file in the `sources` field."
# -----------------------------------------------------------------------------------------------
# `python_source`, `python_sources`, and `python_test_utils` targets
# -----------------------------------------------------------------------------------------------
class PythonSourceTarget(Target):
alias = "python_source"
core_fields = (
*COMMON_TARGET_FIELDS,
InterpreterConstraintsField,
Dependencies,
PythonSourceField,
)
help = "A single Python source file."
class PythonSourcesOverridesField(OverridesField):
help = generate_file_based_overrides_field_help_message(
PythonSourceTarget.alias,
(
"overrides={\n"
' "foo.py": {"skip_pylint": True]},\n'
' "bar.py": {"skip_flake8": True]},\n'
' ("foo.py", "bar.py"): {"tags": ["linter_disabled"]},\n'
"}"
),
)
class PythonTestUtilsGeneratingSourcesField(PythonGeneratingSourcesBase):
default = ("conftest.py", "test_*.pyi", "*_test.pyi", "tests.pyi")
class PythonSourcesGeneratingSourcesField(PythonGeneratingSourcesBase):
default = (
("*.py", "*.pyi")
+ tuple(f"!{pat}" for pat in PythonTestsGeneratingSourcesField.default)
+ tuple(f"!{pat}" for pat in PythonTestUtilsGeneratingSourcesField.default)
)
class PythonTestUtilsGeneratorTarget(Target):
alias = "python_test_utils"
# Keep in sync with `PythonSourcesGeneratorTarget`, outside of the `sources` field.
core_fields = (
*COMMON_TARGET_FIELDS,
InterpreterConstraintsField,
Dependencies,
PythonTestUtilsGeneratingSourcesField,
PythonSourcesOverridesField,
)
help = (
"Generate a `python_source` target for each file in the `sources` field.\n\n"
"This target generator is intended for test utility files like `conftest.py`, although it "
"behaves identically to the `python_sources` target generator and you can safely use that "
"instead. This target only exists to help you better model and keep separate test support "
"files vs. production files."
)
class PythonSourcesGeneratorTarget(Target):
alias = "python_sources"
# Keep in sync with `PythonTestUtilsGeneratorTarget`, outside of the `sources` field.
core_fields = (
*COMMON_TARGET_FIELDS,
InterpreterConstraintsField,
Dependencies,
PythonSourcesGeneratingSourcesField,
PythonSourcesOverridesField,
)
help = (
"Generate a `python_source` target for each file in the `sources` field.\n\n"
"You can either use this target generator or `python_test_utils` for test utility files "
"like `conftest.py`. They behave identically, but can help to better model and keep "
"separate test support files vs. production files."
)
# -----------------------------------------------------------------------------------------------
# `python_requirement` target
# -----------------------------------------------------------------------------------------------
def format_invalid_requirement_string_error(
value: str, e: Exception, *, description_of_origin: str
) -> str:
prefix = f"Invalid requirement '{value}' in {description_of_origin}: {e}"
# We check if they're using Pip-style VCS requirements, and redirect them to instead use PEP
# 440 direct references. See https://pip.pypa.io/en/stable/reference/pip_install/#vcs-support.
recognized_vcs = {"git", "hg", "svn", "bzr"}
if all(f"{vcs}+" not in value for vcs in recognized_vcs):
return prefix
return dedent(
f"""\
{prefix}
It looks like you're trying to use a pip VCS-style requirement?
Instead, use a direct reference (PEP 440).
Instead of this style:
git+https://github.com/django/django.git#egg=Django
git+https://github.com/django/django.git@stable/2.1.x#egg=Django
git+https://github.com/django/django.git@fd209f62f1d83233cc634443cfac5ee4328d98b8#egg=Django
Use this style, where the first value is the name of the dependency:
Django@ git+https://github.com/django/django.git
Django@ git+https://github.com/django/django.git@stable/2.1.x
Django@ git+https://github.com/django/django.git@fd209f62f1d83233cc634443cfac5ee4328d98b8
"""
)
class _PipRequirementSequenceField(Field):
value: tuple[PipRequirement, ...]
@classmethod
def compute_value(
cls, raw_value: Optional[Iterable[str]], address: Address
) -> Tuple[PipRequirement, ...]:
value = super().compute_value(raw_value, address)
if value is None:
return ()
invalid_type_error = InvalidFieldTypeException(
address,
cls.alias,
value,
expected_type="an iterable of pip-style requirement strings (e.g. a list)",
)
if isinstance(value, str) or not isinstance(value, collections.abc.Iterable):
raise invalid_type_error
result = []
for v in value:
# We allow passing a pre-parsed `PipRequirement`. This is intended for macros which
# might have already parsed so that we can avoid parsing multiple times.
if isinstance(v, PipRequirement):
result.append(v)
elif isinstance(v, str):
try:
parsed = PipRequirement.parse(v)
except Exception as e:
raise InvalidFieldException(
format_invalid_requirement_string_error(
v,
e,
description_of_origin=(
f"the '{cls.alias}' field for the target {address}"
),
)
)
result.append(parsed)
else:
raise invalid_type_error
return tuple(result)
class PythonRequirementsField(_PipRequirementSequenceField):
alias = "requirements"
required = True
help = (
'A pip-style requirement string, e.g. `["Django==3.2.8"]`.\n\n'
"You can specify multiple requirements for the same project in order to use environment "
'markers, such as `["foo>=1.2,<1.3 ; python_version>\'3.6\'", "foo==0.9 ; '
"python_version<'3'\"]`.\n\n"
"If the requirement depends on some other requirement to work, such as needing "
"`setuptools` to be built, use the `dependencies` field instead."
)
_default_module_mapping_url = git_url(
"src/python/pants/backend/python/dependency_inference/default_module_mapping.py"
)
class PythonRequirementModulesField(StringSequenceField):
alias = "modules"
help = (
"The modules this requirement provides (used for dependency inference).\n\n"
'For example, the requirement `setuptools` provides `["setuptools", "pkg_resources", '
'"easy_install"]`.\n\n'
"Usually you can leave this field off. If unspecified, Pants will first look at the "
f"default module mapping ({_default_module_mapping_url}), and then will default to "
"the normalized project name. For example, the requirement `Django` would default to "
"the module `django`.\n\n"
"Mutually exclusive with the `type_stub_modules` field."
)
class PythonRequirementTypeStubModulesField(StringSequenceField):
alias = "type_stub_modules"
help = (
"The modules this requirement provides if the requirement is a type stub (used for "
"dependency inference).\n\n"
'For example, the requirement `types-requests` provides `["requests"]`.\n\n'
"Usually you can leave this field off. If unspecified, Pants will first look at the "
f"default module mapping ({_default_module_mapping_url}). If not found _and_ the "
"requirement name starts with `types-` or `stubs-`, or ends with `-types` or `-stubs`, "
"will default to that requirement name without the prefix/suffix. For example, "
"`types-requests` would default to `requests`. Otherwise, will be treated like a normal "
"requirement (see the `modules` field).\n\n"
"Mutually exclusive with the `modules` field."
)
def normalize_module_mapping(
mapping: Mapping[str, Iterable[str]] | None
) -> FrozenDict[str, tuple[str, ...]]:
return FrozenDict({canonicalize_project_name(k): tuple(v) for k, v in (mapping or {}).items()})