repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
listlengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
pantsbuild/pants
18,866
pantsbuild__pants-18866
[ "18564" ]
6b9c2f44bd81741434b6a4f670a6667b87822c91
diff --git a/src/python/pants/engine/streaming_workunit_handler.py b/src/python/pants/engine/streaming_workunit_handler.py --- a/src/python/pants/engine/streaming_workunit_handler.py +++ b/src/python/pants/engine/streaming_workunit_handler.py @@ -23,6 +23,7 @@ from pants.goal.run_tracker import RunTracker from pants.option.options_bootstrapper import OptionsBootstrapper from pants.util.logging import LogLevel +from pants.util.strutil import softwrap logger = logging.getLogger(__name__) @@ -114,9 +115,33 @@ def get_expanded_specs(self) -> ExpandedSpecs: targets_dict: dict[str, list[TargetInfo]] = {str(addr): [] for addr in unexpanded_addresses} for target in expanded_targets: - source = targets_dict.get(str(target.address.spec), None) + target_spec = str(target.address.spec) + source = targets_dict.get(target_spec) if source is None: - source = targets_dict[str(target.address.maybe_convert_to_target_generator())] + target_gen_spec = str(target.address.maybe_convert_to_target_generator()) + source = targets_dict.get(target_gen_spec) + if source is None: + # This is a thing, that may need investigating to be fully understood. + # merely patches over a crash here. See #18564. + logger.warn( + softwrap( + f""" + Unknown source address for target: {target_spec} + Target address generator: {target_gen_spec} + + Input params: + {params} + + Unexpanded addresses: + {unexpanded_addresses} + + Expanded targets: + {expanded_targets} + """ + ) + ) + targets_dict[target_gen_spec or target_spec] = source = [] + source.append( TargetInfo( filename=(
`KeyError` in `StreamingWorkunitContext.get_expanded_specs()` **Describe the bug** We've started to observe this error at work, occasionally: ``` Exception in thread Thread-1: Traceback (most recent call last): File "/github/home/.cache/nce/cdc3a4cfddcd63b6cebdd75b14970e02d8ef0ac5be4d350e57ab5df56c19e85e/cpython-3.9.15+20221106-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/github/home/.cache/nce/6621291ed4120fa45607b367abf7786ce496f389f27240712a63c31f1c438c21/bindings/venvs/2.16.0a0/lib/python3.9/site-packages/pants/engine/streaming_workunit_handler.py", line 298, in run self.poll_workunits(finished=True) File "/github/home/.cache/nce/6621291ed4120fa45607b367abf7786ce496f389f27240712a63c31f1c438c21/bindings/venvs/2.16.0a0/lib/python3.9/site-packages/pants/engine/streaming_workunit_handler.py", line 281, in poll_workunits callback( File "/github/home/.cache/pants/named_caches/pex_root/venvs/s/aad2bc99/venv/lib/python3.9/site-packages/toolchain/pants/buildsense/reporter.py", line 98, in __call__ self.handle_workunits( File "/github/home/.cache/pants/named_caches/pex_root/venvs/s/aad2bc99/venv/lib/python3.9/site-packages/toolchain/pants/buildsense/reporter.py", line 126, in handle_workunits self._on_finish(context, self._call_count, work_units_map) File "/github/home/.cache/pants/named_caches/pex_root/venvs/s/aad2bc99/venv/lib/python3.9/site-packages/toolchain/pants/buildsense/reporter.py", line 152, in _on_finish run_tracker_info = self._get_run_tracker_info(context) File "/github/home/.cache/pants/named_caches/pex_root/venvs/s/aad2bc99/venv/lib/python3.9/site-packages/toolchain/pants/buildsense/reporter.py", line 183, in _get_run_tracker_info targets_specs = _get_expanded_specs(context) File "/github/home/.cache/pants/named_caches/pex_root/venvs/s/aad2bc99/venv/lib/python3.9/site-packages/toolchain/pants/buildsense/reporter.py", line 201, in _get_expanded_specs targets = context.get_expanded_specs().targets File "/github/home/.cache/nce/6621291ed4120fa45607b367abf7786ce496f389f27240712a63c31f1c438c21/bindings/venvs/2.16.0a0/lib/python3.9/site-packages/pants/engine/streaming_workunit_handler.py", line 119, in get_expanded_specs source = targets_dict[str(target.address.maybe_convert_to_target_generator())] KeyError: 'src/python/.../files:files' Error: Process completed with exit code 1. ``` It is for different target addresses, but so far they've all been for a `python_sources` target. **Pants version** `2.16.0a0` **OS** Linux (ubuntu, GitHub CI runner) **Additional info** Started when we switched from the old pants bootstrap script to use `scie-pants`. We do use parametrizations for multiple resolves. https://github.com/pantsbuild/pants/blob/d37d57a0640e7171d9174859d8fc69f5cde8b975/src/python/pants/engine/streaming_workunit_handler.py#L115-L120
2023-04-30T21:48:21
pantsbuild/pants
18,867
pantsbuild__pants-18867
[ "18500" ]
6b9c2f44bd81741434b6a4f670a6667b87822c91
diff --git a/src/python/pants/help/help_printer.py b/src/python/pants/help/help_printer.py --- a/src/python/pants/help/help_printer.py +++ b/src/python/pants/help/help_printer.py @@ -227,7 +227,7 @@ def _print_top_level_help(self, thing: str, show_advanced: bool) -> None: elif thing == "api-types": self._print_all_api_types() elif thing == "backends": - self._print_all_backends() + self._print_all_backends(show_advanced) elif thing == "symbols": self._print_all_symbols(show_advanced) @@ -343,7 +343,7 @@ def _print_all_api_types(self) -> None: f"Use `{self.maybe_green(api_help_cmd)}` to get help for a specific API type or rule.\n" ) - def _print_all_backends(self) -> None: + def _print_all_backends(self, include_experimental: bool) -> None: self._print_title("Backends") print( softwrap( @@ -360,6 +360,8 @@ def _print_all_backends(self) -> None: provider_col_width = 3 + max(map(len, (info.provider for info in backends.values()))) enabled_col_width = 4 for info in backends.values(): + if not (include_experimental or info.enabled) and ".experimental." in info.name: + continue enabled = "[*] " if info.enabled else "[ ] " name_col_width = max( len(info.name) + 1, self._width - enabled_col_width - provider_col_width
`help backends` and `help-advanced backends` show the same content (both include preview/experimental backends) **Describe the bug** Under the `help` goal: `help backends` and `help-advanced backends` show the same content (both include preview/experimental backends). Only the `-advanced` variant should show the preview/experimental backends (according to the `help` output). ``` Usage: ... ./pants help backends List all available backends. ./pants help-advanced backends List all backends, including experimental/preview. ... ``` Either remove the experimental/preview backends from the `help backends` view, or just remove the `help-advanced` version. **Pants version** 2.16.0a0 **OS** Both
2023-04-30T21:48:57
pantsbuild/pants
18,869
pantsbuild__pants-18869
[ "18504" ]
6b9c2f44bd81741434b6a4f670a6667b87822c91
diff --git a/src/python/pants/help/help_printer.py b/src/python/pants/help/help_printer.py --- a/src/python/pants/help/help_printer.py +++ b/src/python/pants/help/help_printer.py @@ -419,6 +419,11 @@ def print_cmd(args: str, desc: str): print_cmd("help tools", "List all external tools.") print_cmd("help backends", "List all available backends.") print_cmd("help-advanced backends", "List all backends, including experimental/preview.") + print_cmd("help symbols", "List available BUILD file symbols.") + print_cmd( + "help-advanced symbols", + "List all available BUILD file symbols, including target types.", + ) print_cmd("help api-types", "List all plugin API types.") print_cmd("help global", "Help for global options.") print_cmd("help-advanced global", "Help for global advanced options.")
`help` output does not mention `symbols` **Describe the bug** `./pants help symbols` was added in #18378. But `./pants help` and `./pants help-advanced` do not mention it. Also, `./pants help [name]` should also mention `symbols` as a valid type of name. **Pants version** 2.16.0a0 **OS** both
2023-04-30T21:49:48
pantsbuild/pants
18,877
pantsbuild__pants-18877
[ "18779" ]
c539080e3a26f5f37f447dfa856a757a9033dc8b
diff --git a/src/python/pants/backend/python/util_rules/pex.py b/src/python/pants/backend/python/util_rules/pex.py --- a/src/python/pants/backend/python/util_rules/pex.py +++ b/src/python/pants/backend/python/util_rules/pex.py @@ -615,10 +615,10 @@ async def build_pex( if request.main is not None: argv.extend(request.main.iter_pex_args()) - for injected_arg in request.inject_args: - argv.extend(["--inject-args", str(injected_arg)]) - for k, v in sorted(request.inject_env.items()): - argv.extend(["--inject-env", f"{k}={v}"]) + argv.extend( + f"--inject-args={shlex.quote(injected_arg)}" for injected_arg in request.inject_args + ) + argv.extend(f"--inject-env={k}={v}" for k, v in sorted(request.inject_env.items())) # TODO(John Sirois): Right now any request requirements will shadow corresponding pex path # requirements, which could lead to problems. Support shading python binaries.
diff --git a/src/python/pants/backend/python/goals/package_pex_binary_integration_test.py b/src/python/pants/backend/python/goals/package_pex_binary_integration_test.py --- a/src/python/pants/backend/python/goals/package_pex_binary_integration_test.py +++ b/src/python/pants/backend/python/goals/package_pex_binary_integration_test.py @@ -177,8 +177,8 @@ def test_layout(rule_runner: RuleRunner, layout: PexLayout) -> None: """\ import os import sys - print(f"FOO={os.environ.get('FOO')}") - print(f"BAR={os.environ.get('BAR')}") + for env in ["FOO", "--inject-arg", "quotes '"]: + print(f"{env}={os.environ.get(env)}") print(f"ARGV={sys.argv[1:]}") """ ), @@ -187,8 +187,8 @@ def test_layout(rule_runner: RuleRunner, layout: PexLayout) -> None: python_sources(name="lib") pex_binary( entry_point="app.py", - args=['123', 'abc'], - env={{'FOO': 'xxx', 'BAR': 'yyy'}}, + args=['123', 'abc', '--inject-env', "quotes 'n spaces"], + env={{'FOO': 'xxx', '--inject-arg': 'yyy', "quotes '": 'n spaces'}}, layout="{layout.value}", ) """ @@ -212,8 +212,9 @@ def test_layout(rule_runner: RuleRunner, layout: PexLayout) -> None: stdout = dedent( """\ FOO=xxx - BAR=yyy - ARGV=['123', 'abc'] + --inject-arg=yyy + quotes '=n spaces + ARGV=['123', 'abc', '--inject-env', "quotes 'n spaces"] """ ).encode() assert stdout == subprocess.run([executable], check=True, stdout=subprocess.PIPE).stdout
`pex_binary().args` are not properly escaped. **Describe the bug** If you attempt to inject any `--args`, `pex` will complain like: ``` pex: error: argument --inject-args: expected one argument ``` **Pants version** 2.16.0rc0 **Additional info** [Slack thread](https://pantsbuild.slack.com/archives/C0D7TNJHL/p1682003882696899) These args needs to be escaped: https://github.com/pantsbuild/pants/blob/1aca34961105f98c2dd63addd37f9e5cfc49ee9b/src/python/pants/backend/python/util_rules/pex.py#L586-L587 Introduced in #17905
Example repro: ```python pex_binary( name="inference-server", layout="packed", include_tools=True, dependencies=["./ackbar/inference_server"], platforms=["linux_x86_64-cp-310-cp310"], script="uvicorn", args=["ackbar.inference_server.app:app", "--host", "0.0.0.0", "--port", "8080"], ) ``` The escaping will work but it confuses me at least as to whether it does - I had to test. Another way to fix is to `f"--inject-args={injected_arg}"`, which, at least to me, much more clearly always works.
2023-05-01T22:12:27
pantsbuild/pants
18,893
pantsbuild__pants-18893
[ "18509" ]
42efbd0b350d5a5e4cb45793cd29c4b12d1fa9eb
diff --git a/src/python/pants/backend/build_files/fix/deprecations/renamed_targets_rules.py b/src/python/pants/backend/build_files/fix/deprecations/renamed_targets_rules.py --- a/src/python/pants/backend/build_files/fix/deprecations/renamed_targets_rules.py +++ b/src/python/pants/backend/build_files/fix/deprecations/renamed_targets_rules.py @@ -4,6 +4,7 @@ from __future__ import annotations import tokenize +from dataclasses import dataclass from pants.backend.build_files.fix.base import FixBuildFilesRequest from pants.backend.build_files.fix.deprecations.base import FixBUILDFileRequest, FixedBUILDFile @@ -22,38 +23,45 @@ class RenameTargetsInFilesRequest(FixBuildFilesRequest): tool_subsystem = BUILDDeprecationsFixer -class RenameTargetsInFileRequest(FrozenDict[str, str]): +class RenameTargetsInFileRequest(FixBUILDFileRequest): """Deprecated target type names to new names.""" +@dataclass(frozen=True) +class RenamedTargetTypes: + """Map deprecated field names to their new name, per target.""" + + target_renames: FrozenDict[str, str] + + @rule def determine_renamed_target_types( target_types: RegisteredTargetTypes, -) -> RenameTargetsInFileRequest: - return RenameTargetsInFileRequest( - { - tgt.deprecated_alias: tgt.alias - for tgt in target_types.types - if tgt.deprecated_alias is not None - } +) -> RenamedTargetTypes: + return RenamedTargetTypes( + FrozenDict( + { + tgt.deprecated_alias: tgt.alias + for tgt in target_types.types + if tgt.deprecated_alias is not None + } + ) ) -class RenameRequest(FixBUILDFileRequest): - pass - - @rule def fix_single( - request: RenameRequest, - renamed_target_types: RenameTargetsInFileRequest, + request: RenameTargetsInFileRequest, + renamed_target_types: RenamedTargetTypes, ) -> FixedBUILDFile: tokens = request.tokenize() def should_be_renamed(token: tokenize.TokenInfo) -> bool: no_indentation = token.start[1] == 0 if not ( - token.type is tokenize.NAME and token.string in renamed_target_types and no_indentation + token.type is tokenize.NAME + and token.string in renamed_target_types.target_renames + and no_indentation ): return False # Ensure that the next token is `(` @@ -70,7 +78,7 @@ def should_be_renamed(token: tokenize.TokenInfo) -> bool: line_index = token.start[0] - 1 line = updated_text_lines[line_index] suffix = line[token.end[1] :] - new_symbol = renamed_target_types[token.string] + new_symbol = renamed_target_types.target_renames[token.string] updated_text_lines[line_index] = f"{new_symbol}{suffix}" return FixedBUILDFile(request.path, content="".join(updated_text_lines).encode("utf-8")) @@ -82,7 +90,7 @@ async def fix( ) -> FixResult: digest_contents = await Get(DigestContents, Digest, request.snapshot.digest) fixed_contents = await MultiGet( - Get(FixedBUILDFile, RenameRequest(file_content.path, file_content.content)) + Get(FixedBUILDFile, RenameTargetsInFileRequest(file_content.path, file_content.content)) for file_content in digest_contents ) snapshot = await Get( diff --git a/src/python/pants/core/goals/update_build_files.py b/src/python/pants/core/goals/update_build_files.py --- a/src/python/pants/core/goals/update_build_files.py +++ b/src/python/pants/core/goals/update_build_files.py @@ -381,7 +381,7 @@ async def maybe_rename_deprecated_targets( old_bytes = "\n".join(request.lines).encode("utf-8") new_content = await Get( FixedBUILDFile, - renamed_fields_rules.RenameFieldsInFileRequest(path=request.path, content=old_bytes), + renamed_targets_rules.RenameTargetsInFileRequest(path=request.path, content=old_bytes), ) return RewrittenBuildFile(
diff --git a/src/python/pants/backend/build_files/fix/deprecations/renamed_targets_rules_test.py b/src/python/pants/backend/build_files/fix/deprecations/renamed_targets_rules_test.py --- a/src/python/pants/backend/build_files/fix/deprecations/renamed_targets_rules_test.py +++ b/src/python/pants/backend/build_files/fix/deprecations/renamed_targets_rules_test.py @@ -6,10 +6,11 @@ import pytest from pants.backend.build_files.fix.deprecations.renamed_targets_rules import ( - RenameRequest, + RenamedTargetTypes, RenameTargetsInFileRequest, fix_single, ) +from pants.util.frozendict import FrozenDict @pytest.mark.parametrize( @@ -29,8 +30,8 @@ def test_rename_deprecated_target_types_noops(lines: list[str]) -> None: content = "\n".join(lines).encode("utf-8") result = fix_single( - RenameRequest("BUILD", content=content), - RenameTargetsInFileRequest({"deprecated_name": "new_name"}), + RenameTargetsInFileRequest("BUILD", content=content), + RenamedTargetTypes(FrozenDict({"deprecated_name": "new_name"})), ) assert result.content == content @@ -46,7 +47,7 @@ def test_rename_deprecated_target_types_noops(lines: list[str]) -> None: ) def test_rename_deprecated_target_types_rewrite(lines: list[str], expected: list[str]) -> None: result = fix_single( - RenameRequest("BUILD", content="\n".join(lines).encode("utf-8")), - RenameTargetsInFileRequest({"deprecated_name": "new_name"}), + RenameTargetsInFileRequest("BUILD", content="\n".join(lines).encode("utf-8")), + RenamedTargetTypes(FrozenDict({"deprecated_name": "new_name"})), ) assert result.content == "\n".join(expected).encode("utf-8")
`pants update-build-files` does not fix ersc **Describe the bug** ``` $ pants update-build-files :: 10:47:16.19 [WARN] DEPRECATED: the target name experimental_run_shell_command is scheduled to be removed in version 2.18.0.dev0. Instead, use `run_shell_command`, which behaves the same. Run `pants update-build-files` to automatically fix your BUILD files. 10:47:16.20 [WARN] DEPRECATED: the target name experimental_run_shell_command is scheduled to be removed in version 2.18.0.dev0. Instead, use `run_shell_command`, which behaves the same. Run `pants update-build-files` to automatically fix your BUILD files. 10:47:27.13 [INFO] No required changes to BUILD files found.However, there may still be deprecations that `update-build-files` doesn't know how to fix. See https://www.pantsbuild.org/v2.16/docs/upgrade-tips for upgrade tips. ``` **Pants version** 2.16.0a0 **OS** Mac M1 **Additional info** The target is in a macro file.
If possible, this should also update them to have `workdir="/"`, to handle the bug fix #18335 / #18840 that changed the default value to behave like the documentation suggested. This applies to `experimental_shell_command` too.
2023-05-03T21:46:57
pantsbuild/pants
18,894
pantsbuild__pants-18894
[ "18890" ]
2417cfeaf5de9b8c4bcf2a847bffc03551c2f773
diff --git a/src/python/pants/backend/adhoc/target_types.py b/src/python/pants/backend/adhoc/target_types.py --- a/src/python/pants/backend/adhoc/target_types.py +++ b/src/python/pants/backend/adhoc/target_types.py @@ -257,8 +257,8 @@ class AdhocToolTarget(Target): {AdhocToolRunnableField.alias}=":python_source", {AdhocToolArgumentsField.alias}=[""], {AdhocToolExecutionDependenciesField.alias}=[":scripts"], - {AdhocToolOutputDirectoriesField.alias}=["logs/my-script.log"], - {AdhocToolOutputFilesField.alias}=["results/"], + {AdhocToolOutputDirectoriesField.alias}=["results/"], + {AdhocToolOutputFilesField.alias}=["logs/my-script.log"], ) shell_sources(name="scripts")
docs: `adhoc_tool` example field values swapped When looking at the rendered docs it was much easier to spot that the example field values here are swapped (files vs directories). 👀 _Originally posted by @kaos in https://github.com/pantsbuild/pants/pull/18237#discussion_r1184219518_
<img width="537" alt="image" src="https://user-images.githubusercontent.com/72965/236041176-8bd9779c-2244-4608-9161-d178b43e9af6.png">
2023-05-03T22:05:22
pantsbuild/pants
18,910
pantsbuild__pants-18910
[ "18890" ]
f3197388373b1ffb0a28f4a19e820c1299b11914
diff --git a/src/python/pants/backend/adhoc/target_types.py b/src/python/pants/backend/adhoc/target_types.py --- a/src/python/pants/backend/adhoc/target_types.py +++ b/src/python/pants/backend/adhoc/target_types.py @@ -264,8 +264,8 @@ class AdhocToolTarget(Target): {AdhocToolRunnableField.alias}=":python_source", {AdhocToolArgumentsField.alias}=[""], {AdhocToolExecutionDependenciesField.alias}=[":scripts"], - {AdhocToolOutputDirectoriesField.alias}=["logs/my-script.log"], - {AdhocToolOutputFilesField.alias}=["results/"], + {AdhocToolOutputDirectoriesField.alias}=["results/"], + {AdhocToolOutputFilesField.alias}=["logs/my-script.log"], ) shell_sources(name="scripts")
docs: `adhoc_tool` example field values swapped When looking at the rendered docs it was much easier to spot that the example field values here are swapped (files vs directories). 👀 _Originally posted by @kaos in https://github.com/pantsbuild/pants/pull/18237#discussion_r1184219518_
<img width="537" alt="image" src="https://user-images.githubusercontent.com/72965/236041176-8bd9779c-2244-4608-9161-d178b43e9af6.png">
2023-05-04T21:28:36
pantsbuild/pants
18,940
pantsbuild__pants-18940
[ "18933" ]
7e6728e5412962674d3c2f96dff23990916f3c0c
diff --git a/src/python/pants/core/target_types.py b/src/python/pants/core/target_types.py --- a/src/python/pants/core/target_types.py +++ b/src/python/pants/core/target_types.py @@ -903,8 +903,17 @@ class LockfileTarget(Target): class LockfilesGeneratorSourcesField(MultipleSourcesField): + """Sources field for synthesized `_lockfiles` targets. + + It is special in that it always ignores any missing files, regardless of the global + `--unmatched-build-file-globs` option. + """ + help = generate_multiple_sources_field_help_message("Example: `sources=['example.lock']`") + def path_globs(self, unmatched_build_file_globs: UnmatchedBuildFileGlobs) -> PathGlobs: # type: ignore[misc] + return super().path_globs(UnmatchedBuildFileGlobs.ignore()) + class LockfilesGeneratorTarget(TargetFilesGenerator): alias = "_lockfiles"
diff --git a/src/python/pants/core/target_types_test.py b/src/python/pants/core/target_types_test.py --- a/src/python/pants/core/target_types_test.py +++ b/src/python/pants/core/target_types_test.py @@ -23,6 +23,7 @@ FilesGeneratorTarget, FileSourceField, FileTarget, + LockfilesGeneratorSourcesField, LockfileSourceField, RelocatedFiles, RelocateFilesViaCodegenRequest, @@ -448,3 +449,20 @@ def test_lockfile_glob_match_error_behavior( UnmatchedBuildFileGlobs(error_behavior) ).glob_match_error_behavior ) + + [email protected]( + "error_behavior", [GlobMatchErrorBehavior.warn, GlobMatchErrorBehavior.error] +) +def test_lockfiles_glob_match_error_behavior( + error_behavior: GlobMatchErrorBehavior, +) -> None: + lockfile_sources = LockfilesGeneratorSourcesField( + ["test.lock"], Address("", target_name="lockfiles-test") + ) + assert ( + GlobMatchErrorBehavior.ignore + == lockfile_sources.path_globs( + UnmatchedBuildFileGlobs(error_behavior) + ).glob_match_error_behavior + )
Requesting `AllTargets` in a plugin fails if an entry in `[python.resolves]` points to a nonexistent file **Describe the bug** In one of our in-repo plugins, we request: ``` await Get(AllTargets, AllTargetsRequest()) ``` This typically works fine, but if I add a new `[python.resolves]` entry: ``` [python.resolves] new = "path/to/new.lockfile" ``` Then the goal logic explodes with: ``` Traceback (most recent call last): File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/color/build/pants/plugins/lockfile/pex/register.py", line 304, in lock_goal all_targets = await Get(AllTargets, AllTargetsRequest()) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 455, in find_all_targets tgts = await Get( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/specs_rules.py", line 175, in addresses_from_raw_specs_without_file_owners target_parametrizations_list = await MultiGet( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 358, in MultiGet return await _MultiGet(tuple(__arg0)) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 165, in __await__ result = yield self.gets File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 283, in resolve_target_parametrizations all_generated = await MultiGet( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 358, in MultiGet return await _MultiGet(tuple(__arg0)) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 165, in __await__ result = yield self.gets File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 1418, in generate_file_targets sources_paths = await Get( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 1031, in resolve_source_paths paths = await Get(Paths, PathGlobs, path_globs) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self native_engine.IntrinsicError: Unmatched glob from path/to:_new_lockfile's `sources` field: "path/to/new.lockfile" ``` **Pants version** `PANTS_SHA=06aaef7f21092a7bd76ba157cd221266b8444653` (on the 2.16.x branch) **OS** MacOS but would presumably see it on Linux too if I pushed my branch to CI. **Additional info** I believe the error is happening because the rule that provides `AllTargets` [here](https://github.com/pantsbuild/pants/blob/main/src/python/pants/engine/internals/graph.py#L588-L593) wraps around: ``` await Get( Targets, RawSpecsWithoutFileOwners( recursive_globs=(RecursiveGlobSpec(""),), description_of_origin="the `AllTargets` rule" ), ) ``` `RawSpecsWithoutFileOwners` has an `unmatched_glob_behavior` field [here](https://github.com/pantsbuild/pants/blob/main/src/python/pants/base/specs.py#L365) that defaults to `GlobMatchErrorBehavior.error`.
Hrmmm although - it looks like that `unmatched_glob_behavior` field is only used in the `RawSpecsWithoutFileOwners.to_build_file_path_globs_tuple` method. If I replace my `AllTargets` request with this: ``` all_targets = await Get( Targets, RawSpecsWithoutFileOwners( recursive_globs=(RecursiveGlobSpec(""),), description_of_origin="the `lock` goal", unmatched_glob_behavior=GlobMatchErrorBehavior.ignore, ), ) ``` I still get the `Unmatched glob` intrinsic error 🤔 This also seems to bite `pants check` when `mypy` is enabled, because its logic includes an `await Get(AllTargets, AllTargetsRequest())`
2023-05-08T19:53:16
pantsbuild/pants
18,946
pantsbuild__pants-18946
[ "18906" ]
fa7ea810069f376c538bddc63a821e3bd2fac87b
diff --git a/src/python/pants/backend/docker/subsystems/docker_options.py b/src/python/pants/backend/docker/subsystems/docker_options.py --- a/src/python/pants/backend/docker/subsystems/docker_options.py +++ b/src/python/pants/backend/docker/subsystems/docker_options.py @@ -66,6 +66,7 @@ def env_vars(self) -> tuple[str, ...]: "extra_image_tags": [], "skip_push": bool, "repository": str, + "use_local_alias": bool, }, ... } @@ -91,6 +92,10 @@ def env_vars(self) -> tuple[str, ...]: `docker_image.repository` or the default repository. Using the placeholders `{target_repository}` or `{default_repository}` those overridden values may be incorporated into the registry specific repository value. + + If `use_local_alias` is true, a built image is additionally tagged locally using the + registry alias as the value for repository (i.e. the additional image tag is not pushed) + and will be used for any `pants run` requests. """ ), fromfile=True,
`[docker].registries` help omits `use_local_alias` feature (in 2.16+) :cry:
doh
2023-05-09T02:16:12
pantsbuild/pants
18,947
pantsbuild__pants-18947
[ "18933" ]
b503cde7f2201908c2d3cfee3c7d2b1128e71650
diff --git a/src/python/pants/core/target_types.py b/src/python/pants/core/target_types.py --- a/src/python/pants/core/target_types.py +++ b/src/python/pants/core/target_types.py @@ -762,8 +762,17 @@ class LockfileTarget(Target): class LockfilesGeneratorSourcesField(MultipleSourcesField): + """Sources field for synthesized `_lockfiles` targets. + + It is special in that it always ignores any missing files, regardless of the global + `--unmatched-build-file-globs` option. + """ + help = generate_multiple_sources_field_help_message("Example: `sources=['example.lock']`") + def path_globs(self, unmatched_build_file_globs: UnmatchedBuildFileGlobs) -> PathGlobs: # type: ignore[misc] + return super().path_globs(UnmatchedBuildFileGlobs.ignore()) + class LockfilesGeneratorTarget(TargetFilesGenerator): alias = "_lockfiles"
diff --git a/src/python/pants/core/target_types_test.py b/src/python/pants/core/target_types_test.py --- a/src/python/pants/core/target_types_test.py +++ b/src/python/pants/core/target_types_test.py @@ -24,6 +24,7 @@ FileSourceField, FileTarget, HTTPSource, + LockfilesGeneratorSourcesField, LockfileSourceField, RelocatedFiles, RelocateFilesViaCodegenRequest, @@ -444,3 +445,20 @@ def test_lockfile_glob_match_error_behavior( UnmatchedBuildFileGlobs(error_behavior) ).glob_match_error_behavior ) + + [email protected]( + "error_behavior", [GlobMatchErrorBehavior.warn, GlobMatchErrorBehavior.error] +) +def test_lockfiles_glob_match_error_behavior( + error_behavior: GlobMatchErrorBehavior, +) -> None: + lockfile_sources = LockfilesGeneratorSourcesField( + ["test.lock"], Address("", target_name="lockfiles-test") + ) + assert ( + GlobMatchErrorBehavior.ignore + == lockfile_sources.path_globs( + UnmatchedBuildFileGlobs(error_behavior) + ).glob_match_error_behavior + )
Requesting `AllTargets` in a plugin fails if an entry in `[python.resolves]` points to a nonexistent file **Describe the bug** In one of our in-repo plugins, we request: ``` await Get(AllTargets, AllTargetsRequest()) ``` This typically works fine, but if I add a new `[python.resolves]` entry: ``` [python.resolves] new = "path/to/new.lockfile" ``` Then the goal logic explodes with: ``` Traceback (most recent call last): File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/color/build/pants/plugins/lockfile/pex/register.py", line 304, in lock_goal all_targets = await Get(AllTargets, AllTargetsRequest()) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 455, in find_all_targets tgts = await Get( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/specs_rules.py", line 175, in addresses_from_raw_specs_without_file_owners target_parametrizations_list = await MultiGet( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 358, in MultiGet return await _MultiGet(tuple(__arg0)) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 165, in __await__ result = yield self.gets File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 283, in resolve_target_parametrizations all_generated = await MultiGet( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 358, in MultiGet return await _MultiGet(tuple(__arg0)) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 165, in __await__ result = yield self.gets File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 1418, in generate_file_targets sources_paths = await Get( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 1031, in resolve_source_paths paths = await Get(Paths, PathGlobs, path_globs) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self native_engine.IntrinsicError: Unmatched glob from path/to:_new_lockfile's `sources` field: "path/to/new.lockfile" ``` **Pants version** `PANTS_SHA=06aaef7f21092a7bd76ba157cd221266b8444653` (on the 2.16.x branch) **OS** MacOS but would presumably see it on Linux too if I pushed my branch to CI. **Additional info** I believe the error is happening because the rule that provides `AllTargets` [here](https://github.com/pantsbuild/pants/blob/main/src/python/pants/engine/internals/graph.py#L588-L593) wraps around: ``` await Get( Targets, RawSpecsWithoutFileOwners( recursive_globs=(RecursiveGlobSpec(""),), description_of_origin="the `AllTargets` rule" ), ) ``` `RawSpecsWithoutFileOwners` has an `unmatched_glob_behavior` field [here](https://github.com/pantsbuild/pants/blob/main/src/python/pants/base/specs.py#L365) that defaults to `GlobMatchErrorBehavior.error`.
Hrmmm although - it looks like that `unmatched_glob_behavior` field is only used in the `RawSpecsWithoutFileOwners.to_build_file_path_globs_tuple` method. If I replace my `AllTargets` request with this: ``` all_targets = await Get( Targets, RawSpecsWithoutFileOwners( recursive_globs=(RecursiveGlobSpec(""),), description_of_origin="the `lock` goal", unmatched_glob_behavior=GlobMatchErrorBehavior.ignore, ), ) ``` I still get the `Unmatched glob` intrinsic error 🤔 This also seems to bite `pants check` when `mypy` is enabled, because its logic includes an `await Get(AllTargets, AllTargetsRequest())`
2023-05-09T02:27:46
pantsbuild/pants
18,948
pantsbuild__pants-18948
[ "18933" ]
8f772835f59322bcb196049cfd67bf036b63a3e5
diff --git a/src/python/pants/core/target_types.py b/src/python/pants/core/target_types.py --- a/src/python/pants/core/target_types.py +++ b/src/python/pants/core/target_types.py @@ -893,8 +893,17 @@ class LockfileTarget(Target): class LockfilesGeneratorSourcesField(MultipleSourcesField): + """Sources field for synthesized `_lockfiles` targets. + + It is special in that it always ignores any missing files, regardless of the global + `--unmatched-build-file-globs` option. + """ + help = generate_multiple_sources_field_help_message("Example: `sources=['example.lock']`") + def path_globs(self, unmatched_build_file_globs: UnmatchedBuildFileGlobs) -> PathGlobs: # type: ignore[misc] + return super().path_globs(UnmatchedBuildFileGlobs.ignore()) + class LockfilesGeneratorTarget(TargetFilesGenerator): alias = "_lockfiles"
diff --git a/src/python/pants/core/target_types_test.py b/src/python/pants/core/target_types_test.py --- a/src/python/pants/core/target_types_test.py +++ b/src/python/pants/core/target_types_test.py @@ -23,6 +23,7 @@ FilesGeneratorTarget, FileSourceField, FileTarget, + LockfilesGeneratorSourcesField, LockfileSourceField, RelocatedFiles, RelocateFilesViaCodegenRequest, @@ -448,3 +449,20 @@ def test_lockfile_glob_match_error_behavior( UnmatchedBuildFileGlobs(error_behavior) ).glob_match_error_behavior ) + + [email protected]( + "error_behavior", [GlobMatchErrorBehavior.warn, GlobMatchErrorBehavior.error] +) +def test_lockfiles_glob_match_error_behavior( + error_behavior: GlobMatchErrorBehavior, +) -> None: + lockfile_sources = LockfilesGeneratorSourcesField( + ["test.lock"], Address("", target_name="lockfiles-test") + ) + assert ( + GlobMatchErrorBehavior.ignore + == lockfile_sources.path_globs( + UnmatchedBuildFileGlobs(error_behavior) + ).glob_match_error_behavior + )
Requesting `AllTargets` in a plugin fails if an entry in `[python.resolves]` points to a nonexistent file **Describe the bug** In one of our in-repo plugins, we request: ``` await Get(AllTargets, AllTargetsRequest()) ``` This typically works fine, but if I add a new `[python.resolves]` entry: ``` [python.resolves] new = "path/to/new.lockfile" ``` Then the goal logic explodes with: ``` Traceback (most recent call last): File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/color/build/pants/plugins/lockfile/pex/register.py", line 304, in lock_goal all_targets = await Get(AllTargets, AllTargetsRequest()) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 455, in find_all_targets tgts = await Get( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/specs_rules.py", line 175, in addresses_from_raw_specs_without_file_owners target_parametrizations_list = await MultiGet( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 358, in MultiGet return await _MultiGet(tuple(__arg0)) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 165, in __await__ result = yield self.gets File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 283, in resolve_target_parametrizations all_generated = await MultiGet( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 358, in MultiGet return await _MultiGet(tuple(__arg0)) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 165, in __await__ result = yield self.gets File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 1418, in generate_file_targets sources_paths = await Get( File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/graph.py", line 1031, in resolve_source_paths paths = await Get(Paths, PathGlobs, path_globs) File "/Users/dan.moran/Library/Caches/nce/56153e74337dc4e840948775afc9384890c3683383a5da29460a7aa1ccb965f6/bindings/venvs/2.16.0rc0+git06aaef7f/lib/python3.9/site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self native_engine.IntrinsicError: Unmatched glob from path/to:_new_lockfile's `sources` field: "path/to/new.lockfile" ``` **Pants version** `PANTS_SHA=06aaef7f21092a7bd76ba157cd221266b8444653` (on the 2.16.x branch) **OS** MacOS but would presumably see it on Linux too if I pushed my branch to CI. **Additional info** I believe the error is happening because the rule that provides `AllTargets` [here](https://github.com/pantsbuild/pants/blob/main/src/python/pants/engine/internals/graph.py#L588-L593) wraps around: ``` await Get( Targets, RawSpecsWithoutFileOwners( recursive_globs=(RecursiveGlobSpec(""),), description_of_origin="the `AllTargets` rule" ), ) ``` `RawSpecsWithoutFileOwners` has an `unmatched_glob_behavior` field [here](https://github.com/pantsbuild/pants/blob/main/src/python/pants/base/specs.py#L365) that defaults to `GlobMatchErrorBehavior.error`.
Hrmmm although - it looks like that `unmatched_glob_behavior` field is only used in the `RawSpecsWithoutFileOwners.to_build_file_path_globs_tuple` method. If I replace my `AllTargets` request with this: ``` all_targets = await Get( Targets, RawSpecsWithoutFileOwners( recursive_globs=(RecursiveGlobSpec(""),), description_of_origin="the `lock` goal", unmatched_glob_behavior=GlobMatchErrorBehavior.ignore, ), ) ``` I still get the `Unmatched glob` intrinsic error 🤔 This also seems to bite `pants check` when `mypy` is enabled, because its logic includes an `await Get(AllTargets, AllTargetsRequest())`
2023-05-09T02:28:07
pantsbuild/pants
18,950
pantsbuild__pants-18950
[ "18906" ]
8f772835f59322bcb196049cfd67bf036b63a3e5
diff --git a/src/python/pants/backend/docker/subsystems/docker_options.py b/src/python/pants/backend/docker/subsystems/docker_options.py --- a/src/python/pants/backend/docker/subsystems/docker_options.py +++ b/src/python/pants/backend/docker/subsystems/docker_options.py @@ -88,6 +88,7 @@ def iter_path_entries(): "extra_image_tags": [], "skip_push": bool, "repository": str, + "use_local_alias": bool, }, ... } @@ -113,6 +114,10 @@ def iter_path_entries(): `docker_image.repository` or the default repository. Using the placeholders `{target_repository}` or `{default_repository}` those overridden values may be incorporated into the registry specific repository value. + + If `use_local_alias` is true, a built image is additionally tagged locally using the + registry alias as the value for repository (i.e. the additional image tag is not pushed) + and will be used for any `pants run` requests. """ ), fromfile=True,
`[docker].registries` help omits `use_local_alias` feature (in 2.16+) :cry:
doh
2023-05-09T10:59:56
pantsbuild/pants
18,957
pantsbuild__pants-18957
[ "11831" ]
df749c145fc76f1d8d4d7de943c98a3d9c7d92c8
diff --git a/build-support/bin/generate_github_workflows.py b/build-support/bin/generate_github_workflows.py --- a/build-support/bin/generate_github_workflows.py +++ b/build-support/bin/generate_github_workflows.py @@ -68,7 +68,7 @@ def hashFiles(path: str) -> str: NATIVE_FILES = [ - ".pants", + "src/python/pants/bin/native_client", "src/python/pants/engine/internals/native_engine.so", "src/python/pants/engine/internals/native_engine.so.metadata", ]
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -58,7 +58,7 @@ jobs: uses: actions/cache@v3 with: key: Linux-ARM64-engine-${{ steps.get-engine-hash.outputs.hash }}-v1 - path: '.pants + path: 'src/python/pants/bin/native_client src/python/pants/engine/internals/native_engine.so @@ -93,7 +93,7 @@ jobs: uses: actions/upload-artifact@v3 with: name: native_binaries.${{ matrix.python-version }}.Linux-ARM64 - path: '.pants + path: 'src/python/pants/bin/native_client src/python/pants/engine/internals/native_engine.so @@ -158,7 +158,7 @@ jobs: uses: actions/cache@v3 with: key: Linux-x86_64-engine-${{ steps.get-engine-hash.outputs.hash }}-v1 - path: '.pants + path: 'src/python/pants/bin/native_client src/python/pants/engine/internals/native_engine.so @@ -193,7 +193,7 @@ jobs: uses: actions/upload-artifact@v3 with: name: native_binaries.${{ matrix.python-version }}.Linux-x86_64 - path: '.pants + path: 'src/python/pants/bin/native_client src/python/pants/engine/internals/native_engine.so @@ -270,7 +270,7 @@ jobs: uses: actions/cache@v3 with: key: macOS11-x86_64-engine-${{ steps.get-engine-hash.outputs.hash }}-v1 - path: '.pants + path: 'src/python/pants/bin/native_client src/python/pants/engine/internals/native_engine.so @@ -305,7 +305,7 @@ jobs: uses: actions/upload-artifact@v3 with: name: native_binaries.${{ matrix.python-version }}.macOS11-x86_64 - path: '.pants + path: 'src/python/pants/bin/native_client src/python/pants/engine/internals/native_engine.so diff --git a/src/rust/engine/options/src/build_root_tests.rs b/src/rust/engine/options/src/build_root_tests.rs --- a/src/rust/engine/options/src/build_root_tests.rs +++ b/src/rust/engine/options/src/build_root_tests.rs @@ -32,7 +32,7 @@ fn test_find_cwd() { assert_sentinel("BUILDROOT"); assert_sentinel("BUILD_ROOT"); - assert_sentinel("pants"); + assert_sentinel("pants.toml"); } #[test] @@ -44,7 +44,7 @@ fn test_find_subdir() { assert!(BuildRoot::find_from(&buildroot_path).is_err()); assert!(BuildRoot::find_from(&subdir).is_err()); - let sentinel = &buildroot.path().join("pants"); + let sentinel = &buildroot.path().join("pants.toml"); fs::write(sentinel, []).unwrap(); assert_eq!( &buildroot_path,
Port pantsd client to rust. This saves us ~500ms on my machine: ``` $ hyperfine -w 2 './pants --no-anonymous-telemetry-enabled -V' 'nails-client 0.0.0.0:$(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V' Benchmark #1: ./pants --no-anonymous-telemetry-enabled -V Time (mean ± σ): 700.7 ms ± 11.5 ms [User: 483.5 ms, System: 45.2 ms] Range (min … max): 688.7 ms … 722.2 ms 10 runs Benchmark #2: nails-client 0.0.0.0:$(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V Time (mean ± σ): 178.1 ms ± 4.6 ms [User: 2.8 ms, System: 1.5 ms] Range (min … max): 173.4 ms … 193.3 ms 16 runs Summary 'nails-client 0.0.0.0:$(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V' ran 3.93 ± 0.12 times faster than './pants --no-anonymous-telemetry-enabled -V' ```
And the rust client is as snappy as we'll likely get since: ``` $ hyperfine -w 3 './pants --no-anonymous-telemetry-enabled -V' 'nails-client 127.0.0.1:$(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V' 'ng --nailgun-server 127.0.0.1 --nailgun-port $(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V' Benchmark #1: ./pants --no-anonymous-telemetry-enabled -V Time (mean ± σ): 703.9 ms ± 14.8 ms [User: 490.4 ms, System: 45.6 ms] Range (min … max): 688.6 ms … 739.4 ms 10 runs Benchmark #2: nails-client 127.0.0.1:$(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V Time (mean ± σ): 181.9 ms ± 9.9 ms [User: 2.6 ms, System: 1.9 ms] Range (min … max): 174.4 ms … 205.5 ms 16 runs Benchmark #3: ng --nailgun-server 127.0.0.1 --nailgun-port $(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V Time (mean ± σ): 220.1 ms ± 4.0 ms [User: 1.2 ms, System: 1.1 ms] Range (min … max): 215.8 ms … 227.0 ms 13 runs Summary 'nails-client 127.0.0.1:$(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V' ran 1.21 ± 0.07 times faster than 'ng --nailgun-server 127.0.0.1 --nailgun-port $(cat .pids/1fd8a12b4fc1/pantsd/socket) does-not-matter --no-anonymous-telemetry-enabled -V' 3.87 ± 0.22 times faster than './pants --no-anonymous-telemetry-enabled -V' ``` #11922 is epic! The client feels snappier, but do we have numbers to prove it? Is there more speed-related work to do? Or is the remaining work for this ticket related to bringing up pantsd? I just did some casual benchmarking of `./pants` and `./pants help` and I don't see a noticeable improvement. Is that on deck for future work? > The client feels snappier, but do we have numbers to prove it? Is there more speed-related work to do? It should be a lot snappier. Are you using `USE_NATIVE_PANTS=1`? The numbers are in this PR: https://github.com/pantsbuild/pants/pull/11922#issuecomment-819882757 The client connection now takes a few ms (see this with -ldebug), so we can't win much more there. The remaining ~200ms noop is all in pantsd. Certainly there is work we could do on that side > Or is the remaining work for this ticket related to bringing up pantsd? Yes, exactly. Oh, hah, I was not using USE_NATIVE_PANTS=1. That is... excellent. The combination of #18145 and https://github.com/pantsbuild/scie-pants/issues/94 give a natural home for the Pants native client in Pants distributions and execution flows. It would be good to finish off the client in anticipation of this. Towards that end I'll be updating this ticket with the remaining work outline needed to enable fully replacing the Pants python main entrypoint with the native Pants client. FWIW: I've had `USE_NATIVE_PANTS` set for ... almost two years now, and never noticed an issue with it. I'll edit this comment as I gather all the required missing elements and cleanups. The lists are not ordered intentionally, but they are labelled for discussion. The required missing functionality: + [ ] 1. Handle launching pantsd when pantsd is not up and pantsd is enabled. The cleanup tasks: + [ ] A. De-dup Pants client logic between Rust and Python in favor of Rust. #11960 + [ ] B. Use the engine logging crate to setup logging in the Rust pants client. #11963 Notes: + 1 could be parametrized such that some information about how to launch Pantsd comes from configuration / the environment. In the pants scie case, there will be a known Python binary the Pants native client knows nothing about but will need to know about to run Pantsd as well as venv information. + B. Requires implementation of dict option parsing in Rust at the least - further review is needed. I actually think the comment above covers things. 1 is the only thing needed to get a prototype of this working and it can probably be implemented robustly by injecting the command line for running the Python Pants client (or that command line's key components) via env var in the lift manifest. The client would then gain the logic currently in the Pants repo `./pants` script - try to connect to Pantsd and if there is a failure, fall back to the python client command line which already knows how to start pantsd and wait for it to be up. This is probably not an ideal end-state - it would likely be good to get the launching of pantsd and wait loop ported into the native client - but that work would be non-disruptive to the release + install process and users of it.
2023-05-09T20:36:34
pantsbuild/pants
19,004
pantsbuild__pants-19004
[ "18488" ]
b8f0ed02b49e20fc46155d822cd568b011e779eb
diff --git a/build-support/bin/terraform_tool_versions.py b/build-support/bin/terraform_tool_versions.py --- a/build-support/bin/terraform_tool_versions.py +++ b/build-support/bin/terraform_tool_versions.py @@ -251,7 +251,7 @@ def fetch_versions( if __name__ == "__main__": versions_url = "https://releases.hashicorp.com/terraform/" - number_of_supported_versions = 32 + number_of_supported_versions = 43 keydata = requests.get("https://keybase.io/hashicorp/pgp_keys.asc").content verifier = GPGVerifier(keydata) diff --git a/src/python/pants/backend/terraform/tool.py b/src/python/pants/backend/terraform/tool.py --- a/src/python/pants/backend/terraform/tool.py +++ b/src/python/pants/backend/terraform/tool.py @@ -26,7 +26,7 @@ class TerraformTool(TemplatedExternalTool): # TODO: Possibly there should not be a default version, since terraform state is sensitive to # the version that created it, so you have to be deliberate about the version you select. - default_version = "1.0.7" + default_version = "1.4.6" default_url_template = ( "https://releases.hashicorp.com/terraform/{version}/terraform_{version}_{platform}.zip" ) @@ -40,132 +40,176 @@ class TerraformTool(TemplatedExternalTool): @classproperty def default_known_versions(cls): return [ - "1.3.5|macos_x86_64|6bf684dbc19ecbf9225f5a2409def32e5ef7d37af3899726accd9420a88a6bcd|20848406", - "1.3.5|macos_arm64|33b25ad89dedbd98bba09cbde69dcf9e928029f322ae9494279cf2c8ce47db89|19287887", + "1.4.6|macos_x86_64|5d8332994b86411b049391d31ad1a0785dfb470db8b9c50617de28ddb5d1f25d|22051279", + "1.4.6|macos_arm64|30a2f87298ff9f299452119bd14afaa8d5b000c572f62fa64baf432e35d9dec1|20613318", + "1.4.6|linux_x86_64|e079db1a8945e39b1f8ba4e513946b3ab9f32bd5a2bdf19b9b186d22c5a3d53b|20779821", + "1.4.6|linux_arm64|b38f5db944ac4942f11ceea465a91e365b0636febd9998c110fbbe95d61c3b26|18834675", + "1.4.5|macos_x86_64|808e54d826737e9a0ca79bbe29330e50d3622bbeeb26066c63b371a291731711|22031074", + "1.4.5|macos_arm64|7104d9d13632aa61b494a349c589048d21bd550e579404c3a41c4932e4d6aa97|20592841", + "1.4.5|linux_x86_64|ce10e941cd11554b15a189cd00191c05abc20dff865599d361bdb863c5f406a9|20767621", + "1.4.5|linux_arm64|ca2c48f518f72fef668255150cc5e63b92545edc62a05939bbff8a350bceb357|18813058", + "1.4.4|macos_x86_64|0303ed9d7e5a225fc2e6fa9bf76fc6574c0c0359f22d5dfc04bc8b3234444f7c|22032187", + "1.4.4|macos_arm64|75602d9ec491982ceabea813569579b2991093a4e0d76b7ca86ffd9b7a2a1d1e|20594012", + "1.4.4|linux_x86_64|67541c1f6631befcc25b764028e5605e59234d4424e60a256518ee1e8dd50593|20767354", + "1.4.4|linux_arm64|f0b4e092f2aa6de3324e5e4b5b51260ecf5e8c2f5335ff7a2ffdc4fb54a8922d|18814310", + "1.4.3|macos_x86_64|89bdb242bfacf24167f365ef7a3bf0ad0e443ddd27ebde425fb71d77ce1a2597|22032267", + "1.4.3|macos_arm64|20b9d484bf99ada6c0de89316176ba33f7c87f64c0738991188465147bba221b|20574247", + "1.4.3|linux_x86_64|2252ee6ac8437b93db2b2ba341edc87951e2916afaeb50a88b858e80796e9111|20781685", + "1.4.3|linux_arm64|d3d9464953d390970e7f4f7cbcd94dbf63136da6fe1cbb4955d944a9315bdcdb|18814307", + "1.4.2|macos_x86_64|c218a6c0ef6692b25af16995c8c7bdf6739e9638fef9235c6aced3cd84afaf66|22030042", + "1.4.2|macos_arm64|af8ff7576c8fc41496fdf97e9199b00d8d81729a6a0e821eaf4dfd08aa763540|20588400", + "1.4.2|linux_x86_64|9f3ca33d04f5335472829d1df7785115b60176d610ae6f1583343b0a2221a931|20234129", + "1.4.2|linux_arm64|39c182670c4e63e918e0a16080b1cc47bb16e158d7da96333d682d6a9cb8eb91|18206088", + "1.4.1|macos_x86_64|96466364a7e66e3d456ecb6c85a63c83e124c004f8835fb8ea9b7bbb7542a9d0|22077050", + "1.4.1|macos_arm64|61f76e130b97c8a9017d8aaff15d252af29117e35ea1a0fc30bcaab7ceafce73|20634145", + "1.4.1|linux_x86_64|9e9f3e6752168dea8ecb3643ea9c18c65d5a52acc06c22453ebc4e3fc2d34421|20276168", + "1.4.1|linux_arm64|53322cc70b6e50ac1985bf26a78ffa2814789a4704880f071eaf3e67a463d6f6|18248378", + "1.4.0|macos_x86_64|e897a4217f1c3bfe37c694570dcc6371336fbda698790bb6b0547ec8daf1ffb3|21935694", + "1.4.0|macos_arm64|d4a1e564714c6acf848e86dc020ff182477b49f932e3f550a5d9c8f5da7636fb|20508091", + "1.4.0|linux_x86_64|5da60da508d6d1941ffa8b9216147456a16bbff6db7622ae9ad01d314cbdd188|20144407", + "1.4.0|linux_arm64|33e0f4f0b75f507fc19012111de008308df343153cd6a3992507f4566c0bb723|18130960", + "1.3.9|macos_x86_64|a73326ea8fb06f6976597e005f8047cbd55ac76ed1e517303d8f6395db6c7805|21194871", + "1.3.9|macos_arm64|d8a59a794a7f99b484a07a0ed2aa6520921d146ac5a7f4b1b806dcf5c4af0525|19793371", + "1.3.9|linux_x86_64|53048fa573effdd8f2a59b726234c6f450491fe0ded6931e9f4c6e3df6eece56|19477757", + "1.3.9|linux_arm64|da571087268c5faf884912c4239c6b9c8e1ed8e8401ab1dcb45712df70f42f1b|17513770", + "1.3.8|macos_x86_64|1a27a6fac31ecb05de610daf61a29fe83d304d7c519d773afbf56c11c3b6276b|21189878", + "1.3.8|macos_arm64|873b05ac81645cd7289d6ccfd3e73d4735af1a453f2cd19da0650bdabf7d2eb6|19780134", + "1.3.8|linux_x86_64|9d9e7d6a9b41cef8b837af688441d4fbbd84b503d24061d078ad662441c70240|19479266", + "1.3.8|linux_arm64|a42bf3c7d6327f45d2b212b692ab4229285fb44dbb8adb7c39e18be2b26167c8|17507360", + "1.3.7|macos_x86_64|eeae48adcd55212b34148ed203dd5843e9b2a84a852a9877f3386fadb0514980|21185288", + "1.3.7|macos_arm64|01d553db5f7b4cf0729b725e4402643efde5884b1dabf5eb80af328ce5e447cf|19774151", + "1.3.7|linux_x86_64|b8cf184dee15dfa89713fe56085313ab23db22e17284a9a27c0999c67ce3021e|19464102", + "1.3.7|linux_arm64|5b491c555ea8a62dda551675fd9f27d369f5cdbe87608d2a7367d3da2d38ea38|17499971", + "1.3.6|macos_x86_64|13881fe0100238577394243a90c0631783aad21b77a9a7ee830404f86c0d37bb|21183111", + "1.3.6|macos_arm64|dbff0aeeaeee877c254f5414bef5c9d186e159aa0019223aac678abad9442c53|19779986", + "1.3.6|linux_x86_64|bb44a4c2b0a832d49253b9034d8ccbd34f9feeb26eda71c665f6e7fa0861f49b|19466755", + "1.3.6|linux_arm64|f4b1af29094290f1b3935c29033c4e5291664ee2c015ca251a020dd425c847c3|17501845", + "1.3.5|macos_x86_64|e6c9836188265b20c2588e9c9d6b1727094b324a379337e68ba58a6d26be8b51|21182319", + "1.3.5|macos_arm64|fcec1cbff229fbe59b03257ba2451d5ad1f5129714f08ccf6372b2737647c063|19780547", "1.3.5|linux_x86_64|ac28037216c3bc41de2c22724e863d883320a770056969b8d211ca8af3d477cf|19469337", "1.3.5|linux_arm64|ba5b1761046b899197bbfce3ad9b448d14550106d2cc37c52a60fc6822b584ed|17502759", - "1.3.4|macos_x86_64|03e0d7f629f28e2ea31ec2c69408b500f00eac674c613f7f1097536dcfa2cf6c|20847508", - "1.3.4|macos_arm64|7b4401edd8de50cda97d76b051c3a4b1882fa5aa8e867d4c4c2770e4c3b0056e|19284666", + "1.3.4|macos_x86_64|2a75c69ec5ed8506658b266a40075256b62a7d245ff6297df7e48fa72af23879|21181585", + "1.3.4|macos_arm64|a1f740f92afac6db84421a3ec07d9061c34a32f88b4b0b47d243de16c961169f|19773343", "1.3.4|linux_x86_64|b24210f28191fa2a08efe69f54e3db2e87a63369ac4f5dcaf9f34dc9318eb1a8|19462529", "1.3.4|linux_arm64|65381c6b61b2d1a98892199f649a5764ff5a772080a73d70f8663245e6402c39|17494667", - "1.3.3|macos_x86_64|e544aefb984fd9b19de250ac063a7aa28cbfdce2eda428dd2429a521912f6a93|20843907", - "1.3.3|macos_arm64|1850df7904025b20b26ac101274f30673b132adc84686178d3d0cb802be4597e|19268812", + "1.3.3|macos_x86_64|2b3cf653cd106becdea562b6c8d3f8939641e5626c5278729cbef81678fa9f42|21163874", + "1.3.3|macos_arm64|51e94ecf88059e8a53c363a048b658230f560574f99b0d8396ebacead894d159|19755200", "1.3.3|linux_x86_64|fa5cbf4274c67f2937cabf1a6544529d35d0b8b729ce814b40d0611fd26193c1|19451941", "1.3.3|linux_arm64|b940a080c698564df5e6a2f1c4e1b51b2c70a5115358d2361e3697d3985ecbfe|17488660", - "1.3.2|macos_x86_64|edaed5a7c4057f1f2a3826922f3e594c45e24c1e22605b94de9c097b683c38bd|20843900", - "1.3.2|macos_arm64|ff92cd79b01d39a890314c2df91355c0b6d6815fbc069ccaee9da5d8b9ff8580|19270064", + "1.3.2|macos_x86_64|3639461bbc712dc130913bbe632afb449fce8c0df692429d311e7cb808601901|21163990", + "1.3.2|macos_arm64|80480acbfee2e2d0b094f721f7568a40b790603080d6612e19b797a16b8ba82d|19757201", "1.3.2|linux_x86_64|6372e02a7f04bef9dac4a7a12f4580a0ad96a37b5997e80738e070be330cb11c|19451510", "1.3.2|linux_arm64|ce1a8770aaf27736a3352c5c31e95fb10d0944729b9d81013bf6848f8657da5f|17485206", - "1.3.1|macos_x86_64|5f5967e12e75a3ca1720be3eeba8232b4ba8b42d2d9e9f9664eff7a68267e873|20842029", - "1.3.1|macos_arm64|a525488cc3a26d25c5769fb7ffcabbfcd64f79cec5ebbfc94c18b5ec74a03b35|19269260", + "1.3.1|macos_x86_64|4282ebe6d1d72ace0d93e8a4bcf9a6f3aceac107966216355bb516b1c49cc203|21161667", + "1.3.1|macos_arm64|f0514f29b08da2f39ba4fff0d7eb40093915c9c69ddc700b6f39b78275207d96|19756039", "1.3.1|linux_x86_64|0847b14917536600ba743a759401c45196bf89937b51dd863152137f32791899|19450765", "1.3.1|linux_arm64|7ebb3d1ff94017fbef8acd0193e0bd29dec1a8925e2b573c05a92fdb743d1d5b|17486534", - "1.3.0|macos_x86_64|6502dbcbd7d1a356fa446ec12c2859a9a7276af92c89ce3cef7f675a8582a152|20842934", - "1.3.0|macos_arm64|6a3512a1b1006f2edc6fe5f51add9a6e1ef3967912ecf27e66f22e70b9ad7158|19255975", + "1.3.0|macos_x86_64|80e55182d4495da867c93c25dc6ae29be83ece39d3225e6adedecd55b72d6bbf|21163947", + "1.3.0|macos_arm64|df703317b5c7f80dc7c61e46de4697c9f440e650a893623351ab5e184995b404|19741011", "1.3.0|linux_x86_64|380ca822883176af928c80e5771d1c0ac9d69b13c6d746e6202482aedde7d457|19450952", "1.3.0|linux_arm64|0a15de6f934cf2217e5055412e7600d342b4f7dcc133564690776fece6213a9a|17488551", - "1.2.9|macos_x86_64|46206e564fdd792e709b7ec70eab1c873c9b1b17f4d33c07a1faa9d68955061b|21329275", - "1.2.9|macos_arm64|e61195aa7cc5caf6c86c35b8099b4a29339cd51e54518eb020bddb35cfc0737d|19773052", + "1.2.9|macos_x86_64|84a678ece9929cebc34c7a9a1ba287c8b91820b336f4af8437af7feaa0117b7c|21672810", + "1.2.9|macos_arm64|bc3b94b53cdf1be3c4988faa61aad343f48e013928c64bfc6ebeb61657f97baa|20280541", "1.2.9|linux_x86_64|0e0fc38641addac17103122e1953a9afad764a90e74daf4ff8ceeba4e362f2fb|19906116", "1.2.9|linux_arm64|6da7bf01f5a72e61255c2d80eddeba51998e2bb1f50a6d81b0d3b71e70e18531|17946045", - "1.2.8|macos_x86_64|0f8eecc764b57a938aa115a3ce2baa0d245479f17c28a4217bcf432ee23c2c5d|21332730", - "1.2.8|macos_arm64|d6b900682d33aff84f8f63f69557f8ea8537218748fcac6f12483aaa46959a14|19770539", + "1.2.8|macos_x86_64|efd3e21a9bb1cfa68303f8d119ea8970dbb616f5f99caa0fe21d796e0cd70252|21678594", + "1.2.8|macos_arm64|2c83bfea9e1c202c449e91bee06a804afb45cb8ba64a73da48fb0f61df51b327|20277152", "1.2.8|linux_x86_64|3e9c46d6f37338e90d5018c156d89961b0ffb0f355249679593aff99f9abe2a2|19907515", "1.2.8|linux_arm64|26c05cadb05cdaa8ac64b90b982b4e9350715ec2e9995a6b03bb964d230de055|17947439", - "1.2.7|macos_x86_64|acc781e964be9b527101b00eb6e7e63e7e509dd1355ff8567b80d0244c460634|21330075", - "1.2.7|macos_arm64|e4717057e1cbb606f1e089261def9a17ddd18b78707d9e212c768dc0d739a220|19773241", + "1.2.7|macos_x86_64|74e47b54ea78685be24c84e0e17b22b56220afcdb24ec853514b3863199f01e4|21673162", + "1.2.7|macos_arm64|ec4e623914b411f8cc93a1e71396a1e7f1fe1e96bb2e532ba3e955d2ca5cc442|20278743", "1.2.7|linux_x86_64|dfd7c44a5b6832d62860a01095a15b53616fb3ea4441ab89542f9364e3fca718|19907183", "1.2.7|linux_arm64|80d064008d57ba5dc97e189215c87275bf39ca14b1234430eae2f114394ea229|17943724", - "1.2.6|macos_x86_64|94d1efad05a06c879b9c1afc8a6f7acb2532d33864225605fc766ecdd58d9888|21328767", - "1.2.6|macos_arm64|452675f91cfe955a95708697a739d9b114c39ff566da7d9b31489064ceaaf66a|19774190", + "1.2.6|macos_x86_64|d896d2776af8b06cd4acd695ad75913040ce31234f5948688fd3c3fde53b1f75|21670957", + "1.2.6|macos_arm64|c88ceb34f343a2bb86960e32925c5ec43b41922ee9ede1019c5cf7d7b4097718|20279669", "1.2.6|linux_x86_64|9fd445e7a191317dcfc99d012ab632f2cc01f12af14a44dfbaba82e0f9680365|19905977", "1.2.6|linux_arm64|322755d11f0da11169cdb234af74ada5599046c698dccc125859505f85da2a20|17943213", - "1.2.5|macos_x86_64|d196f94486e54407524a0efbcb5756b197b763863ead2e145f86dd6c80fc9ce8|21323818", - "1.2.5|macos_arm64|77dd998d26e578aa22de557dc142672307807c88e3a4da65d8442de61479899f|19767100", + "1.2.5|macos_x86_64|2520fde736b43332b0c2648f4f6dde407335f322a3085114dc4f70e6e50eadc0|21659883", + "1.2.5|macos_arm64|92ad40db4a0930bdf872d6336a7b3a18b17c6fd04d9fc769b554bf51c8add505|20266441", "1.2.5|linux_x86_64|281344ed7e2b49b3d6af300b1fe310beed8778c56f3563c4d60e5541c0978f1b|19897064", "1.2.5|linux_arm64|0544420eb29b792444014988018ae77a7c8df6b23d84983728695ba73e38f54a|17938208", - "1.2.4|macos_x86_64|3e04343620fb01b8be01c8689dcb018b8823d8d7b070346086d7df22cc4cd5e6|21321939", - "1.2.4|macos_arm64|e596dcdfe55b2070a55fcb271873e86d1af7f6b624ffad4837ccef119fdac97a|19765021", + "1.2.4|macos_x86_64|e7d2c66264a3da94854ae6ff692bbb9a1bc11c36bb5658e3ef19841388a07430|21658356", + "1.2.4|macos_arm64|c31754ff5553707ef9fd2f913b833c779ab05ce192eb14913f51816a077c6798|20263133", "1.2.4|linux_x86_64|705ea62a44a0081594dad6b2b093eefefb12d54fa5a20a66562f9e082b00414c|19895510", "1.2.4|linux_arm64|11cfa2233dc708b51b16d5b923379db67e35c22b1b988773e5b31a7c2e251471|17936883", - "1.2.3|macos_x86_64|2962b0ebdf6f431b8fb182ffc1d8b582b73945db0c3ab99230ffc360d9e297a2|21318448", - "1.2.3|macos_arm64|601962205ad3dcf9b1b75f758589890a07854506cbd08ca2fc25afbf373bff53|19757696", + "1.2.3|macos_x86_64|bdc22658463237530dc120dadb0221762d9fb9116e7a6e0dc063d8ae649c431e|21658937", + "1.2.3|macos_arm64|6f06debac2ac54951464bf490e1606f973ab53ad8ba5decea76646e8f9309512|20256836", "1.2.3|linux_x86_64|728b6fbcb288ad1b7b6590585410a98d3b7e05efe4601ef776c37e15e9a83a96|19891436", "1.2.3|linux_arm64|a48991e938a25bfe5d257f4b6cbbdc73d920cc34bbc8f0e685e28b9610ad75fe|17933271", - "1.2.2|macos_x86_64|bd224d57718ed2b6e5e3b55383878d4b122c6dc058d65625605cef1ace9dcb25|21317982", - "1.2.2|macos_arm64|4750d46e47345809a0baa3c330771c8c8a227b77bec4caa7451422a21acefae5|19758608", + "1.2.2|macos_x86_64|1d22663c1ab22ecea774ae63aee21eecfee0bbc23b953206d889a5ba3c08525a|21656824", + "1.2.2|macos_arm64|b87716b55a3b10cced60db5285bae57aee9cc0f81c555dccdc4f54f62c2a3b60|20254768", "1.2.2|linux_x86_64|2934a0e8824925beb956b2edb5fef212a6141c089d29d8568150a43f95b3a626|19889133", "1.2.2|linux_arm64|9c6202237d7477412054dcd36fdc269da9ee66ecbc45bb07d0d63b7d36af7b21|17932829", - "1.2.1|macos_x86_64|d7c9a677efb22276afdd6c7703cbfee87d509a31acb247b96aa550a35154400a|21309907", - "1.2.1|macos_arm64|96e3659e89bfb50f70d1bb8660452ec433019d00a862d2291817c831305d85ea|19751670", + "1.2.1|macos_x86_64|31c0fd4deb7c6a77c08d2fdf59c37950e6df7165088c004e1dd7f5e09fbf6307|21645582", + "1.2.1|macos_arm64|70159b3e3eb49ee71193815943d9217c59203fd4ee8c6960aeded744094a2250|20253448", "1.2.1|linux_x86_64|8cf8eb7ed2d95a4213fbfd0459ab303f890e79220196d1c4aae9ecf22547302e|19881618", "1.2.1|linux_arm64|972ea512dac822274791dedceb6e7f8b9ac2ed36bd7759269b6806d0ab049128|17922073", - "1.2.0|macos_x86_64|f608b1fee818988d89a16b7d1b6d22b37cc98892608c52c22661ca6cbfc3d216|21309982", - "1.2.0|macos_arm64|d4df7307bad8c13e443493c53898a7060f77d661bfdf06215b61b65621ed53e9|19750767", + "1.2.0|macos_x86_64|1b102ba3bf0c60ff6cbee74f721bf8105793c1107a1c6d03dcab98d7079f0c77|21645732", + "1.2.0|macos_arm64|f5e46cabe5889b60597f0e9c365cbc663e4c952c90a16c10489897c2075ae4f0|20253335", "1.2.0|linux_x86_64|b87de03adbdfdff3c2552c8c8377552d0eecd787154465100cf4e29de4a7be1f|19880608", "1.2.0|linux_arm64|ee80b8635d8fdbaed57beffe281cf87b8b1fd1ddb29c08d20e25a152d9f0f871|17920355", - "1.1.9|macos_x86_64|c902b3c12042ac1d950637c2dd72ff19139519658f69290b310f1a5924586286|20709155", - "1.1.9|macos_arm64|918a8684da5a5529285135f14b09766bd4eb0e8c6612a4db7c121174b4831739|19835808", + "1.1.9|macos_x86_64|685258b525eae94fb0b406faf661aa056d31666256bf28e625365a251cb89fdc|20850638", + "1.1.9|macos_arm64|39fac4be74462be86b2290dd09fe1092f73dfb48e2df92406af0e199cfa6a16c|20093184", "1.1.9|linux_x86_64|9d2d8a89f5cc8bc1c06cb6f34ce76ec4b99184b07eb776f8b39183b513d7798a|19262029", "1.1.9|linux_arm64|e8a09d1fe5a68ed75e5fabe26c609ad12a7e459002dea6543f1084993b87a266|17521011", - "1.1.8|macos_x86_64|29ad0af72d498a76bbc51cc5cb09a6d6d0e5673cbbab6ef7aca57e3c3e780f46|20216382", - "1.1.8|macos_arm64|d6fefdc27396a019da56cce26f7eeea3d6986714cbdd488ff6a424f4bca40de8|19371647", + "1.1.8|macos_x86_64|48f1f1e04d0aa8f5f1a661de95e3c2b8fd8ab16b3d44015372aff7693d36c2cf|20354970", + "1.1.8|macos_arm64|943e1948c4eae82cf8b490bb274939fe666252bbc146f098e7da65b23416264a|19631574", "1.1.8|linux_x86_64|fbd37c1ec3d163f493075aa0fa85147e7e3f88dd98760ee7af7499783454f4c5|18796132", "1.1.8|linux_arm64|10b2c063dcff91329ee44bce9d71872825566b713308b3da1e5768c6998fb84f|17107405", - "1.1.7|macos_x86_64|5e7e939e084ae29af7fd86b00a618433d905477c52add2d4ea8770692acbceac|20213394", - "1.1.7|macos_arm64|a36b6e2810f81a404c11005942b69c3d1d9baa8dd07de6b1f84e87a67eedb58f|19371095", + "1.1.7|macos_x86_64|6e56eea328683541f6de0d5f449251a974d173e6d8161530956a20d9c239731a|20351873", + "1.1.7|macos_arm64|8919ceee34f6bfb16a6e9ff61c95f4043c35c6d70b21de27e5a153c19c7eba9c|19625836", "1.1.7|linux_x86_64|e4add092a54ff6febd3325d1e0c109c9e590dc6c38f8bb7f9632e4e6bcca99d4|18795309", "1.1.7|linux_arm64|2f72982008c52d2d57294ea50794d7c6ae45d2948e08598bfec3e492bce8d96e|17109768", - "1.1.6|macos_x86_64|bbfc916117e45788661c066ec39a0727f64c7557bf6ce9f486bbd97c16841975|20168574", - "1.1.6|macos_arm64|dddb11195fc413653b98e7a830ec7314f297e6c22575fc878f4ee2287a25b4f5|19326402", + "1.1.6|macos_x86_64|7a499c1f08d89548ae4c0e829eea43845fa1bd7b464e7df46102b35e6081fe44|20303856", + "1.1.6|macos_arm64|f06a14fdb610ec5a7f18bdbb2f67187230eb418329756732d970b6ca3dae12c3|19577273", "1.1.6|linux_x86_64|3e330ce4c8c0434cdd79fe04ed6f6e28e72db44c47ae50d01c342c8a2b05d331|18751464", "1.1.6|linux_arm64|a53fb63625af3572f7252b9fb61d787ab153132a8984b12f4bb84b8ee408ec53|17069580", - "1.1.5|macos_x86_64|7d4dbd76329c25869e407706fed01213beb9d6235c26e01c795a141c2065d053|20157551", - "1.1.5|macos_arm64|723363af9524c0897e9a7d871d27f0d96f6aafd11990df7e6348f5b45d2dbe2c|19328643", + "1.1.5|macos_x86_64|dcf7133ebf61d195e432ddcb70e604bf45056163d960e991881efbecdbd7892b|20300006", + "1.1.5|macos_arm64|6e5a8d22343722dc8bfcf1d2fd7b742f5b46287f87171e8143fc9b87db32c3d4|19581167", "1.1.5|linux_x86_64|30942d5055c7151f051c8ea75481ff1dc95b2c4409dbb50196419c21168d6467|18748879", "1.1.5|linux_arm64|2fb6324c24c14523ae63cedcbc94a8e6c1c317987eced0abfca2f6218d217ca5|17069683", - "1.1.4|macos_x86_64|c2b2500835d2eb9d614f50f6f74c08781f0fee803699279b3eb0188b656427f2|20098620", - "1.1.4|macos_arm64|a753e6cf402beddc4043a3968ff3e790cf50cc526827cda83a0f442a893f2235|19248286", + "1.1.4|macos_x86_64|4f3bc78fedd4aa17f67acc0db4eafdb6d70ba72392aaba65fe72855520f11f3d|20242050", + "1.1.4|macos_arm64|5642b46e9c7fb692f05eba998cd4065fb2e48aa8b0aac9d2a116472fbabe34a1|19498408", "1.1.4|linux_x86_64|fca028d622f82788fdc35c1349e78d69ff07c7bb68c27d12f8b48c420e3ecdfb|18695508", "1.1.4|linux_arm64|3c1982cf0d16276c82960db60c998d79ba19e413af4fa2c7f6f86e4994379437|16996040", - "1.1.3|macos_x86_64|c54022e514a97e9b96dae24a3308227d034989ecbafb65e3293eea91f2d5edfb|20098660", - "1.1.3|macos_arm64|856e435da081d0a214c47a4eb09b1842f35eaa55e7ef0f9fa715d4816981d640|19244516", + "1.1.3|macos_x86_64|016bab760c96d4e64d2140a5f25c614ccc13c3fe9b3889e70c564bd02099259f|20241648", + "1.1.3|macos_arm64|02ba769bb0a8d4bc50ff60989b0f201ce54fd2afac2fb3544a0791aca5d3f6d5|19493636", "1.1.3|linux_x86_64|b215de2a18947fff41803716b1829a3c462c4f009b687c2cbdb52ceb51157c2f|18692580", "1.1.3|linux_arm64|ad5a1f2c132bedc5105e3f9900e4fe46858d582c0f2a2d74355da718bbcef65d|16996972", - "1.1.2|macos_x86_64|214da2e97f95389ba7557b8fcb11fe05a23d877e0fd67cd97fcbc160560078f1|20098558", - "1.1.2|macos_arm64|39e28f49a753c99b5e2cb30ac8146fb6b48da319c9db9d152b1e8a05ec9d4a13|19240921", + "1.1.2|macos_x86_64|78faa76db5dc0ecfe4bf7c6368dbf5cca019a806f9d203580a24a4e0f8cd8353|20240584", + "1.1.2|macos_arm64|cc3bd03b72db6247c9105edfeb9c8f674cf603e08259075143ffad66f5c25a07|19486800", "1.1.2|linux_x86_64|734efa82e2d0d3df8f239ce17f7370dabd38e535d21e64d35c73e45f35dfa95c|18687805", "1.1.2|linux_arm64|088e2226d1ddb7f68a4f65c704022a1cfdbf20fe40f02e0c3646942f211fd746|16994702", - "1.1.1|macos_x86_64|85fa7c90359c4e3358f78e58f35897b3e466d00c0d0648820830cac5a07609c3|20094218", - "1.1.1|macos_arm64|9cd8faf29095c57e30f04f9ca5fa9105f6717b277c65061a46f74f22f0f5907e|19240711", + "1.1.1|macos_x86_64|d125dd2e92b9245f2202199b52f234035f36bdcbcd9a06f08e647e14a9d9067a|20237718", + "1.1.1|macos_arm64|4cb6e5eb4f6036924caf934c509a1dfd61cd2c651bb3ee8fbfe2e2914dd9ed17|19488315", "1.1.1|linux_x86_64|07b8dc444540918597a60db9351af861335c3941f28ea8774e168db97dd74557|18687006", "1.1.1|linux_arm64|d6fd14da47af9ec5fa3ad5962eaef8eed6ff2f8a5041671f9c90ec5f4f8bb554|16995635", - "1.1.0|macos_x86_64|6fb2af160879d807291980642efa93cc9a97ddf662b17cc3753065c974a5296d|20089311", - "1.1.0|macos_arm64|f69e0613f09c21d44ce2131b20e8b97909f3fc7aa90c443639475f5e474a22ec|19240009", + "1.1.0|macos_x86_64|6e0ba9afb8795a544e70dc0459f0095fea7df15e38f5d88a7dd3f620d50f8bfe|20226329", + "1.1.0|macos_arm64|7955e173c7eadb87123fc0633c3ee67d5ba3b7d6c7f485fe803efed9f99dce54|19491369", "1.1.0|linux_x86_64|763378aa75500ce5ba67d0cba8aa605670cd28bf8bafc709333a30908441acb5|18683106", "1.1.0|linux_arm64|6697e9a263e264310373f3c91bf83f4cbfeb67b13994d2a8f7bcc492b554552e|16987201", - "1.0.11|macos_x86_64|92f2e7eebb9699e23800f8accd519775a02bd25fe79e1fe4530eca123f178202|19340098", - "1.0.11|macos_arm64|0f38af81641b00a2cbb8d25015d917887a7b62792c74c28d59e40e56ce6f265c|18498208", + "1.0.11|macos_x86_64|551a16b612edaae1037925d0e2dba30d16504ff4bd66606955172c2ed8d76131|19422757", + "1.0.11|macos_arm64|737e1765afbadb3d76e1929d4b4af8da55010839aa08e9e730d46791eb8ea5a6|18467868", "1.0.11|linux_x86_64|eeb46091a42dc303c3a3c300640c7774ab25cbee5083dafa5fd83b54c8aca664|18082446", "1.0.11|linux_arm64|30c650f4bc218659d43e07d911c00f08e420664a3d12c812228e66f666758645|16148492", - "1.0.10|macos_x86_64|e7595530a0dcdaec757621cbd9f931926fd904b1a1e5206bf2c9db6b73cee04d|33021017", - "1.0.10|macos_arm64|eecea1343888e2648d5f7ea25a29494fd3b5ecde95d0231024414458c59cb184|32073869", + "1.0.10|macos_x86_64|077479e98701bc9be88db21abeec684286fd85a3463ce437d7739d2a4e372f18|33140832", + "1.0.10|macos_arm64|776f2e144039ece66ae326ebda0884254848a2e11f0590757d02e3a74f058c81|32013985", "1.0.10|linux_x86_64|a221682fcc9cbd7fde22f305ead99b3ad49d8303f152e118edda086a2807716d|32674953", "1.0.10|linux_arm64|b091dbe5c00785ae8b5cb64149d697d61adea75e495d9e3d910f61d8c9967226|30505040", - "1.0.9|macos_x86_64|fb791c3efa323c5f0c2c36d14b9230deb1dc37f096a8159e718e8a9efa49a879|33017665", - "1.0.9|macos_arm64|aa5cc13903be35236a60d116f593e519534bcabbb2cf91b69cae19307a17b3c0|32069384", + "1.0.9|macos_x86_64|be122ff7fb925643c5ebf4e5704b18426e18d3ca49ab59ae33d208c908cb6d5a|33140006", + "1.0.9|macos_arm64|89b2b4fd1a0c57fabc08ad3180ad148b1f7c1c0492ed865408f75f12e11a083b|32010657", "1.0.9|linux_x86_64|f06ac64c6a14ed6a923d255788e4a5daefa2b50e35f32d7a3b5a2f9a5a91e255|32674820", "1.0.9|linux_arm64|457ac590301126e7b151ea08c5b9586a882c60039a0605fb1e44b8d23d2624fd|30510941", - "1.0.8|macos_x86_64|e2493c7ae12597d4a1e6437f6805b0a8bcaf01fc4e991d1f52f2773af3317342|33018420", - "1.0.8|macos_arm64|9f0e1366484748ecbd87c8ef69cc4d3d79296b0e2c1a108bcbbff985dbb92de8|32068918", + "1.0.8|macos_x86_64|909781ee76250cf7445f3b7d2b82c701688725fa1db3fb5543dfeed8c47b59de|33140123", + "1.0.8|macos_arm64|92fa31b93d736fab6f3d105beb502a9da908445ed942a3d46952eae88907c53e|32011344", "1.0.8|linux_x86_64|a73459d406067ce40a46f026dce610740d368c3b4a3d96591b10c7a577984c2e|32681118", "1.0.8|linux_arm64|01aaef769f4791f9b28530e750aadbc983a8eabd0d55909e26392b333a1a26e4|30515501", - "1.0.7|macos_x86_64|80ae021d6143c7f7cbf4571f65595d154561a2a25fd934b7a8ccc1ebf3014b9b|33020029", - "1.0.7|macos_arm64|cbab9aca5bc4e604565697355eed185bb699733811374761b92000cc188a7725|32071346", + "1.0.7|macos_x86_64|23b85d914465882b027d3819cc05cd114a1aaf39b550de742e81a99daa998183|33140742", + "1.0.7|macos_arm64|d9062959f28ba0f934bfe2b6e0b021e0c01a48fa065102554ca103b8274e8e0c|32012708", "1.0.7|linux_x86_64|bc79e47649e2529049a356f9e60e06b47462bf6743534a10a4c16594f443be7b|32671441", "1.0.7|linux_arm64|4e71a9e759578020750be41e945c086e387affb58568db6d259d80d123ac80d3|30529105", - "1.0.6|macos_x86_64|3a97f2fffb75ac47a320d1595e20947afc8324571a784f1bd50bd91e26d5648c|33022053", - "1.0.6|macos_arm64|aaff1eccaf4099da22fe3c6b662011f8295dad9c94a35e1557b92844610f91f3|32080428", + "1.0.6|macos_x86_64|5ac4f41d5e28f31817927f2c5766c5d9b98b68d7b342e25b22d053f9ecd5a9f1|33141677", + "1.0.6|macos_arm64|613020f90a6a5d0b98ebeb4e7cdc4b392aa06ce738fbb700159a465cd27dcbfa|32024047", "1.0.6|linux_x86_64|6a454323d252d34e928785a3b7c52bfaff1192f82685dfee4da1279bb700b733|32677516", "1.0.6|linux_arm64|2047f8afc7d0d7b645a0422181ba3fe47b3547c4fe658f95eebeb872752ec129|30514636", ]
Terraform 1.0.7 (the default) file download length is incorrect on macOS_x86_64 **Describe the bug** Title. Error message: ``` 10:08:19.28 [ERROR] 1 Exception encountered: Engine traceback: in `fmt` goal in Format with `terraform fmt` Exception: Error hashing/capturing URL fetch response: Downloaded file was larger than expected digest ``` **Pants version** 2.15 **OS** Intel MacOS **Additional info** Probably just need to rerun `build-support/bin/terraform_tool_versions.py`
So, this is wild. We generated them with originally with that script. You're right though, rerunning that script _all_ the MacOS ones have changed.
2023-05-14T16:26:04
pantsbuild/pants
19,019
pantsbuild__pants-19019
[ "19017" ]
d12d7e2026225159219b21aba159bd0b6c3f8d39
diff --git a/src/python/pants/backend/shell/target_types.py b/src/python/pants/backend/shell/target_types.py --- a/src/python/pants/backend/shell/target_types.py +++ b/src/python/pants/backend/shell/target_types.py @@ -266,7 +266,15 @@ class ShellSourcesGeneratorTarget(TargetFilesGenerator): class ShellCommandCommandField(StringField): alias = "command" required = True - help = "Shell command to execute.\n\nThe command is executed as 'bash -c <command>' by default." + help = help_text( + """ + Shell command to execute. + + The command is executed as 'bash -c <command>' by default. If you want to invoke a binary + use `exec -a $0 <binary> <args>` as the command so that the binary gets the correct `argv[0]` + set. + """ + ) class ShellCommandOutputFilesField(AdhocToolOutputFilesField):
`AdhocProcessRequest` isn't replacing `$0` correctly **Describe the bug** From https://pantsbuild.slack.com/archives/C0D7TNJHL/p1684255827991839 ``` file( name="downloaded-jq", source = http_source( len = 3953824, sha256 = "af986793a515d500ab2d35f8d2aecd656e764504b789b66d7e1a0b727a124c44", url = "https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64", ), ) shell_command( name = "sandboxed-jq", command="chmod +x jq-linux64", tools = ["chmod"], execution_dependencies=[":downloaded-jq"], output_directories = ["."], ) run_shell_command( name = "jq", command=f"{{chroot}}/{build_file_dir() / 'jq-linux64'}", execution_dependencies=[":sandboxed-jq"], workdir="/", ) ``` Run with: `$ pants run //:jq -- --help` yields usage: ``` Usage: /tmp/pants-sandbox-zLIAv5/3rdparty/tools/jq-linux64 [options] <jq filter> [file...] /tmp/pants-sandbox-zLIAv5/3rdparty/tools/jq-linux64 [options] --args <jq filter> [strings...] /tmp/pants-sandbox-zLIAv5/3rdparty/tools/jq-linux64 [options] --jsonargs <jq filter> [JSON_TEXTS...] ``` **Pants version** `main` **OS** Linux **Additional info**
CC @chrisjrn Changing the `argv` inside `_prepare_process_request_from_target` to `f'exec -a {shell_command.address.spec} {command}',` _almost_ does the right thing, but the quoting is off. It produces `/usr/bin/bash -c $'\'exec -a //:sandboxed-jq chmod +x jq-linux64\''`, but what we want is `/usr/bin/bash -c $'exec -a //:sandboxed-jq chmod +x jq-linux64'` @thejcannon This is probably something where you want to start nesting `shlex.quote` calls. Maybe? Also the code I'm editing is the wrong codepath :sweat_smile:
2023-05-16T20:25:44
pantsbuild/pants
19,031
pantsbuild__pants-19031
[ "19017" ]
c3dddf9848fd8d753cc4ce058e595d21460ab868
diff --git a/src/python/pants/backend/shell/target_types.py b/src/python/pants/backend/shell/target_types.py --- a/src/python/pants/backend/shell/target_types.py +++ b/src/python/pants/backend/shell/target_types.py @@ -266,7 +266,15 @@ class ShellSourcesGeneratorTarget(TargetFilesGenerator): class ShellCommandCommandField(StringField): alias = "command" required = True - help = "Shell command to execute.\n\nThe command is executed as 'bash -c <command>' by default." + help = help_text( + """ + Shell command to execute. + + The command is executed as 'bash -c <command>' by default. If you want to invoke a binary + use `exec -a $0 <binary> <args>` as the command so that the binary gets the correct `argv[0]` + set. + """ + ) class ShellCommandOutputsField(StringSequenceField):
`AdhocProcessRequest` isn't replacing `$0` correctly **Describe the bug** From https://pantsbuild.slack.com/archives/C0D7TNJHL/p1684255827991839 ``` file( name="downloaded-jq", source = http_source( len = 3953824, sha256 = "af986793a515d500ab2d35f8d2aecd656e764504b789b66d7e1a0b727a124c44", url = "https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64", ), ) shell_command( name = "sandboxed-jq", command="chmod +x jq-linux64", tools = ["chmod"], execution_dependencies=[":downloaded-jq"], output_directories = ["."], ) run_shell_command( name = "jq", command=f"{{chroot}}/{build_file_dir() / 'jq-linux64'}", execution_dependencies=[":sandboxed-jq"], workdir="/", ) ``` Run with: `$ pants run //:jq -- --help` yields usage: ``` Usage: /tmp/pants-sandbox-zLIAv5/3rdparty/tools/jq-linux64 [options] <jq filter> [file...] /tmp/pants-sandbox-zLIAv5/3rdparty/tools/jq-linux64 [options] --args <jq filter> [strings...] /tmp/pants-sandbox-zLIAv5/3rdparty/tools/jq-linux64 [options] --jsonargs <jq filter> [JSON_TEXTS...] ``` **Pants version** `main` **OS** Linux **Additional info**
CC @chrisjrn Changing the `argv` inside `_prepare_process_request_from_target` to `f'exec -a {shell_command.address.spec} {command}',` _almost_ does the right thing, but the quoting is off. It produces `/usr/bin/bash -c $'\'exec -a //:sandboxed-jq chmod +x jq-linux64\''`, but what we want is `/usr/bin/bash -c $'exec -a //:sandboxed-jq chmod +x jq-linux64'` @thejcannon This is probably something where you want to start nesting `shlex.quote` calls. Maybe? Also the code I'm editing is the wrong codepath :sweat_smile:
2023-05-18T01:59:23
pantsbuild/pants
19,093
pantsbuild__pants-19093
[ "18089" ]
2307d75e63c8abddad6f18a9b6bfc5fb0de84edc
diff --git a/src/python/pants/backend/helm/util_rules/tool.py b/src/python/pants/backend/helm/util_rules/tool.py --- a/src/python/pants/backend/helm/util_rules/tool.py +++ b/src/python/pants/backend/helm/util_rules/tool.py @@ -440,10 +440,12 @@ async def setup_helm( @rule async def helm_process( - request: HelmProcess, helm_binary: HelmBinary, helm_subsytem: HelmSubsystem + request: HelmProcess, + helm_binary: HelmBinary, + helm_subsystem: HelmSubsystem, ) -> Process: global_extra_env = await Get( - EnvironmentVars, EnvironmentVarsRequest(helm_subsytem.extra_env_vars) + EnvironmentVars, EnvironmentVarsRequest(helm_subsystem.extra_env_vars) ) # Helm binary's setup parameters go last to prevent end users overriding any of its values. @@ -455,8 +457,21 @@ async def helm_process( } append_only_caches = {**request.extra_append_only_caches, **helm_binary.append_only_caches} + argv = [helm_binary.path, *request.argv] + + # A special case for "--debug". + # This ensures that it is applied to all operations in the chain, + # not just the final one. + # For example, we want this applied to the call to `template`, not just the call to `install` + # Also, we can be helpful and automatically forward a request to debug Pants to also debug Helm + debug_requested = "--debug" in helm_subsystem.valid_args() or ( + 0 < logger.getEffectiveLevel() <= LogLevel.DEBUG.level + ) + if debug_requested and "--debug" not in request.argv: + argv.append("--debug") + return Process( - [helm_binary.path, *request.argv], + argv, input_digest=request.input_digest, immutable_input_digests=immutable_input_digests, env=env, diff --git a/src/python/pants/util/logging.py b/src/python/pants/util/logging.py --- a/src/python/pants/util/logging.py +++ b/src/python/pants/util/logging.py @@ -17,7 +17,7 @@ class LogLevel(Enum): NB: The `logging` module uses the opposite integer ordering of levels from Rust's `log` crate, but the ordering implementation of this enum inverts its comparison to make its ordering align - with Rust's. + with Rust's. That is, TRACE > DEBUG > INFO > WARN > ERROR """ TRACE = ("trace", TRACE)
helm backend doesn't pass --debug to template despite (misleading!) "Use --debug flag to render out invalid YAML" **Describe the bug** ``` $ tree src/chart/foo/ src/chart/foo/ ├── BUILD ├── Chart.yaml ├── templates │   ├── app.yaml │   └── _helpers.tpl └── values.yaml 1 directory, 5 files ``` ``` $ cat src/chart/foo/BUILD helm_chart( name="foo" ) helm_deployment(dependencies=[":foo"], name="deployfoo") ``` ``` $ cat src/chart/foo/templates/app.yaml {{ include "doesnotexist" (list $ .) }} ``` So trying to deploy this contrived example gives ``` $ ./pants experimental-deploy src/chart/foo:deployfoo 15:33:50.61 [INFO] Initialization options changed: reinitializing scheduler... 15:33:53.65 [INFO] Scheduler initialized. 15:33:54.09 [ERROR] 1 Exception encountered: Engine traceback: in `experimental-deploy` goal ProcessExecutionFailure: Process 'Rendering Helm deployment src/chart/foo:deployfoo' failed with exit code 1. stdout: stderr: Error: template: foo/templates/app.yaml:1:3: executing "foo/templates/app.yaml" at <include "doesnotexist" (list $ .)>: error calling include: template: no template "doesnotexist" associated with template "gotpl" Use --debug flag to render out invalid YAML Use `--keep-sandboxes=on_failure` to preserve the process chroot for inspection. ``` So, following the suggestion in the error message: ``` $ ./pants --keep-sandboxes=on_failure experimental-deploy src/chart/foo:deployfoo -- --debug 15:34:39.94 [INFO] Initialization options changed: reinitializing scheduler... 15:34:43.04 [INFO] Scheduler initialized. 15:34:43.48 [INFO] Preserving local process execution dir /tmp/pants-sandbox-C9BdhW for Rendering Helm deployment src/chart/foo:deployfoo 15:34:43.49 [ERROR] 1 Exception encountered: Engine traceback: in `experimental-deploy` goal ProcessExecutionFailure: Process 'Rendering Helm deployment src/chart/foo:deployfoo' failed with exit code 1. stdout: stderr: Error: template: foo/templates/app.yaml:1:3: executing "foo/templates/app.yaml" at <include "doesnotexist" (list $ .)>: error calling include: template: no template "doesnotexist" associated with template "gotpl" Use --debug flag to render out invalid YAML ``` Huh I thought I did use the `--debug` flag. ``` $ cat /tmp/pants-sandbox-C9BdhW/__run.sh #!/bin/bash # This command line should execute the same process as pants did internally. export HELM_CACHE_HOME=__cache HELM_CONFIG_HOME=__config HELM_DATA_HOME=__data HOME=/home/ecsb PATH=$'/home/ecsb/.cargo/bin:/home/ecsb/bin/:/home/ecsb/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin:/usr/lib/llvm/15/bin:/usr/lib/llvm/14/bin' cd /tmp/pants-sandbox-C9BdhW __helm/linux-amd64/helm template deployfoo foo --output-dir __out --values __values/src/chart/foo/Chart.yaml,__values/src/chart/foo/values.yaml ``` ^^ No flag But! to add to that confusion... if I manually add the flag to the sandbox it isn't all that helpful after all ``` $ pwd /tmp/pants-sandbox-C9BdhW $ tail -1 __run.sh __helm/linux-amd64/helm template deployfoo foo --output-dir __out --values __values/src/chart/foo/Chart.yaml,__values/src/chart/foo/values.yaml --debug $ ./__run.sh install.go:192: [debug] Original chart version: "" install.go:209: [debug] CHART PATH: /tmp/pants-sandbox-C9BdhW/foo Error: template: foo/templates/app.yaml:1:3: executing "foo/templates/app.yaml" at <include "doesnotexist" (list $ .)>: error calling include: template: no template "doesnotexist" associated with template "gotpl" helm.go:84: [debug] template: foo/templates/app.yaml:1:3: executing "foo/templates/app.yaml" at <include "doesnotexist" (list $ .)>: error calling include: template: no template "doesnotexist" associated with template "gotpl" ``` Since the original message comes from helm I'm not sure what to suggest. But the behavior where stdout says "use this flag!" and then pants swallows the flag when you use it doesn't feel great. **Pants version** 2.16.0.dev5 **OS** Linux **Additional info** Add any other information about the problem here, such as attachments or links to gists, if relevant.
ah, so, looks like the args are passed through to the `helm upgrade` but not to the calls to `helm template` before that.
2023-05-22T19:53:27
pantsbuild/pants
19,100
pantsbuild__pants-19100
[ "19068" ]
942a8cca5b4e03acca8f872d4640f24bd174f0ad
diff --git a/src/python/pants/backend/javascript/package/rules.py b/src/python/pants/backend/javascript/package/rules.py --- a/src/python/pants/backend/javascript/package/rules.py +++ b/src/python/pants/backend/javascript/package/rules.py @@ -16,6 +16,7 @@ NodeBuildScript, NodeBuildScriptEntryPointField, NodeBuildScriptExtraCaches, + NodeBuildScriptExtraEnvVarsField, NodeBuildScriptOutputDirectoriesField, NodeBuildScriptOutputFilesField, NodeBuildScriptSourcesField, @@ -32,6 +33,7 @@ PackageFieldSet, ) from pants.core.target_types import ResourceSourceField +from pants.engine.env_vars import EnvironmentVars, EnvironmentVarsRequest from pants.engine.internals.native_engine import AddPrefix, Digest, Snapshot from pants.engine.internals.selectors import Get from pants.engine.process import ProcessResult @@ -66,6 +68,7 @@ class NodeBuildScriptPackageFieldSet(PackageFieldSet): output_directories: NodeBuildScriptOutputDirectoriesField output_files: NodeBuildScriptOutputFilesField extra_caches: NodeBuildScriptExtraCaches + extra_env_vars: NodeBuildScriptExtraEnvVarsField @dataclass(frozen=True) @@ -128,6 +131,7 @@ class NodeBuildScriptRequest: output_directories: tuple[str, ...] script_name: str extra_caches: tuple[str, ...] + extra_env_vars: tuple[str, ...] def __post_init__(self) -> None: if not (self.output_directories or self.output_files): @@ -154,6 +158,7 @@ def from_generate_request( or (), script_name=req.protocol_target[NodeBuildScriptEntryPointField].value, extra_caches=req.protocol_target[NodeBuildScriptExtraCaches].value or (), + extra_env_vars=req.protocol_target[NodeBuildScriptExtraEnvVarsField].value or (), ) @classmethod @@ -164,6 +169,7 @@ def from_package_request(cls, req: NodeBuildScriptPackageFieldSet) -> NodeBuildS output_directories=req.output_directories.value or (), script_name=req.script_name.value, extra_caches=req.extra_caches.value or (), + extra_env_vars=req.extra_env_vars.value or (), ) def get_paths(self) -> Iterable[str]: @@ -180,12 +186,14 @@ async def run_node_build_script(req: NodeBuildScriptRequest) -> NodeBuildScriptR output_dirs = req.output_directories script_name = req.script_name extra_caches = req.extra_caches + extra_env_vars = req.extra_env_vars def cache_name(cache_path: str) -> str: parts = (installation.project_env.package_dir(), script_name, cache_path) return "_".join(_NOT_ALPHANUMERIC.sub("_", part) for part in parts if part) args = ("run", script_name) + target_env_vars = await Get(EnvironmentVars, EnvironmentVarsRequest(extra_env_vars)) result = await Get( ProcessResult, NodeJsProjectEnvironmentProcess( @@ -204,6 +212,7 @@ def cache_name(cache_path: str) -> str: per_package_caches=FrozenDict( {cache_name(extra_cache): extra_cache for extra_cache in extra_caches or ()} ), + extra_env=target_env_vars, ), ) diff --git a/src/python/pants/backend/javascript/package_json.py b/src/python/pants/backend/javascript/package_json.py --- a/src/python/pants/backend/javascript/package_json.py +++ b/src/python/pants/backend/javascript/package_json.py @@ -88,6 +88,7 @@ class NodeBuildScript(NodeScript): output_directories: tuple[str, ...] = () output_files: tuple[str, ...] = () extra_caches: tuple[str, ...] = () + extra_env_vars: tuple[str, ...] = () alias: ClassVar[str] = "node_build_script" @@ -98,6 +99,7 @@ def create( output_directories: Iterable[str] = (), output_files: Iterable[str] = (), extra_caches: Iterable[str] = (), + extra_env_vars: Iterable[str] = (), ) -> NodeBuildScript: """A build script, mapped from the `scripts` section of a package.json file. @@ -110,6 +112,7 @@ def create( output_directories=tuple(output_directories), output_files=tuple(output_files), extra_caches=tuple(extra_caches), + extra_env_vars=tuple(extra_env_vars), ) @@ -410,6 +413,20 @@ class NodeBuildScriptOutputDirectoriesField(StringSequenceField): ) +class NodeBuildScriptExtraEnvVarsField(StringSequenceField): + alias = "extra_env_vars" + required = False + default = () + help = help_text( + """ + Additional environment variables to include in environment when running a build script process. + + 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. + """ + ) + + class NodeBuildScriptExtraCaches(StringSequenceField): alias = "extra_caches" required = False @@ -452,6 +469,7 @@ class NodeBuildScriptTarget(Target): NodeBuildScriptOutputFilesField, NodeBuildScriptSourcesField, NodeBuildScriptExtraCaches, + NodeBuildScriptExtraEnvVarsField, NodePackageDependenciesField, OutputPathField, ) @@ -923,6 +941,7 @@ async def generate_node_package_targets( NodeBuildScriptEntryPointField.alias: build_script.entry_point, NodeBuildScriptOutputDirectoriesField.alias: build_script.output_directories, NodeBuildScriptOutputFilesField.alias: build_script.output_files, + NodeBuildScriptExtraEnvVarsField.alias: build_script.extra_env_vars, NodeBuildScriptExtraCaches.alias: build_script.extra_caches, NodePackageDependenciesField.alias: [ file_tgt.address.spec, diff --git a/src/python/pants/backend/javascript/run/rules.py b/src/python/pants/backend/javascript/run/rules.py --- a/src/python/pants/backend/javascript/run/rules.py +++ b/src/python/pants/backend/javascript/run/rules.py @@ -13,10 +13,12 @@ from pants.backend.javascript.nodejs_project_environment import NodeJsProjectEnvironmentProcess from pants.backend.javascript.package_json import ( NodeBuildScriptEntryPointField, + NodeBuildScriptExtraEnvVarsField, NodePackageDependenciesField, ) from pants.core.goals.run import RunFieldSet, RunInSandboxBehavior, RunRequest from pants.core.util_rules.environments import EnvironmentField +from pants.engine.env_vars import EnvironmentVars, EnvironmentVarsRequest from pants.engine.internals.selectors import Get from pants.engine.process import Process from pants.engine.rules import Rule, collect_rules, rule @@ -29,6 +31,7 @@ class RunNodeBuildScriptFieldSet(RunFieldSet): run_in_sandbox_behavior = RunInSandboxBehavior.RUN_REQUEST_HERMETIC entry_point: NodeBuildScriptEntryPointField + extra_env_vars: NodeBuildScriptExtraEnvVarsField environment: EnvironmentField @@ -39,6 +42,9 @@ async def run_node_build_script( installation = await Get( InstalledNodePackageWithSource, InstalledNodePackageRequest(field_set.address) ) + target_env_vars = await Get( + EnvironmentVars, EnvironmentVarsRequest(field_set.extra_env_vars.value or ()) + ) process = await Get( Process, NodeJsProjectEnvironmentProcess( @@ -46,6 +52,7 @@ async def run_node_build_script( args=("--prefix", "{chroot}", "run", str(field_set.entry_point.value)), description=f"Running {str(field_set.entry_point.value)}.", input_digest=installation.digest, + extra_env=target_env_vars, ), )
diff --git a/src/python/pants/backend/javascript/package/rules_test.py b/src/python/pants/backend/javascript/package/rules_test.py --- a/src/python/pants/backend/javascript/package/rules_test.py +++ b/src/python/pants/backend/javascript/package/rules_test.py @@ -234,3 +234,42 @@ def test_packages_files_as_resource_in_workspace( rule_runner.write_digest(result.snapshot.digest) with open(os.path.join(rule_runner.build_root, "src/js/a/dist/index.cjs")) as f: assert f.read() == "blarb\n" + + +def test_extra_envs(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "src/js/BUILD": dedent( + """\ + package_json( + scripts=[ + node_build_script(entry_point="build", extra_env_vars=["FOO=BAR"], output_files=["dist/index.cjs"]) + ] + ) + """ + ), + "src/js/package.json": json.dumps( + { + "name": "ham", + "version": "0.0.1", + "browser": "lib/index.mjs", + "scripts": {"build": "mkdir dist && echo $FOO >> dist/index.cjs"}, + } + ), + "src/js/package-lock.json": json.dumps({}), + "src/js/lib/BUILD": dedent( + """\ + javascript_sources() + """ + ), + "src/js/lib/index.mjs": "", + } + ) + tgt = rule_runner.get_target(Address("src/js", generated_name="build")) + snapshot = rule_runner.request(Snapshot, (EMPTY_DIGEST,)) + result = rule_runner.request( + GeneratedSources, [GenerateResourcesFromNodeBuildScriptRequest(snapshot, tgt)] + ) + rule_runner.write_digest(result.snapshot.digest) + with open(os.path.join(rule_runner.build_root, "src/js/dist/index.cjs")) as f: + assert f.read() == "BAR\n" diff --git a/src/python/pants/backend/javascript/run/rules_test.py b/src/python/pants/backend/javascript/run/rules_test.py --- a/src/python/pants/backend/javascript/run/rules_test.py +++ b/src/python/pants/backend/javascript/run/rules_test.py @@ -75,3 +75,38 @@ def test_creates_run_requests_package_json_scripts(rule_runner: RuleRunner) -> N result = rule_runner.request(RunRequest, [RunNodeBuildScriptFieldSet.create(tgt)]) assert result.args == ("npm", "--prefix", "{chroot}", "run", script) + + +def test_extra_envs(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "src/js/BUILD": dedent( + """\ + package_json( + scripts=[ + node_build_script(entry_point="build", extra_env_vars=["FOO=BAR"], output_files=["dist/index.cjs"]) + ] + ) + """ + ), + "src/js/package.json": json.dumps( + { + "name": "ham", + "version": "0.0.1", + "browser": "lib/index.mjs", + "scripts": {"build": "mkdir dist && echo $FOO >> dist/index.cjs"}, + } + ), + "src/js/package-lock.json": json.dumps({}), + "src/js/lib/BUILD": dedent( + """\ + javascript_sources() + """ + ), + "src/js/lib/index.mjs": "", + } + ) + tgt = rule_runner.get_target(Address("src/js", generated_name="build")) + + result = rule_runner.request(RunRequest, [RunNodeBuildScriptFieldSet.create(tgt)]) + assert result.extra_env.get("FOO") == "BAR"
javascript: Enable passing env vars to `node_build_script` **Is your feature request related to a problem? Please describe.** Quote from slack: >It would be great if we could use extra_env_vars to set up environment variables for node_build_script. Many projects need compile time env vars to create a bundle. **Describe the solution you'd like** An `extra_env_vars` field on `node_build_script`. **Describe alternatives you've considered** - **Additional context** -
2023-05-23T14:35:01
pantsbuild/pants
19,130
pantsbuild__pants-19130
[ "19098" ]
a34feabef5400eb52472c34900ed39438dfa1d55
diff --git a/src/python/pants/backend/docker/target_types.py b/src/python/pants/backend/docker/target_types.py --- a/src/python/pants/backend/docker/target_types.py +++ b/src/python/pants/backend/docker/target_types.py @@ -282,8 +282,9 @@ class DockerImageBuildSecretsOptionField( Secret files to expose to the build (only if BuildKit enabled). Secrets may use absolute paths, or paths relative to your build root, or the BUILD file - if prefixed with `./`. The id should be valid as used by the Docker build `--secret` - option. See [Docker secrets](https://docs.docker.com/engine/swarm/secrets/) for more + if prefixed with `./`. Paths to your home directory will be automatically expanded. + The id should be valid as used by the Docker build `--secret` option. + See [Docker secrets](https://docs.docker.com/engine/swarm/secrets/) for more information. Example: @@ -292,6 +293,7 @@ class DockerImageBuildSecretsOptionField( secrets={ "mysecret": "/var/secrets/some-secret", "repo-secret": "src/proj/secrets/some-secret", + "home-dir-secret": "~/.config/some-secret", "target-secret": "./secrets/some-secret", } ) @@ -308,8 +310,9 @@ def option_values(self, **kwargs) -> Iterator[str]: full_path = os.path.join( get_buildroot(), self.address.spec_path if re.match(r"\.{1,2}/", path) else "", - path, + os.path.expanduser(path), ) + yield f"id={secret},src={os.path.normpath(full_path)}"
diff --git a/src/python/pants/backend/docker/target_types_test.py b/src/python/pants/backend/docker/target_types_test.py new file mode 100644 --- /dev/null +++ b/src/python/pants/backend/docker/target_types_test.py @@ -0,0 +1,36 @@ +# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). +import os +from pathlib import Path + +import pytest + +from pants.backend.docker.target_types import DockerImageBuildSecretsOptionField +from pants.engine.internals.native_engine import Address + + [email protected]( + "src, expected", + [ + ( + "/aboslute/path", + "/aboslute/path", + ), + ( + "./relative/path", + str(Path.cwd().joinpath("./relative/path")), + ), + ( + "~/home/path", + os.path.expanduser("~/home/path"), + ), + ], +) +def test_secret_path_resolvement(src: str, expected: str): + Path.cwd().joinpath("pants.toml").write_text("") + secrets_option_field = DockerImageBuildSecretsOptionField( + {"mysecret": src}, address=Address("") + ) + values = list(secrets_option_field.option_values()) + + assert values == [f"id=mysecret,src={expected}"]
docker_image secrets doesn't expanduser **Describe the bug** When defining secrets on a `docker_image` target, paths starting with `~` are not respected. For example: ``` docker_image( secrets={ mysecret="~/.secret" } ) ``` Leads to an error: `ERROR: failed to stat <pwd>/~/.secret: stat <pwd>/~/.secret: no such file or directory`. **Pants version** 2.15.0 **OS** MacOS
2023-05-24T13:29:11
pantsbuild/pants
19,135
pantsbuild__pants-19135
[ "18488" ]
5eda12ff32c23ababc1d6c6f2b6ab3c33f41cf38
diff --git a/build-support/bin/terraform_tool_versions.py b/build-support/bin/terraform_tool_versions.py --- a/build-support/bin/terraform_tool_versions.py +++ b/build-support/bin/terraform_tool_versions.py @@ -251,7 +251,7 @@ def fetch_versions( if __name__ == "__main__": versions_url = "https://releases.hashicorp.com/terraform/" - number_of_supported_versions = 32 + number_of_supported_versions = 43 keydata = requests.get("https://keybase.io/hashicorp/pgp_keys.asc").content verifier = GPGVerifier(keydata) diff --git a/src/python/pants/backend/terraform/tool.py b/src/python/pants/backend/terraform/tool.py --- a/src/python/pants/backend/terraform/tool.py +++ b/src/python/pants/backend/terraform/tool.py @@ -26,7 +26,7 @@ class TerraformTool(TemplatedExternalTool): # TODO: Possibly there should not be a default version, since terraform state is sensitive to # the version that created it, so you have to be deliberate about the version you select. - default_version = "1.0.7" + default_version = "1.4.6" default_url_template = ( "https://releases.hashicorp.com/terraform/{version}/terraform_{version}_{platform}.zip" ) @@ -40,132 +40,176 @@ class TerraformTool(TemplatedExternalTool): @classproperty def default_known_versions(cls): return [ - "1.3.5|macos_x86_64|6bf684dbc19ecbf9225f5a2409def32e5ef7d37af3899726accd9420a88a6bcd|20848406", - "1.3.5|macos_arm64|33b25ad89dedbd98bba09cbde69dcf9e928029f322ae9494279cf2c8ce47db89|19287887", + "1.4.6|macos_x86_64|5d8332994b86411b049391d31ad1a0785dfb470db8b9c50617de28ddb5d1f25d|22051279", + "1.4.6|macos_arm64|30a2f87298ff9f299452119bd14afaa8d5b000c572f62fa64baf432e35d9dec1|20613318", + "1.4.6|linux_x86_64|e079db1a8945e39b1f8ba4e513946b3ab9f32bd5a2bdf19b9b186d22c5a3d53b|20779821", + "1.4.6|linux_arm64|b38f5db944ac4942f11ceea465a91e365b0636febd9998c110fbbe95d61c3b26|18834675", + "1.4.5|macos_x86_64|808e54d826737e9a0ca79bbe29330e50d3622bbeeb26066c63b371a291731711|22031074", + "1.4.5|macos_arm64|7104d9d13632aa61b494a349c589048d21bd550e579404c3a41c4932e4d6aa97|20592841", + "1.4.5|linux_x86_64|ce10e941cd11554b15a189cd00191c05abc20dff865599d361bdb863c5f406a9|20767621", + "1.4.5|linux_arm64|ca2c48f518f72fef668255150cc5e63b92545edc62a05939bbff8a350bceb357|18813058", + "1.4.4|macos_x86_64|0303ed9d7e5a225fc2e6fa9bf76fc6574c0c0359f22d5dfc04bc8b3234444f7c|22032187", + "1.4.4|macos_arm64|75602d9ec491982ceabea813569579b2991093a4e0d76b7ca86ffd9b7a2a1d1e|20594012", + "1.4.4|linux_x86_64|67541c1f6631befcc25b764028e5605e59234d4424e60a256518ee1e8dd50593|20767354", + "1.4.4|linux_arm64|f0b4e092f2aa6de3324e5e4b5b51260ecf5e8c2f5335ff7a2ffdc4fb54a8922d|18814310", + "1.4.3|macos_x86_64|89bdb242bfacf24167f365ef7a3bf0ad0e443ddd27ebde425fb71d77ce1a2597|22032267", + "1.4.3|macos_arm64|20b9d484bf99ada6c0de89316176ba33f7c87f64c0738991188465147bba221b|20574247", + "1.4.3|linux_x86_64|2252ee6ac8437b93db2b2ba341edc87951e2916afaeb50a88b858e80796e9111|20781685", + "1.4.3|linux_arm64|d3d9464953d390970e7f4f7cbcd94dbf63136da6fe1cbb4955d944a9315bdcdb|18814307", + "1.4.2|macos_x86_64|c218a6c0ef6692b25af16995c8c7bdf6739e9638fef9235c6aced3cd84afaf66|22030042", + "1.4.2|macos_arm64|af8ff7576c8fc41496fdf97e9199b00d8d81729a6a0e821eaf4dfd08aa763540|20588400", + "1.4.2|linux_x86_64|9f3ca33d04f5335472829d1df7785115b60176d610ae6f1583343b0a2221a931|20234129", + "1.4.2|linux_arm64|39c182670c4e63e918e0a16080b1cc47bb16e158d7da96333d682d6a9cb8eb91|18206088", + "1.4.1|macos_x86_64|96466364a7e66e3d456ecb6c85a63c83e124c004f8835fb8ea9b7bbb7542a9d0|22077050", + "1.4.1|macos_arm64|61f76e130b97c8a9017d8aaff15d252af29117e35ea1a0fc30bcaab7ceafce73|20634145", + "1.4.1|linux_x86_64|9e9f3e6752168dea8ecb3643ea9c18c65d5a52acc06c22453ebc4e3fc2d34421|20276168", + "1.4.1|linux_arm64|53322cc70b6e50ac1985bf26a78ffa2814789a4704880f071eaf3e67a463d6f6|18248378", + "1.4.0|macos_x86_64|e897a4217f1c3bfe37c694570dcc6371336fbda698790bb6b0547ec8daf1ffb3|21935694", + "1.4.0|macos_arm64|d4a1e564714c6acf848e86dc020ff182477b49f932e3f550a5d9c8f5da7636fb|20508091", + "1.4.0|linux_x86_64|5da60da508d6d1941ffa8b9216147456a16bbff6db7622ae9ad01d314cbdd188|20144407", + "1.4.0|linux_arm64|33e0f4f0b75f507fc19012111de008308df343153cd6a3992507f4566c0bb723|18130960", + "1.3.9|macos_x86_64|a73326ea8fb06f6976597e005f8047cbd55ac76ed1e517303d8f6395db6c7805|21194871", + "1.3.9|macos_arm64|d8a59a794a7f99b484a07a0ed2aa6520921d146ac5a7f4b1b806dcf5c4af0525|19793371", + "1.3.9|linux_x86_64|53048fa573effdd8f2a59b726234c6f450491fe0ded6931e9f4c6e3df6eece56|19477757", + "1.3.9|linux_arm64|da571087268c5faf884912c4239c6b9c8e1ed8e8401ab1dcb45712df70f42f1b|17513770", + "1.3.8|macos_x86_64|1a27a6fac31ecb05de610daf61a29fe83d304d7c519d773afbf56c11c3b6276b|21189878", + "1.3.8|macos_arm64|873b05ac81645cd7289d6ccfd3e73d4735af1a453f2cd19da0650bdabf7d2eb6|19780134", + "1.3.8|linux_x86_64|9d9e7d6a9b41cef8b837af688441d4fbbd84b503d24061d078ad662441c70240|19479266", + "1.3.8|linux_arm64|a42bf3c7d6327f45d2b212b692ab4229285fb44dbb8adb7c39e18be2b26167c8|17507360", + "1.3.7|macos_x86_64|eeae48adcd55212b34148ed203dd5843e9b2a84a852a9877f3386fadb0514980|21185288", + "1.3.7|macos_arm64|01d553db5f7b4cf0729b725e4402643efde5884b1dabf5eb80af328ce5e447cf|19774151", + "1.3.7|linux_x86_64|b8cf184dee15dfa89713fe56085313ab23db22e17284a9a27c0999c67ce3021e|19464102", + "1.3.7|linux_arm64|5b491c555ea8a62dda551675fd9f27d369f5cdbe87608d2a7367d3da2d38ea38|17499971", + "1.3.6|macos_x86_64|13881fe0100238577394243a90c0631783aad21b77a9a7ee830404f86c0d37bb|21183111", + "1.3.6|macos_arm64|dbff0aeeaeee877c254f5414bef5c9d186e159aa0019223aac678abad9442c53|19779986", + "1.3.6|linux_x86_64|bb44a4c2b0a832d49253b9034d8ccbd34f9feeb26eda71c665f6e7fa0861f49b|19466755", + "1.3.6|linux_arm64|f4b1af29094290f1b3935c29033c4e5291664ee2c015ca251a020dd425c847c3|17501845", + "1.3.5|macos_x86_64|e6c9836188265b20c2588e9c9d6b1727094b324a379337e68ba58a6d26be8b51|21182319", + "1.3.5|macos_arm64|fcec1cbff229fbe59b03257ba2451d5ad1f5129714f08ccf6372b2737647c063|19780547", "1.3.5|linux_x86_64|ac28037216c3bc41de2c22724e863d883320a770056969b8d211ca8af3d477cf|19469337", "1.3.5|linux_arm64|ba5b1761046b899197bbfce3ad9b448d14550106d2cc37c52a60fc6822b584ed|17502759", - "1.3.4|macos_x86_64|03e0d7f629f28e2ea31ec2c69408b500f00eac674c613f7f1097536dcfa2cf6c|20847508", - "1.3.4|macos_arm64|7b4401edd8de50cda97d76b051c3a4b1882fa5aa8e867d4c4c2770e4c3b0056e|19284666", + "1.3.4|macos_x86_64|2a75c69ec5ed8506658b266a40075256b62a7d245ff6297df7e48fa72af23879|21181585", + "1.3.4|macos_arm64|a1f740f92afac6db84421a3ec07d9061c34a32f88b4b0b47d243de16c961169f|19773343", "1.3.4|linux_x86_64|b24210f28191fa2a08efe69f54e3db2e87a63369ac4f5dcaf9f34dc9318eb1a8|19462529", "1.3.4|linux_arm64|65381c6b61b2d1a98892199f649a5764ff5a772080a73d70f8663245e6402c39|17494667", - "1.3.3|macos_x86_64|e544aefb984fd9b19de250ac063a7aa28cbfdce2eda428dd2429a521912f6a93|20843907", - "1.3.3|macos_arm64|1850df7904025b20b26ac101274f30673b132adc84686178d3d0cb802be4597e|19268812", + "1.3.3|macos_x86_64|2b3cf653cd106becdea562b6c8d3f8939641e5626c5278729cbef81678fa9f42|21163874", + "1.3.3|macos_arm64|51e94ecf88059e8a53c363a048b658230f560574f99b0d8396ebacead894d159|19755200", "1.3.3|linux_x86_64|fa5cbf4274c67f2937cabf1a6544529d35d0b8b729ce814b40d0611fd26193c1|19451941", "1.3.3|linux_arm64|b940a080c698564df5e6a2f1c4e1b51b2c70a5115358d2361e3697d3985ecbfe|17488660", - "1.3.2|macos_x86_64|edaed5a7c4057f1f2a3826922f3e594c45e24c1e22605b94de9c097b683c38bd|20843900", - "1.3.2|macos_arm64|ff92cd79b01d39a890314c2df91355c0b6d6815fbc069ccaee9da5d8b9ff8580|19270064", + "1.3.2|macos_x86_64|3639461bbc712dc130913bbe632afb449fce8c0df692429d311e7cb808601901|21163990", + "1.3.2|macos_arm64|80480acbfee2e2d0b094f721f7568a40b790603080d6612e19b797a16b8ba82d|19757201", "1.3.2|linux_x86_64|6372e02a7f04bef9dac4a7a12f4580a0ad96a37b5997e80738e070be330cb11c|19451510", "1.3.2|linux_arm64|ce1a8770aaf27736a3352c5c31e95fb10d0944729b9d81013bf6848f8657da5f|17485206", - "1.3.1|macos_x86_64|5f5967e12e75a3ca1720be3eeba8232b4ba8b42d2d9e9f9664eff7a68267e873|20842029", - "1.3.1|macos_arm64|a525488cc3a26d25c5769fb7ffcabbfcd64f79cec5ebbfc94c18b5ec74a03b35|19269260", + "1.3.1|macos_x86_64|4282ebe6d1d72ace0d93e8a4bcf9a6f3aceac107966216355bb516b1c49cc203|21161667", + "1.3.1|macos_arm64|f0514f29b08da2f39ba4fff0d7eb40093915c9c69ddc700b6f39b78275207d96|19756039", "1.3.1|linux_x86_64|0847b14917536600ba743a759401c45196bf89937b51dd863152137f32791899|19450765", "1.3.1|linux_arm64|7ebb3d1ff94017fbef8acd0193e0bd29dec1a8925e2b573c05a92fdb743d1d5b|17486534", - "1.3.0|macos_x86_64|6502dbcbd7d1a356fa446ec12c2859a9a7276af92c89ce3cef7f675a8582a152|20842934", - "1.3.0|macos_arm64|6a3512a1b1006f2edc6fe5f51add9a6e1ef3967912ecf27e66f22e70b9ad7158|19255975", + "1.3.0|macos_x86_64|80e55182d4495da867c93c25dc6ae29be83ece39d3225e6adedecd55b72d6bbf|21163947", + "1.3.0|macos_arm64|df703317b5c7f80dc7c61e46de4697c9f440e650a893623351ab5e184995b404|19741011", "1.3.0|linux_x86_64|380ca822883176af928c80e5771d1c0ac9d69b13c6d746e6202482aedde7d457|19450952", "1.3.0|linux_arm64|0a15de6f934cf2217e5055412e7600d342b4f7dcc133564690776fece6213a9a|17488551", - "1.2.9|macos_x86_64|46206e564fdd792e709b7ec70eab1c873c9b1b17f4d33c07a1faa9d68955061b|21329275", - "1.2.9|macos_arm64|e61195aa7cc5caf6c86c35b8099b4a29339cd51e54518eb020bddb35cfc0737d|19773052", + "1.2.9|macos_x86_64|84a678ece9929cebc34c7a9a1ba287c8b91820b336f4af8437af7feaa0117b7c|21672810", + "1.2.9|macos_arm64|bc3b94b53cdf1be3c4988faa61aad343f48e013928c64bfc6ebeb61657f97baa|20280541", "1.2.9|linux_x86_64|0e0fc38641addac17103122e1953a9afad764a90e74daf4ff8ceeba4e362f2fb|19906116", "1.2.9|linux_arm64|6da7bf01f5a72e61255c2d80eddeba51998e2bb1f50a6d81b0d3b71e70e18531|17946045", - "1.2.8|macos_x86_64|0f8eecc764b57a938aa115a3ce2baa0d245479f17c28a4217bcf432ee23c2c5d|21332730", - "1.2.8|macos_arm64|d6b900682d33aff84f8f63f69557f8ea8537218748fcac6f12483aaa46959a14|19770539", + "1.2.8|macos_x86_64|efd3e21a9bb1cfa68303f8d119ea8970dbb616f5f99caa0fe21d796e0cd70252|21678594", + "1.2.8|macos_arm64|2c83bfea9e1c202c449e91bee06a804afb45cb8ba64a73da48fb0f61df51b327|20277152", "1.2.8|linux_x86_64|3e9c46d6f37338e90d5018c156d89961b0ffb0f355249679593aff99f9abe2a2|19907515", "1.2.8|linux_arm64|26c05cadb05cdaa8ac64b90b982b4e9350715ec2e9995a6b03bb964d230de055|17947439", - "1.2.7|macos_x86_64|acc781e964be9b527101b00eb6e7e63e7e509dd1355ff8567b80d0244c460634|21330075", - "1.2.7|macos_arm64|e4717057e1cbb606f1e089261def9a17ddd18b78707d9e212c768dc0d739a220|19773241", + "1.2.7|macos_x86_64|74e47b54ea78685be24c84e0e17b22b56220afcdb24ec853514b3863199f01e4|21673162", + "1.2.7|macos_arm64|ec4e623914b411f8cc93a1e71396a1e7f1fe1e96bb2e532ba3e955d2ca5cc442|20278743", "1.2.7|linux_x86_64|dfd7c44a5b6832d62860a01095a15b53616fb3ea4441ab89542f9364e3fca718|19907183", "1.2.7|linux_arm64|80d064008d57ba5dc97e189215c87275bf39ca14b1234430eae2f114394ea229|17943724", - "1.2.6|macos_x86_64|94d1efad05a06c879b9c1afc8a6f7acb2532d33864225605fc766ecdd58d9888|21328767", - "1.2.6|macos_arm64|452675f91cfe955a95708697a739d9b114c39ff566da7d9b31489064ceaaf66a|19774190", + "1.2.6|macos_x86_64|d896d2776af8b06cd4acd695ad75913040ce31234f5948688fd3c3fde53b1f75|21670957", + "1.2.6|macos_arm64|c88ceb34f343a2bb86960e32925c5ec43b41922ee9ede1019c5cf7d7b4097718|20279669", "1.2.6|linux_x86_64|9fd445e7a191317dcfc99d012ab632f2cc01f12af14a44dfbaba82e0f9680365|19905977", "1.2.6|linux_arm64|322755d11f0da11169cdb234af74ada5599046c698dccc125859505f85da2a20|17943213", - "1.2.5|macos_x86_64|d196f94486e54407524a0efbcb5756b197b763863ead2e145f86dd6c80fc9ce8|21323818", - "1.2.5|macos_arm64|77dd998d26e578aa22de557dc142672307807c88e3a4da65d8442de61479899f|19767100", + "1.2.5|macos_x86_64|2520fde736b43332b0c2648f4f6dde407335f322a3085114dc4f70e6e50eadc0|21659883", + "1.2.5|macos_arm64|92ad40db4a0930bdf872d6336a7b3a18b17c6fd04d9fc769b554bf51c8add505|20266441", "1.2.5|linux_x86_64|281344ed7e2b49b3d6af300b1fe310beed8778c56f3563c4d60e5541c0978f1b|19897064", "1.2.5|linux_arm64|0544420eb29b792444014988018ae77a7c8df6b23d84983728695ba73e38f54a|17938208", - "1.2.4|macos_x86_64|3e04343620fb01b8be01c8689dcb018b8823d8d7b070346086d7df22cc4cd5e6|21321939", - "1.2.4|macos_arm64|e596dcdfe55b2070a55fcb271873e86d1af7f6b624ffad4837ccef119fdac97a|19765021", + "1.2.4|macos_x86_64|e7d2c66264a3da94854ae6ff692bbb9a1bc11c36bb5658e3ef19841388a07430|21658356", + "1.2.4|macos_arm64|c31754ff5553707ef9fd2f913b833c779ab05ce192eb14913f51816a077c6798|20263133", "1.2.4|linux_x86_64|705ea62a44a0081594dad6b2b093eefefb12d54fa5a20a66562f9e082b00414c|19895510", "1.2.4|linux_arm64|11cfa2233dc708b51b16d5b923379db67e35c22b1b988773e5b31a7c2e251471|17936883", - "1.2.3|macos_x86_64|2962b0ebdf6f431b8fb182ffc1d8b582b73945db0c3ab99230ffc360d9e297a2|21318448", - "1.2.3|macos_arm64|601962205ad3dcf9b1b75f758589890a07854506cbd08ca2fc25afbf373bff53|19757696", + "1.2.3|macos_x86_64|bdc22658463237530dc120dadb0221762d9fb9116e7a6e0dc063d8ae649c431e|21658937", + "1.2.3|macos_arm64|6f06debac2ac54951464bf490e1606f973ab53ad8ba5decea76646e8f9309512|20256836", "1.2.3|linux_x86_64|728b6fbcb288ad1b7b6590585410a98d3b7e05efe4601ef776c37e15e9a83a96|19891436", "1.2.3|linux_arm64|a48991e938a25bfe5d257f4b6cbbdc73d920cc34bbc8f0e685e28b9610ad75fe|17933271", - "1.2.2|macos_x86_64|bd224d57718ed2b6e5e3b55383878d4b122c6dc058d65625605cef1ace9dcb25|21317982", - "1.2.2|macos_arm64|4750d46e47345809a0baa3c330771c8c8a227b77bec4caa7451422a21acefae5|19758608", + "1.2.2|macos_x86_64|1d22663c1ab22ecea774ae63aee21eecfee0bbc23b953206d889a5ba3c08525a|21656824", + "1.2.2|macos_arm64|b87716b55a3b10cced60db5285bae57aee9cc0f81c555dccdc4f54f62c2a3b60|20254768", "1.2.2|linux_x86_64|2934a0e8824925beb956b2edb5fef212a6141c089d29d8568150a43f95b3a626|19889133", "1.2.2|linux_arm64|9c6202237d7477412054dcd36fdc269da9ee66ecbc45bb07d0d63b7d36af7b21|17932829", - "1.2.1|macos_x86_64|d7c9a677efb22276afdd6c7703cbfee87d509a31acb247b96aa550a35154400a|21309907", - "1.2.1|macos_arm64|96e3659e89bfb50f70d1bb8660452ec433019d00a862d2291817c831305d85ea|19751670", + "1.2.1|macos_x86_64|31c0fd4deb7c6a77c08d2fdf59c37950e6df7165088c004e1dd7f5e09fbf6307|21645582", + "1.2.1|macos_arm64|70159b3e3eb49ee71193815943d9217c59203fd4ee8c6960aeded744094a2250|20253448", "1.2.1|linux_x86_64|8cf8eb7ed2d95a4213fbfd0459ab303f890e79220196d1c4aae9ecf22547302e|19881618", "1.2.1|linux_arm64|972ea512dac822274791dedceb6e7f8b9ac2ed36bd7759269b6806d0ab049128|17922073", - "1.2.0|macos_x86_64|f608b1fee818988d89a16b7d1b6d22b37cc98892608c52c22661ca6cbfc3d216|21309982", - "1.2.0|macos_arm64|d4df7307bad8c13e443493c53898a7060f77d661bfdf06215b61b65621ed53e9|19750767", + "1.2.0|macos_x86_64|1b102ba3bf0c60ff6cbee74f721bf8105793c1107a1c6d03dcab98d7079f0c77|21645732", + "1.2.0|macos_arm64|f5e46cabe5889b60597f0e9c365cbc663e4c952c90a16c10489897c2075ae4f0|20253335", "1.2.0|linux_x86_64|b87de03adbdfdff3c2552c8c8377552d0eecd787154465100cf4e29de4a7be1f|19880608", "1.2.0|linux_arm64|ee80b8635d8fdbaed57beffe281cf87b8b1fd1ddb29c08d20e25a152d9f0f871|17920355", - "1.1.9|macos_x86_64|c902b3c12042ac1d950637c2dd72ff19139519658f69290b310f1a5924586286|20709155", - "1.1.9|macos_arm64|918a8684da5a5529285135f14b09766bd4eb0e8c6612a4db7c121174b4831739|19835808", + "1.1.9|macos_x86_64|685258b525eae94fb0b406faf661aa056d31666256bf28e625365a251cb89fdc|20850638", + "1.1.9|macos_arm64|39fac4be74462be86b2290dd09fe1092f73dfb48e2df92406af0e199cfa6a16c|20093184", "1.1.9|linux_x86_64|9d2d8a89f5cc8bc1c06cb6f34ce76ec4b99184b07eb776f8b39183b513d7798a|19262029", "1.1.9|linux_arm64|e8a09d1fe5a68ed75e5fabe26c609ad12a7e459002dea6543f1084993b87a266|17521011", - "1.1.8|macos_x86_64|29ad0af72d498a76bbc51cc5cb09a6d6d0e5673cbbab6ef7aca57e3c3e780f46|20216382", - "1.1.8|macos_arm64|d6fefdc27396a019da56cce26f7eeea3d6986714cbdd488ff6a424f4bca40de8|19371647", + "1.1.8|macos_x86_64|48f1f1e04d0aa8f5f1a661de95e3c2b8fd8ab16b3d44015372aff7693d36c2cf|20354970", + "1.1.8|macos_arm64|943e1948c4eae82cf8b490bb274939fe666252bbc146f098e7da65b23416264a|19631574", "1.1.8|linux_x86_64|fbd37c1ec3d163f493075aa0fa85147e7e3f88dd98760ee7af7499783454f4c5|18796132", "1.1.8|linux_arm64|10b2c063dcff91329ee44bce9d71872825566b713308b3da1e5768c6998fb84f|17107405", - "1.1.7|macos_x86_64|5e7e939e084ae29af7fd86b00a618433d905477c52add2d4ea8770692acbceac|20213394", - "1.1.7|macos_arm64|a36b6e2810f81a404c11005942b69c3d1d9baa8dd07de6b1f84e87a67eedb58f|19371095", + "1.1.7|macos_x86_64|6e56eea328683541f6de0d5f449251a974d173e6d8161530956a20d9c239731a|20351873", + "1.1.7|macos_arm64|8919ceee34f6bfb16a6e9ff61c95f4043c35c6d70b21de27e5a153c19c7eba9c|19625836", "1.1.7|linux_x86_64|e4add092a54ff6febd3325d1e0c109c9e590dc6c38f8bb7f9632e4e6bcca99d4|18795309", "1.1.7|linux_arm64|2f72982008c52d2d57294ea50794d7c6ae45d2948e08598bfec3e492bce8d96e|17109768", - "1.1.6|macos_x86_64|bbfc916117e45788661c066ec39a0727f64c7557bf6ce9f486bbd97c16841975|20168574", - "1.1.6|macos_arm64|dddb11195fc413653b98e7a830ec7314f297e6c22575fc878f4ee2287a25b4f5|19326402", + "1.1.6|macos_x86_64|7a499c1f08d89548ae4c0e829eea43845fa1bd7b464e7df46102b35e6081fe44|20303856", + "1.1.6|macos_arm64|f06a14fdb610ec5a7f18bdbb2f67187230eb418329756732d970b6ca3dae12c3|19577273", "1.1.6|linux_x86_64|3e330ce4c8c0434cdd79fe04ed6f6e28e72db44c47ae50d01c342c8a2b05d331|18751464", "1.1.6|linux_arm64|a53fb63625af3572f7252b9fb61d787ab153132a8984b12f4bb84b8ee408ec53|17069580", - "1.1.5|macos_x86_64|7d4dbd76329c25869e407706fed01213beb9d6235c26e01c795a141c2065d053|20157551", - "1.1.5|macos_arm64|723363af9524c0897e9a7d871d27f0d96f6aafd11990df7e6348f5b45d2dbe2c|19328643", + "1.1.5|macos_x86_64|dcf7133ebf61d195e432ddcb70e604bf45056163d960e991881efbecdbd7892b|20300006", + "1.1.5|macos_arm64|6e5a8d22343722dc8bfcf1d2fd7b742f5b46287f87171e8143fc9b87db32c3d4|19581167", "1.1.5|linux_x86_64|30942d5055c7151f051c8ea75481ff1dc95b2c4409dbb50196419c21168d6467|18748879", "1.1.5|linux_arm64|2fb6324c24c14523ae63cedcbc94a8e6c1c317987eced0abfca2f6218d217ca5|17069683", - "1.1.4|macos_x86_64|c2b2500835d2eb9d614f50f6f74c08781f0fee803699279b3eb0188b656427f2|20098620", - "1.1.4|macos_arm64|a753e6cf402beddc4043a3968ff3e790cf50cc526827cda83a0f442a893f2235|19248286", + "1.1.4|macos_x86_64|4f3bc78fedd4aa17f67acc0db4eafdb6d70ba72392aaba65fe72855520f11f3d|20242050", + "1.1.4|macos_arm64|5642b46e9c7fb692f05eba998cd4065fb2e48aa8b0aac9d2a116472fbabe34a1|19498408", "1.1.4|linux_x86_64|fca028d622f82788fdc35c1349e78d69ff07c7bb68c27d12f8b48c420e3ecdfb|18695508", "1.1.4|linux_arm64|3c1982cf0d16276c82960db60c998d79ba19e413af4fa2c7f6f86e4994379437|16996040", - "1.1.3|macos_x86_64|c54022e514a97e9b96dae24a3308227d034989ecbafb65e3293eea91f2d5edfb|20098660", - "1.1.3|macos_arm64|856e435da081d0a214c47a4eb09b1842f35eaa55e7ef0f9fa715d4816981d640|19244516", + "1.1.3|macos_x86_64|016bab760c96d4e64d2140a5f25c614ccc13c3fe9b3889e70c564bd02099259f|20241648", + "1.1.3|macos_arm64|02ba769bb0a8d4bc50ff60989b0f201ce54fd2afac2fb3544a0791aca5d3f6d5|19493636", "1.1.3|linux_x86_64|b215de2a18947fff41803716b1829a3c462c4f009b687c2cbdb52ceb51157c2f|18692580", "1.1.3|linux_arm64|ad5a1f2c132bedc5105e3f9900e4fe46858d582c0f2a2d74355da718bbcef65d|16996972", - "1.1.2|macos_x86_64|214da2e97f95389ba7557b8fcb11fe05a23d877e0fd67cd97fcbc160560078f1|20098558", - "1.1.2|macos_arm64|39e28f49a753c99b5e2cb30ac8146fb6b48da319c9db9d152b1e8a05ec9d4a13|19240921", + "1.1.2|macos_x86_64|78faa76db5dc0ecfe4bf7c6368dbf5cca019a806f9d203580a24a4e0f8cd8353|20240584", + "1.1.2|macos_arm64|cc3bd03b72db6247c9105edfeb9c8f674cf603e08259075143ffad66f5c25a07|19486800", "1.1.2|linux_x86_64|734efa82e2d0d3df8f239ce17f7370dabd38e535d21e64d35c73e45f35dfa95c|18687805", "1.1.2|linux_arm64|088e2226d1ddb7f68a4f65c704022a1cfdbf20fe40f02e0c3646942f211fd746|16994702", - "1.1.1|macos_x86_64|85fa7c90359c4e3358f78e58f35897b3e466d00c0d0648820830cac5a07609c3|20094218", - "1.1.1|macos_arm64|9cd8faf29095c57e30f04f9ca5fa9105f6717b277c65061a46f74f22f0f5907e|19240711", + "1.1.1|macos_x86_64|d125dd2e92b9245f2202199b52f234035f36bdcbcd9a06f08e647e14a9d9067a|20237718", + "1.1.1|macos_arm64|4cb6e5eb4f6036924caf934c509a1dfd61cd2c651bb3ee8fbfe2e2914dd9ed17|19488315", "1.1.1|linux_x86_64|07b8dc444540918597a60db9351af861335c3941f28ea8774e168db97dd74557|18687006", "1.1.1|linux_arm64|d6fd14da47af9ec5fa3ad5962eaef8eed6ff2f8a5041671f9c90ec5f4f8bb554|16995635", - "1.1.0|macos_x86_64|6fb2af160879d807291980642efa93cc9a97ddf662b17cc3753065c974a5296d|20089311", - "1.1.0|macos_arm64|f69e0613f09c21d44ce2131b20e8b97909f3fc7aa90c443639475f5e474a22ec|19240009", + "1.1.0|macos_x86_64|6e0ba9afb8795a544e70dc0459f0095fea7df15e38f5d88a7dd3f620d50f8bfe|20226329", + "1.1.0|macos_arm64|7955e173c7eadb87123fc0633c3ee67d5ba3b7d6c7f485fe803efed9f99dce54|19491369", "1.1.0|linux_x86_64|763378aa75500ce5ba67d0cba8aa605670cd28bf8bafc709333a30908441acb5|18683106", "1.1.0|linux_arm64|6697e9a263e264310373f3c91bf83f4cbfeb67b13994d2a8f7bcc492b554552e|16987201", - "1.0.11|macos_x86_64|92f2e7eebb9699e23800f8accd519775a02bd25fe79e1fe4530eca123f178202|19340098", - "1.0.11|macos_arm64|0f38af81641b00a2cbb8d25015d917887a7b62792c74c28d59e40e56ce6f265c|18498208", + "1.0.11|macos_x86_64|551a16b612edaae1037925d0e2dba30d16504ff4bd66606955172c2ed8d76131|19422757", + "1.0.11|macos_arm64|737e1765afbadb3d76e1929d4b4af8da55010839aa08e9e730d46791eb8ea5a6|18467868", "1.0.11|linux_x86_64|eeb46091a42dc303c3a3c300640c7774ab25cbee5083dafa5fd83b54c8aca664|18082446", "1.0.11|linux_arm64|30c650f4bc218659d43e07d911c00f08e420664a3d12c812228e66f666758645|16148492", - "1.0.10|macos_x86_64|e7595530a0dcdaec757621cbd9f931926fd904b1a1e5206bf2c9db6b73cee04d|33021017", - "1.0.10|macos_arm64|eecea1343888e2648d5f7ea25a29494fd3b5ecde95d0231024414458c59cb184|32073869", + "1.0.10|macos_x86_64|077479e98701bc9be88db21abeec684286fd85a3463ce437d7739d2a4e372f18|33140832", + "1.0.10|macos_arm64|776f2e144039ece66ae326ebda0884254848a2e11f0590757d02e3a74f058c81|32013985", "1.0.10|linux_x86_64|a221682fcc9cbd7fde22f305ead99b3ad49d8303f152e118edda086a2807716d|32674953", "1.0.10|linux_arm64|b091dbe5c00785ae8b5cb64149d697d61adea75e495d9e3d910f61d8c9967226|30505040", - "1.0.9|macos_x86_64|fb791c3efa323c5f0c2c36d14b9230deb1dc37f096a8159e718e8a9efa49a879|33017665", - "1.0.9|macos_arm64|aa5cc13903be35236a60d116f593e519534bcabbb2cf91b69cae19307a17b3c0|32069384", + "1.0.9|macos_x86_64|be122ff7fb925643c5ebf4e5704b18426e18d3ca49ab59ae33d208c908cb6d5a|33140006", + "1.0.9|macos_arm64|89b2b4fd1a0c57fabc08ad3180ad148b1f7c1c0492ed865408f75f12e11a083b|32010657", "1.0.9|linux_x86_64|f06ac64c6a14ed6a923d255788e4a5daefa2b50e35f32d7a3b5a2f9a5a91e255|32674820", "1.0.9|linux_arm64|457ac590301126e7b151ea08c5b9586a882c60039a0605fb1e44b8d23d2624fd|30510941", - "1.0.8|macos_x86_64|e2493c7ae12597d4a1e6437f6805b0a8bcaf01fc4e991d1f52f2773af3317342|33018420", - "1.0.8|macos_arm64|9f0e1366484748ecbd87c8ef69cc4d3d79296b0e2c1a108bcbbff985dbb92de8|32068918", + "1.0.8|macos_x86_64|909781ee76250cf7445f3b7d2b82c701688725fa1db3fb5543dfeed8c47b59de|33140123", + "1.0.8|macos_arm64|92fa31b93d736fab6f3d105beb502a9da908445ed942a3d46952eae88907c53e|32011344", "1.0.8|linux_x86_64|a73459d406067ce40a46f026dce610740d368c3b4a3d96591b10c7a577984c2e|32681118", "1.0.8|linux_arm64|01aaef769f4791f9b28530e750aadbc983a8eabd0d55909e26392b333a1a26e4|30515501", - "1.0.7|macos_x86_64|80ae021d6143c7f7cbf4571f65595d154561a2a25fd934b7a8ccc1ebf3014b9b|33020029", - "1.0.7|macos_arm64|cbab9aca5bc4e604565697355eed185bb699733811374761b92000cc188a7725|32071346", + "1.0.7|macos_x86_64|23b85d914465882b027d3819cc05cd114a1aaf39b550de742e81a99daa998183|33140742", + "1.0.7|macos_arm64|d9062959f28ba0f934bfe2b6e0b021e0c01a48fa065102554ca103b8274e8e0c|32012708", "1.0.7|linux_x86_64|bc79e47649e2529049a356f9e60e06b47462bf6743534a10a4c16594f443be7b|32671441", "1.0.7|linux_arm64|4e71a9e759578020750be41e945c086e387affb58568db6d259d80d123ac80d3|30529105", - "1.0.6|macos_x86_64|3a97f2fffb75ac47a320d1595e20947afc8324571a784f1bd50bd91e26d5648c|33022053", - "1.0.6|macos_arm64|aaff1eccaf4099da22fe3c6b662011f8295dad9c94a35e1557b92844610f91f3|32080428", + "1.0.6|macos_x86_64|5ac4f41d5e28f31817927f2c5766c5d9b98b68d7b342e25b22d053f9ecd5a9f1|33141677", + "1.0.6|macos_arm64|613020f90a6a5d0b98ebeb4e7cdc4b392aa06ce738fbb700159a465cd27dcbfa|32024047", "1.0.6|linux_x86_64|6a454323d252d34e928785a3b7c52bfaff1192f82685dfee4da1279bb700b733|32677516", "1.0.6|linux_arm64|2047f8afc7d0d7b645a0422181ba3fe47b3547c4fe658f95eebeb872752ec129|30514636", ]
Terraform 1.0.7 (the default) file download length is incorrect on macOS_x86_64 **Describe the bug** Title. Error message: ``` 10:08:19.28 [ERROR] 1 Exception encountered: Engine traceback: in `fmt` goal in Format with `terraform fmt` Exception: Error hashing/capturing URL fetch response: Downloaded file was larger than expected digest ``` **Pants version** 2.15 **OS** Intel MacOS **Additional info** Probably just need to rerun `build-support/bin/terraform_tool_versions.py`
So, this is wild. We generated them with originally with that script. You're right though, rerunning that script _all_ the MacOS ones have changed. Ah, it's related to their change in signing keys and certs because of [HCSEC-2023-01](https://discuss.hashicorp.com/t/hcsec-2023-01-hashicorp-response-to-circleci-security-alert/48842/1), specifically the [guidance here](https://support.hashicorp.com/hc/en-us/articles/13177506317203) > Action for customers: > After certificate revocation, users are expected to encounter errors using Apple artifacts that were downloaded before January 23rd. > Users will need to re-download Apple artifacts from the Releases Site, which have been signed using the new certificate. I guess the cert bakes a signature into the artifact or something? So it looks like just rerunning the build-support script to get the new versions is the correct course of action.
2023-05-24T17:56:12
pantsbuild/pants
19,136
pantsbuild__pants-19136
[ "18488" ]
8499390c2d97d2ca9091651c161edba11353b700
diff --git a/build-support/bin/terraform_tool_versions.py b/build-support/bin/terraform_tool_versions.py --- a/build-support/bin/terraform_tool_versions.py +++ b/build-support/bin/terraform_tool_versions.py @@ -251,7 +251,7 @@ def fetch_versions( if __name__ == "__main__": versions_url = "https://releases.hashicorp.com/terraform/" - number_of_supported_versions = 32 + number_of_supported_versions = 43 keydata = requests.get("https://keybase.io/hashicorp/pgp_keys.asc").content verifier = GPGVerifier(keydata) diff --git a/src/python/pants/backend/terraform/tool.py b/src/python/pants/backend/terraform/tool.py --- a/src/python/pants/backend/terraform/tool.py +++ b/src/python/pants/backend/terraform/tool.py @@ -26,7 +26,7 @@ class TerraformTool(TemplatedExternalTool): # TODO: Possibly there should not be a default version, since terraform state is sensitive to # the version that created it, so you have to be deliberate about the version you select. - default_version = "1.0.7" + default_version = "1.4.6" default_url_template = ( "https://releases.hashicorp.com/terraform/{version}/terraform_{version}_{platform}.zip" ) @@ -40,132 +40,176 @@ class TerraformTool(TemplatedExternalTool): @classproperty def default_known_versions(cls): return [ - "1.3.5|macos_x86_64|6bf684dbc19ecbf9225f5a2409def32e5ef7d37af3899726accd9420a88a6bcd|20848406", - "1.3.5|macos_arm64|33b25ad89dedbd98bba09cbde69dcf9e928029f322ae9494279cf2c8ce47db89|19287887", + "1.4.6|macos_x86_64|5d8332994b86411b049391d31ad1a0785dfb470db8b9c50617de28ddb5d1f25d|22051279", + "1.4.6|macos_arm64|30a2f87298ff9f299452119bd14afaa8d5b000c572f62fa64baf432e35d9dec1|20613318", + "1.4.6|linux_x86_64|e079db1a8945e39b1f8ba4e513946b3ab9f32bd5a2bdf19b9b186d22c5a3d53b|20779821", + "1.4.6|linux_arm64|b38f5db944ac4942f11ceea465a91e365b0636febd9998c110fbbe95d61c3b26|18834675", + "1.4.5|macos_x86_64|808e54d826737e9a0ca79bbe29330e50d3622bbeeb26066c63b371a291731711|22031074", + "1.4.5|macos_arm64|7104d9d13632aa61b494a349c589048d21bd550e579404c3a41c4932e4d6aa97|20592841", + "1.4.5|linux_x86_64|ce10e941cd11554b15a189cd00191c05abc20dff865599d361bdb863c5f406a9|20767621", + "1.4.5|linux_arm64|ca2c48f518f72fef668255150cc5e63b92545edc62a05939bbff8a350bceb357|18813058", + "1.4.4|macos_x86_64|0303ed9d7e5a225fc2e6fa9bf76fc6574c0c0359f22d5dfc04bc8b3234444f7c|22032187", + "1.4.4|macos_arm64|75602d9ec491982ceabea813569579b2991093a4e0d76b7ca86ffd9b7a2a1d1e|20594012", + "1.4.4|linux_x86_64|67541c1f6631befcc25b764028e5605e59234d4424e60a256518ee1e8dd50593|20767354", + "1.4.4|linux_arm64|f0b4e092f2aa6de3324e5e4b5b51260ecf5e8c2f5335ff7a2ffdc4fb54a8922d|18814310", + "1.4.3|macos_x86_64|89bdb242bfacf24167f365ef7a3bf0ad0e443ddd27ebde425fb71d77ce1a2597|22032267", + "1.4.3|macos_arm64|20b9d484bf99ada6c0de89316176ba33f7c87f64c0738991188465147bba221b|20574247", + "1.4.3|linux_x86_64|2252ee6ac8437b93db2b2ba341edc87951e2916afaeb50a88b858e80796e9111|20781685", + "1.4.3|linux_arm64|d3d9464953d390970e7f4f7cbcd94dbf63136da6fe1cbb4955d944a9315bdcdb|18814307", + "1.4.2|macos_x86_64|c218a6c0ef6692b25af16995c8c7bdf6739e9638fef9235c6aced3cd84afaf66|22030042", + "1.4.2|macos_arm64|af8ff7576c8fc41496fdf97e9199b00d8d81729a6a0e821eaf4dfd08aa763540|20588400", + "1.4.2|linux_x86_64|9f3ca33d04f5335472829d1df7785115b60176d610ae6f1583343b0a2221a931|20234129", + "1.4.2|linux_arm64|39c182670c4e63e918e0a16080b1cc47bb16e158d7da96333d682d6a9cb8eb91|18206088", + "1.4.1|macos_x86_64|96466364a7e66e3d456ecb6c85a63c83e124c004f8835fb8ea9b7bbb7542a9d0|22077050", + "1.4.1|macos_arm64|61f76e130b97c8a9017d8aaff15d252af29117e35ea1a0fc30bcaab7ceafce73|20634145", + "1.4.1|linux_x86_64|9e9f3e6752168dea8ecb3643ea9c18c65d5a52acc06c22453ebc4e3fc2d34421|20276168", + "1.4.1|linux_arm64|53322cc70b6e50ac1985bf26a78ffa2814789a4704880f071eaf3e67a463d6f6|18248378", + "1.4.0|macos_x86_64|e897a4217f1c3bfe37c694570dcc6371336fbda698790bb6b0547ec8daf1ffb3|21935694", + "1.4.0|macos_arm64|d4a1e564714c6acf848e86dc020ff182477b49f932e3f550a5d9c8f5da7636fb|20508091", + "1.4.0|linux_x86_64|5da60da508d6d1941ffa8b9216147456a16bbff6db7622ae9ad01d314cbdd188|20144407", + "1.4.0|linux_arm64|33e0f4f0b75f507fc19012111de008308df343153cd6a3992507f4566c0bb723|18130960", + "1.3.9|macos_x86_64|a73326ea8fb06f6976597e005f8047cbd55ac76ed1e517303d8f6395db6c7805|21194871", + "1.3.9|macos_arm64|d8a59a794a7f99b484a07a0ed2aa6520921d146ac5a7f4b1b806dcf5c4af0525|19793371", + "1.3.9|linux_x86_64|53048fa573effdd8f2a59b726234c6f450491fe0ded6931e9f4c6e3df6eece56|19477757", + "1.3.9|linux_arm64|da571087268c5faf884912c4239c6b9c8e1ed8e8401ab1dcb45712df70f42f1b|17513770", + "1.3.8|macos_x86_64|1a27a6fac31ecb05de610daf61a29fe83d304d7c519d773afbf56c11c3b6276b|21189878", + "1.3.8|macos_arm64|873b05ac81645cd7289d6ccfd3e73d4735af1a453f2cd19da0650bdabf7d2eb6|19780134", + "1.3.8|linux_x86_64|9d9e7d6a9b41cef8b837af688441d4fbbd84b503d24061d078ad662441c70240|19479266", + "1.3.8|linux_arm64|a42bf3c7d6327f45d2b212b692ab4229285fb44dbb8adb7c39e18be2b26167c8|17507360", + "1.3.7|macos_x86_64|eeae48adcd55212b34148ed203dd5843e9b2a84a852a9877f3386fadb0514980|21185288", + "1.3.7|macos_arm64|01d553db5f7b4cf0729b725e4402643efde5884b1dabf5eb80af328ce5e447cf|19774151", + "1.3.7|linux_x86_64|b8cf184dee15dfa89713fe56085313ab23db22e17284a9a27c0999c67ce3021e|19464102", + "1.3.7|linux_arm64|5b491c555ea8a62dda551675fd9f27d369f5cdbe87608d2a7367d3da2d38ea38|17499971", + "1.3.6|macos_x86_64|13881fe0100238577394243a90c0631783aad21b77a9a7ee830404f86c0d37bb|21183111", + "1.3.6|macos_arm64|dbff0aeeaeee877c254f5414bef5c9d186e159aa0019223aac678abad9442c53|19779986", + "1.3.6|linux_x86_64|bb44a4c2b0a832d49253b9034d8ccbd34f9feeb26eda71c665f6e7fa0861f49b|19466755", + "1.3.6|linux_arm64|f4b1af29094290f1b3935c29033c4e5291664ee2c015ca251a020dd425c847c3|17501845", + "1.3.5|macos_x86_64|e6c9836188265b20c2588e9c9d6b1727094b324a379337e68ba58a6d26be8b51|21182319", + "1.3.5|macos_arm64|fcec1cbff229fbe59b03257ba2451d5ad1f5129714f08ccf6372b2737647c063|19780547", "1.3.5|linux_x86_64|ac28037216c3bc41de2c22724e863d883320a770056969b8d211ca8af3d477cf|19469337", "1.3.5|linux_arm64|ba5b1761046b899197bbfce3ad9b448d14550106d2cc37c52a60fc6822b584ed|17502759", - "1.3.4|macos_x86_64|03e0d7f629f28e2ea31ec2c69408b500f00eac674c613f7f1097536dcfa2cf6c|20847508", - "1.3.4|macos_arm64|7b4401edd8de50cda97d76b051c3a4b1882fa5aa8e867d4c4c2770e4c3b0056e|19284666", + "1.3.4|macos_x86_64|2a75c69ec5ed8506658b266a40075256b62a7d245ff6297df7e48fa72af23879|21181585", + "1.3.4|macos_arm64|a1f740f92afac6db84421a3ec07d9061c34a32f88b4b0b47d243de16c961169f|19773343", "1.3.4|linux_x86_64|b24210f28191fa2a08efe69f54e3db2e87a63369ac4f5dcaf9f34dc9318eb1a8|19462529", "1.3.4|linux_arm64|65381c6b61b2d1a98892199f649a5764ff5a772080a73d70f8663245e6402c39|17494667", - "1.3.3|macos_x86_64|e544aefb984fd9b19de250ac063a7aa28cbfdce2eda428dd2429a521912f6a93|20843907", - "1.3.3|macos_arm64|1850df7904025b20b26ac101274f30673b132adc84686178d3d0cb802be4597e|19268812", + "1.3.3|macos_x86_64|2b3cf653cd106becdea562b6c8d3f8939641e5626c5278729cbef81678fa9f42|21163874", + "1.3.3|macos_arm64|51e94ecf88059e8a53c363a048b658230f560574f99b0d8396ebacead894d159|19755200", "1.3.3|linux_x86_64|fa5cbf4274c67f2937cabf1a6544529d35d0b8b729ce814b40d0611fd26193c1|19451941", "1.3.3|linux_arm64|b940a080c698564df5e6a2f1c4e1b51b2c70a5115358d2361e3697d3985ecbfe|17488660", - "1.3.2|macos_x86_64|edaed5a7c4057f1f2a3826922f3e594c45e24c1e22605b94de9c097b683c38bd|20843900", - "1.3.2|macos_arm64|ff92cd79b01d39a890314c2df91355c0b6d6815fbc069ccaee9da5d8b9ff8580|19270064", + "1.3.2|macos_x86_64|3639461bbc712dc130913bbe632afb449fce8c0df692429d311e7cb808601901|21163990", + "1.3.2|macos_arm64|80480acbfee2e2d0b094f721f7568a40b790603080d6612e19b797a16b8ba82d|19757201", "1.3.2|linux_x86_64|6372e02a7f04bef9dac4a7a12f4580a0ad96a37b5997e80738e070be330cb11c|19451510", "1.3.2|linux_arm64|ce1a8770aaf27736a3352c5c31e95fb10d0944729b9d81013bf6848f8657da5f|17485206", - "1.3.1|macos_x86_64|5f5967e12e75a3ca1720be3eeba8232b4ba8b42d2d9e9f9664eff7a68267e873|20842029", - "1.3.1|macos_arm64|a525488cc3a26d25c5769fb7ffcabbfcd64f79cec5ebbfc94c18b5ec74a03b35|19269260", + "1.3.1|macos_x86_64|4282ebe6d1d72ace0d93e8a4bcf9a6f3aceac107966216355bb516b1c49cc203|21161667", + "1.3.1|macos_arm64|f0514f29b08da2f39ba4fff0d7eb40093915c9c69ddc700b6f39b78275207d96|19756039", "1.3.1|linux_x86_64|0847b14917536600ba743a759401c45196bf89937b51dd863152137f32791899|19450765", "1.3.1|linux_arm64|7ebb3d1ff94017fbef8acd0193e0bd29dec1a8925e2b573c05a92fdb743d1d5b|17486534", - "1.3.0|macos_x86_64|6502dbcbd7d1a356fa446ec12c2859a9a7276af92c89ce3cef7f675a8582a152|20842934", - "1.3.0|macos_arm64|6a3512a1b1006f2edc6fe5f51add9a6e1ef3967912ecf27e66f22e70b9ad7158|19255975", + "1.3.0|macos_x86_64|80e55182d4495da867c93c25dc6ae29be83ece39d3225e6adedecd55b72d6bbf|21163947", + "1.3.0|macos_arm64|df703317b5c7f80dc7c61e46de4697c9f440e650a893623351ab5e184995b404|19741011", "1.3.0|linux_x86_64|380ca822883176af928c80e5771d1c0ac9d69b13c6d746e6202482aedde7d457|19450952", "1.3.0|linux_arm64|0a15de6f934cf2217e5055412e7600d342b4f7dcc133564690776fece6213a9a|17488551", - "1.2.9|macos_x86_64|46206e564fdd792e709b7ec70eab1c873c9b1b17f4d33c07a1faa9d68955061b|21329275", - "1.2.9|macos_arm64|e61195aa7cc5caf6c86c35b8099b4a29339cd51e54518eb020bddb35cfc0737d|19773052", + "1.2.9|macos_x86_64|84a678ece9929cebc34c7a9a1ba287c8b91820b336f4af8437af7feaa0117b7c|21672810", + "1.2.9|macos_arm64|bc3b94b53cdf1be3c4988faa61aad343f48e013928c64bfc6ebeb61657f97baa|20280541", "1.2.9|linux_x86_64|0e0fc38641addac17103122e1953a9afad764a90e74daf4ff8ceeba4e362f2fb|19906116", "1.2.9|linux_arm64|6da7bf01f5a72e61255c2d80eddeba51998e2bb1f50a6d81b0d3b71e70e18531|17946045", - "1.2.8|macos_x86_64|0f8eecc764b57a938aa115a3ce2baa0d245479f17c28a4217bcf432ee23c2c5d|21332730", - "1.2.8|macos_arm64|d6b900682d33aff84f8f63f69557f8ea8537218748fcac6f12483aaa46959a14|19770539", + "1.2.8|macos_x86_64|efd3e21a9bb1cfa68303f8d119ea8970dbb616f5f99caa0fe21d796e0cd70252|21678594", + "1.2.8|macos_arm64|2c83bfea9e1c202c449e91bee06a804afb45cb8ba64a73da48fb0f61df51b327|20277152", "1.2.8|linux_x86_64|3e9c46d6f37338e90d5018c156d89961b0ffb0f355249679593aff99f9abe2a2|19907515", "1.2.8|linux_arm64|26c05cadb05cdaa8ac64b90b982b4e9350715ec2e9995a6b03bb964d230de055|17947439", - "1.2.7|macos_x86_64|acc781e964be9b527101b00eb6e7e63e7e509dd1355ff8567b80d0244c460634|21330075", - "1.2.7|macos_arm64|e4717057e1cbb606f1e089261def9a17ddd18b78707d9e212c768dc0d739a220|19773241", + "1.2.7|macos_x86_64|74e47b54ea78685be24c84e0e17b22b56220afcdb24ec853514b3863199f01e4|21673162", + "1.2.7|macos_arm64|ec4e623914b411f8cc93a1e71396a1e7f1fe1e96bb2e532ba3e955d2ca5cc442|20278743", "1.2.7|linux_x86_64|dfd7c44a5b6832d62860a01095a15b53616fb3ea4441ab89542f9364e3fca718|19907183", "1.2.7|linux_arm64|80d064008d57ba5dc97e189215c87275bf39ca14b1234430eae2f114394ea229|17943724", - "1.2.6|macos_x86_64|94d1efad05a06c879b9c1afc8a6f7acb2532d33864225605fc766ecdd58d9888|21328767", - "1.2.6|macos_arm64|452675f91cfe955a95708697a739d9b114c39ff566da7d9b31489064ceaaf66a|19774190", + "1.2.6|macos_x86_64|d896d2776af8b06cd4acd695ad75913040ce31234f5948688fd3c3fde53b1f75|21670957", + "1.2.6|macos_arm64|c88ceb34f343a2bb86960e32925c5ec43b41922ee9ede1019c5cf7d7b4097718|20279669", "1.2.6|linux_x86_64|9fd445e7a191317dcfc99d012ab632f2cc01f12af14a44dfbaba82e0f9680365|19905977", "1.2.6|linux_arm64|322755d11f0da11169cdb234af74ada5599046c698dccc125859505f85da2a20|17943213", - "1.2.5|macos_x86_64|d196f94486e54407524a0efbcb5756b197b763863ead2e145f86dd6c80fc9ce8|21323818", - "1.2.5|macos_arm64|77dd998d26e578aa22de557dc142672307807c88e3a4da65d8442de61479899f|19767100", + "1.2.5|macos_x86_64|2520fde736b43332b0c2648f4f6dde407335f322a3085114dc4f70e6e50eadc0|21659883", + "1.2.5|macos_arm64|92ad40db4a0930bdf872d6336a7b3a18b17c6fd04d9fc769b554bf51c8add505|20266441", "1.2.5|linux_x86_64|281344ed7e2b49b3d6af300b1fe310beed8778c56f3563c4d60e5541c0978f1b|19897064", "1.2.5|linux_arm64|0544420eb29b792444014988018ae77a7c8df6b23d84983728695ba73e38f54a|17938208", - "1.2.4|macos_x86_64|3e04343620fb01b8be01c8689dcb018b8823d8d7b070346086d7df22cc4cd5e6|21321939", - "1.2.4|macos_arm64|e596dcdfe55b2070a55fcb271873e86d1af7f6b624ffad4837ccef119fdac97a|19765021", + "1.2.4|macos_x86_64|e7d2c66264a3da94854ae6ff692bbb9a1bc11c36bb5658e3ef19841388a07430|21658356", + "1.2.4|macos_arm64|c31754ff5553707ef9fd2f913b833c779ab05ce192eb14913f51816a077c6798|20263133", "1.2.4|linux_x86_64|705ea62a44a0081594dad6b2b093eefefb12d54fa5a20a66562f9e082b00414c|19895510", "1.2.4|linux_arm64|11cfa2233dc708b51b16d5b923379db67e35c22b1b988773e5b31a7c2e251471|17936883", - "1.2.3|macos_x86_64|2962b0ebdf6f431b8fb182ffc1d8b582b73945db0c3ab99230ffc360d9e297a2|21318448", - "1.2.3|macos_arm64|601962205ad3dcf9b1b75f758589890a07854506cbd08ca2fc25afbf373bff53|19757696", + "1.2.3|macos_x86_64|bdc22658463237530dc120dadb0221762d9fb9116e7a6e0dc063d8ae649c431e|21658937", + "1.2.3|macos_arm64|6f06debac2ac54951464bf490e1606f973ab53ad8ba5decea76646e8f9309512|20256836", "1.2.3|linux_x86_64|728b6fbcb288ad1b7b6590585410a98d3b7e05efe4601ef776c37e15e9a83a96|19891436", "1.2.3|linux_arm64|a48991e938a25bfe5d257f4b6cbbdc73d920cc34bbc8f0e685e28b9610ad75fe|17933271", - "1.2.2|macos_x86_64|bd224d57718ed2b6e5e3b55383878d4b122c6dc058d65625605cef1ace9dcb25|21317982", - "1.2.2|macos_arm64|4750d46e47345809a0baa3c330771c8c8a227b77bec4caa7451422a21acefae5|19758608", + "1.2.2|macos_x86_64|1d22663c1ab22ecea774ae63aee21eecfee0bbc23b953206d889a5ba3c08525a|21656824", + "1.2.2|macos_arm64|b87716b55a3b10cced60db5285bae57aee9cc0f81c555dccdc4f54f62c2a3b60|20254768", "1.2.2|linux_x86_64|2934a0e8824925beb956b2edb5fef212a6141c089d29d8568150a43f95b3a626|19889133", "1.2.2|linux_arm64|9c6202237d7477412054dcd36fdc269da9ee66ecbc45bb07d0d63b7d36af7b21|17932829", - "1.2.1|macos_x86_64|d7c9a677efb22276afdd6c7703cbfee87d509a31acb247b96aa550a35154400a|21309907", - "1.2.1|macos_arm64|96e3659e89bfb50f70d1bb8660452ec433019d00a862d2291817c831305d85ea|19751670", + "1.2.1|macos_x86_64|31c0fd4deb7c6a77c08d2fdf59c37950e6df7165088c004e1dd7f5e09fbf6307|21645582", + "1.2.1|macos_arm64|70159b3e3eb49ee71193815943d9217c59203fd4ee8c6960aeded744094a2250|20253448", "1.2.1|linux_x86_64|8cf8eb7ed2d95a4213fbfd0459ab303f890e79220196d1c4aae9ecf22547302e|19881618", "1.2.1|linux_arm64|972ea512dac822274791dedceb6e7f8b9ac2ed36bd7759269b6806d0ab049128|17922073", - "1.2.0|macos_x86_64|f608b1fee818988d89a16b7d1b6d22b37cc98892608c52c22661ca6cbfc3d216|21309982", - "1.2.0|macos_arm64|d4df7307bad8c13e443493c53898a7060f77d661bfdf06215b61b65621ed53e9|19750767", + "1.2.0|macos_x86_64|1b102ba3bf0c60ff6cbee74f721bf8105793c1107a1c6d03dcab98d7079f0c77|21645732", + "1.2.0|macos_arm64|f5e46cabe5889b60597f0e9c365cbc663e4c952c90a16c10489897c2075ae4f0|20253335", "1.2.0|linux_x86_64|b87de03adbdfdff3c2552c8c8377552d0eecd787154465100cf4e29de4a7be1f|19880608", "1.2.0|linux_arm64|ee80b8635d8fdbaed57beffe281cf87b8b1fd1ddb29c08d20e25a152d9f0f871|17920355", - "1.1.9|macos_x86_64|c902b3c12042ac1d950637c2dd72ff19139519658f69290b310f1a5924586286|20709155", - "1.1.9|macos_arm64|918a8684da5a5529285135f14b09766bd4eb0e8c6612a4db7c121174b4831739|19835808", + "1.1.9|macos_x86_64|685258b525eae94fb0b406faf661aa056d31666256bf28e625365a251cb89fdc|20850638", + "1.1.9|macos_arm64|39fac4be74462be86b2290dd09fe1092f73dfb48e2df92406af0e199cfa6a16c|20093184", "1.1.9|linux_x86_64|9d2d8a89f5cc8bc1c06cb6f34ce76ec4b99184b07eb776f8b39183b513d7798a|19262029", "1.1.9|linux_arm64|e8a09d1fe5a68ed75e5fabe26c609ad12a7e459002dea6543f1084993b87a266|17521011", - "1.1.8|macos_x86_64|29ad0af72d498a76bbc51cc5cb09a6d6d0e5673cbbab6ef7aca57e3c3e780f46|20216382", - "1.1.8|macos_arm64|d6fefdc27396a019da56cce26f7eeea3d6986714cbdd488ff6a424f4bca40de8|19371647", + "1.1.8|macos_x86_64|48f1f1e04d0aa8f5f1a661de95e3c2b8fd8ab16b3d44015372aff7693d36c2cf|20354970", + "1.1.8|macos_arm64|943e1948c4eae82cf8b490bb274939fe666252bbc146f098e7da65b23416264a|19631574", "1.1.8|linux_x86_64|fbd37c1ec3d163f493075aa0fa85147e7e3f88dd98760ee7af7499783454f4c5|18796132", "1.1.8|linux_arm64|10b2c063dcff91329ee44bce9d71872825566b713308b3da1e5768c6998fb84f|17107405", - "1.1.7|macos_x86_64|5e7e939e084ae29af7fd86b00a618433d905477c52add2d4ea8770692acbceac|20213394", - "1.1.7|macos_arm64|a36b6e2810f81a404c11005942b69c3d1d9baa8dd07de6b1f84e87a67eedb58f|19371095", + "1.1.7|macos_x86_64|6e56eea328683541f6de0d5f449251a974d173e6d8161530956a20d9c239731a|20351873", + "1.1.7|macos_arm64|8919ceee34f6bfb16a6e9ff61c95f4043c35c6d70b21de27e5a153c19c7eba9c|19625836", "1.1.7|linux_x86_64|e4add092a54ff6febd3325d1e0c109c9e590dc6c38f8bb7f9632e4e6bcca99d4|18795309", "1.1.7|linux_arm64|2f72982008c52d2d57294ea50794d7c6ae45d2948e08598bfec3e492bce8d96e|17109768", - "1.1.6|macos_x86_64|bbfc916117e45788661c066ec39a0727f64c7557bf6ce9f486bbd97c16841975|20168574", - "1.1.6|macos_arm64|dddb11195fc413653b98e7a830ec7314f297e6c22575fc878f4ee2287a25b4f5|19326402", + "1.1.6|macos_x86_64|7a499c1f08d89548ae4c0e829eea43845fa1bd7b464e7df46102b35e6081fe44|20303856", + "1.1.6|macos_arm64|f06a14fdb610ec5a7f18bdbb2f67187230eb418329756732d970b6ca3dae12c3|19577273", "1.1.6|linux_x86_64|3e330ce4c8c0434cdd79fe04ed6f6e28e72db44c47ae50d01c342c8a2b05d331|18751464", "1.1.6|linux_arm64|a53fb63625af3572f7252b9fb61d787ab153132a8984b12f4bb84b8ee408ec53|17069580", - "1.1.5|macos_x86_64|7d4dbd76329c25869e407706fed01213beb9d6235c26e01c795a141c2065d053|20157551", - "1.1.5|macos_arm64|723363af9524c0897e9a7d871d27f0d96f6aafd11990df7e6348f5b45d2dbe2c|19328643", + "1.1.5|macos_x86_64|dcf7133ebf61d195e432ddcb70e604bf45056163d960e991881efbecdbd7892b|20300006", + "1.1.5|macos_arm64|6e5a8d22343722dc8bfcf1d2fd7b742f5b46287f87171e8143fc9b87db32c3d4|19581167", "1.1.5|linux_x86_64|30942d5055c7151f051c8ea75481ff1dc95b2c4409dbb50196419c21168d6467|18748879", "1.1.5|linux_arm64|2fb6324c24c14523ae63cedcbc94a8e6c1c317987eced0abfca2f6218d217ca5|17069683", - "1.1.4|macos_x86_64|c2b2500835d2eb9d614f50f6f74c08781f0fee803699279b3eb0188b656427f2|20098620", - "1.1.4|macos_arm64|a753e6cf402beddc4043a3968ff3e790cf50cc526827cda83a0f442a893f2235|19248286", + "1.1.4|macos_x86_64|4f3bc78fedd4aa17f67acc0db4eafdb6d70ba72392aaba65fe72855520f11f3d|20242050", + "1.1.4|macos_arm64|5642b46e9c7fb692f05eba998cd4065fb2e48aa8b0aac9d2a116472fbabe34a1|19498408", "1.1.4|linux_x86_64|fca028d622f82788fdc35c1349e78d69ff07c7bb68c27d12f8b48c420e3ecdfb|18695508", "1.1.4|linux_arm64|3c1982cf0d16276c82960db60c998d79ba19e413af4fa2c7f6f86e4994379437|16996040", - "1.1.3|macos_x86_64|c54022e514a97e9b96dae24a3308227d034989ecbafb65e3293eea91f2d5edfb|20098660", - "1.1.3|macos_arm64|856e435da081d0a214c47a4eb09b1842f35eaa55e7ef0f9fa715d4816981d640|19244516", + "1.1.3|macos_x86_64|016bab760c96d4e64d2140a5f25c614ccc13c3fe9b3889e70c564bd02099259f|20241648", + "1.1.3|macos_arm64|02ba769bb0a8d4bc50ff60989b0f201ce54fd2afac2fb3544a0791aca5d3f6d5|19493636", "1.1.3|linux_x86_64|b215de2a18947fff41803716b1829a3c462c4f009b687c2cbdb52ceb51157c2f|18692580", "1.1.3|linux_arm64|ad5a1f2c132bedc5105e3f9900e4fe46858d582c0f2a2d74355da718bbcef65d|16996972", - "1.1.2|macos_x86_64|214da2e97f95389ba7557b8fcb11fe05a23d877e0fd67cd97fcbc160560078f1|20098558", - "1.1.2|macos_arm64|39e28f49a753c99b5e2cb30ac8146fb6b48da319c9db9d152b1e8a05ec9d4a13|19240921", + "1.1.2|macos_x86_64|78faa76db5dc0ecfe4bf7c6368dbf5cca019a806f9d203580a24a4e0f8cd8353|20240584", + "1.1.2|macos_arm64|cc3bd03b72db6247c9105edfeb9c8f674cf603e08259075143ffad66f5c25a07|19486800", "1.1.2|linux_x86_64|734efa82e2d0d3df8f239ce17f7370dabd38e535d21e64d35c73e45f35dfa95c|18687805", "1.1.2|linux_arm64|088e2226d1ddb7f68a4f65c704022a1cfdbf20fe40f02e0c3646942f211fd746|16994702", - "1.1.1|macos_x86_64|85fa7c90359c4e3358f78e58f35897b3e466d00c0d0648820830cac5a07609c3|20094218", - "1.1.1|macos_arm64|9cd8faf29095c57e30f04f9ca5fa9105f6717b277c65061a46f74f22f0f5907e|19240711", + "1.1.1|macos_x86_64|d125dd2e92b9245f2202199b52f234035f36bdcbcd9a06f08e647e14a9d9067a|20237718", + "1.1.1|macos_arm64|4cb6e5eb4f6036924caf934c509a1dfd61cd2c651bb3ee8fbfe2e2914dd9ed17|19488315", "1.1.1|linux_x86_64|07b8dc444540918597a60db9351af861335c3941f28ea8774e168db97dd74557|18687006", "1.1.1|linux_arm64|d6fd14da47af9ec5fa3ad5962eaef8eed6ff2f8a5041671f9c90ec5f4f8bb554|16995635", - "1.1.0|macos_x86_64|6fb2af160879d807291980642efa93cc9a97ddf662b17cc3753065c974a5296d|20089311", - "1.1.0|macos_arm64|f69e0613f09c21d44ce2131b20e8b97909f3fc7aa90c443639475f5e474a22ec|19240009", + "1.1.0|macos_x86_64|6e0ba9afb8795a544e70dc0459f0095fea7df15e38f5d88a7dd3f620d50f8bfe|20226329", + "1.1.0|macos_arm64|7955e173c7eadb87123fc0633c3ee67d5ba3b7d6c7f485fe803efed9f99dce54|19491369", "1.1.0|linux_x86_64|763378aa75500ce5ba67d0cba8aa605670cd28bf8bafc709333a30908441acb5|18683106", "1.1.0|linux_arm64|6697e9a263e264310373f3c91bf83f4cbfeb67b13994d2a8f7bcc492b554552e|16987201", - "1.0.11|macos_x86_64|92f2e7eebb9699e23800f8accd519775a02bd25fe79e1fe4530eca123f178202|19340098", - "1.0.11|macos_arm64|0f38af81641b00a2cbb8d25015d917887a7b62792c74c28d59e40e56ce6f265c|18498208", + "1.0.11|macos_x86_64|551a16b612edaae1037925d0e2dba30d16504ff4bd66606955172c2ed8d76131|19422757", + "1.0.11|macos_arm64|737e1765afbadb3d76e1929d4b4af8da55010839aa08e9e730d46791eb8ea5a6|18467868", "1.0.11|linux_x86_64|eeb46091a42dc303c3a3c300640c7774ab25cbee5083dafa5fd83b54c8aca664|18082446", "1.0.11|linux_arm64|30c650f4bc218659d43e07d911c00f08e420664a3d12c812228e66f666758645|16148492", - "1.0.10|macos_x86_64|e7595530a0dcdaec757621cbd9f931926fd904b1a1e5206bf2c9db6b73cee04d|33021017", - "1.0.10|macos_arm64|eecea1343888e2648d5f7ea25a29494fd3b5ecde95d0231024414458c59cb184|32073869", + "1.0.10|macos_x86_64|077479e98701bc9be88db21abeec684286fd85a3463ce437d7739d2a4e372f18|33140832", + "1.0.10|macos_arm64|776f2e144039ece66ae326ebda0884254848a2e11f0590757d02e3a74f058c81|32013985", "1.0.10|linux_x86_64|a221682fcc9cbd7fde22f305ead99b3ad49d8303f152e118edda086a2807716d|32674953", "1.0.10|linux_arm64|b091dbe5c00785ae8b5cb64149d697d61adea75e495d9e3d910f61d8c9967226|30505040", - "1.0.9|macos_x86_64|fb791c3efa323c5f0c2c36d14b9230deb1dc37f096a8159e718e8a9efa49a879|33017665", - "1.0.9|macos_arm64|aa5cc13903be35236a60d116f593e519534bcabbb2cf91b69cae19307a17b3c0|32069384", + "1.0.9|macos_x86_64|be122ff7fb925643c5ebf4e5704b18426e18d3ca49ab59ae33d208c908cb6d5a|33140006", + "1.0.9|macos_arm64|89b2b4fd1a0c57fabc08ad3180ad148b1f7c1c0492ed865408f75f12e11a083b|32010657", "1.0.9|linux_x86_64|f06ac64c6a14ed6a923d255788e4a5daefa2b50e35f32d7a3b5a2f9a5a91e255|32674820", "1.0.9|linux_arm64|457ac590301126e7b151ea08c5b9586a882c60039a0605fb1e44b8d23d2624fd|30510941", - "1.0.8|macos_x86_64|e2493c7ae12597d4a1e6437f6805b0a8bcaf01fc4e991d1f52f2773af3317342|33018420", - "1.0.8|macos_arm64|9f0e1366484748ecbd87c8ef69cc4d3d79296b0e2c1a108bcbbff985dbb92de8|32068918", + "1.0.8|macos_x86_64|909781ee76250cf7445f3b7d2b82c701688725fa1db3fb5543dfeed8c47b59de|33140123", + "1.0.8|macos_arm64|92fa31b93d736fab6f3d105beb502a9da908445ed942a3d46952eae88907c53e|32011344", "1.0.8|linux_x86_64|a73459d406067ce40a46f026dce610740d368c3b4a3d96591b10c7a577984c2e|32681118", "1.0.8|linux_arm64|01aaef769f4791f9b28530e750aadbc983a8eabd0d55909e26392b333a1a26e4|30515501", - "1.0.7|macos_x86_64|80ae021d6143c7f7cbf4571f65595d154561a2a25fd934b7a8ccc1ebf3014b9b|33020029", - "1.0.7|macos_arm64|cbab9aca5bc4e604565697355eed185bb699733811374761b92000cc188a7725|32071346", + "1.0.7|macos_x86_64|23b85d914465882b027d3819cc05cd114a1aaf39b550de742e81a99daa998183|33140742", + "1.0.7|macos_arm64|d9062959f28ba0f934bfe2b6e0b021e0c01a48fa065102554ca103b8274e8e0c|32012708", "1.0.7|linux_x86_64|bc79e47649e2529049a356f9e60e06b47462bf6743534a10a4c16594f443be7b|32671441", "1.0.7|linux_arm64|4e71a9e759578020750be41e945c086e387affb58568db6d259d80d123ac80d3|30529105", - "1.0.6|macos_x86_64|3a97f2fffb75ac47a320d1595e20947afc8324571a784f1bd50bd91e26d5648c|33022053", - "1.0.6|macos_arm64|aaff1eccaf4099da22fe3c6b662011f8295dad9c94a35e1557b92844610f91f3|32080428", + "1.0.6|macos_x86_64|5ac4f41d5e28f31817927f2c5766c5d9b98b68d7b342e25b22d053f9ecd5a9f1|33141677", + "1.0.6|macos_arm64|613020f90a6a5d0b98ebeb4e7cdc4b392aa06ce738fbb700159a465cd27dcbfa|32024047", "1.0.6|linux_x86_64|6a454323d252d34e928785a3b7c52bfaff1192f82685dfee4da1279bb700b733|32677516", "1.0.6|linux_arm64|2047f8afc7d0d7b645a0422181ba3fe47b3547c4fe658f95eebeb872752ec129|30514636", ]
Terraform 1.0.7 (the default) file download length is incorrect on macOS_x86_64 **Describe the bug** Title. Error message: ``` 10:08:19.28 [ERROR] 1 Exception encountered: Engine traceback: in `fmt` goal in Format with `terraform fmt` Exception: Error hashing/capturing URL fetch response: Downloaded file was larger than expected digest ``` **Pants version** 2.15 **OS** Intel MacOS **Additional info** Probably just need to rerun `build-support/bin/terraform_tool_versions.py`
So, this is wild. We generated them with originally with that script. You're right though, rerunning that script _all_ the MacOS ones have changed. Ah, it's related to their change in signing keys and certs because of [HCSEC-2023-01](https://discuss.hashicorp.com/t/hcsec-2023-01-hashicorp-response-to-circleci-security-alert/48842/1), specifically the [guidance here](https://support.hashicorp.com/hc/en-us/articles/13177506317203) > Action for customers: > After certificate revocation, users are expected to encounter errors using Apple artifacts that were downloaded before January 23rd. > Users will need to re-download Apple artifacts from the Releases Site, which have been signed using the new certificate. I guess the cert bakes a signature into the artifact or something? So it looks like just rerunning the build-support script to get the new versions is the correct course of action.
2023-05-24T17:56:21
pantsbuild/pants
19,149
pantsbuild__pants-19149
[ "12430" ]
a963b6dc701aa28ee0532acf0b8a187c0b485d8b
diff --git a/src/python/pants/backend/python/util_rules/package_dists.py b/src/python/pants/backend/python/util_rules/package_dists.py --- a/src/python/pants/backend/python/util_rules/package_dists.py +++ b/src/python/pants/backend/python/util_rules/package_dists.py @@ -105,7 +105,7 @@ class TargetNotExported(SetupPyError): """Indicates a target that was expected to be exported is not.""" -class InvalidEntryPoint(SetupPyError): +class InvalidEntryPoint(SetupPyError, InvalidFieldException): """Indicates that a specified binary entry point was invalid."""
The `InvalidEntryPoint` should subclass `InvalidFieldException` That sounds good to have `InvalidEntryPoint` subclass `InvalidFieldException`, definitely. And makes sense if you want to do in a followup to keep this PR better scoped. _Originally posted by @Eric-Arellano in https://github.com/pantsbuild/pants/pull/12414#discussion_r677074818_
2023-05-25T05:18:26
pantsbuild/pants
19,155
pantsbuild__pants-19155
[ "15855", "15855" ]
361a665a8b2ec471dec82907f63e0f9d40d7ccca
diff --git a/src/python/pants/backend/python/util_rules/pex_from_targets.py b/src/python/pants/backend/python/util_rules/pex_from_targets.py --- a/src/python/pants/backend/python/util_rules/pex_from_targets.py +++ b/src/python/pants/backend/python/util_rules/pex_from_targets.py @@ -46,6 +46,7 @@ ) from pants.backend.python.util_rules.python_sources import rules as python_sources_rules from pants.core.goals.generate_lockfiles import NoCompatibleResolveException +from pants.core.goals.package import TraverseIfNotPackageTarget from pants.core.target_types import FileSourceField from pants.engine.addresses import Address, Addresses from pants.engine.collection import DeduplicatedCollection @@ -538,7 +539,14 @@ async def create_pex_from_targets( sources_digests.append(request.additional_sources) if request.include_source_files: transitive_targets = await Get( - TransitiveTargets, TransitiveTargetsRequest(request.addresses) + TransitiveTargets, + TransitiveTargetsRequest( + request.addresses, + should_traverse_deps_predicate=TraverseIfNotPackageTarget( + roots=request.addresses, + union_membership=union_membership, + ), + ), ) sources = await Get(PythonSourceFiles, PythonSourceFilesRequest(transitive_targets.closure))
diff --git a/src/python/pants/backend/python/util_rules/pex_from_targets_test.py b/src/python/pants/backend/python/util_rules/pex_from_targets_test.py --- a/src/python/pants/backend/python/util_rules/pex_from_targets_test.py +++ b/src/python/pants/backend/python/util_rules/pex_from_targets_test.py @@ -16,10 +16,12 @@ import pytest from pants.backend.python import target_types_rules +from pants.backend.python.goals import package_pex_binary from pants.backend.python.subsystems import setuptools from pants.backend.python.subsystems.setup import PythonSetup from pants.backend.python.target_types import ( EntryPoint, + PexBinary, PexLayout, PythonRequirementTarget, PythonSourcesGeneratorTarget, @@ -70,6 +72,7 @@ def rule_runner() -> PythonRuleRunner: return PythonRuleRunner( rules=[ + *package_pex_binary.rules(), *pex_test_utils.rules(), *pex_from_targets.rules(), *target_types_rules.rules(), @@ -80,6 +83,7 @@ def rule_runner() -> PythonRuleRunner: *setuptools.rules(), ], target_types=[ + PexBinary, PythonSourcesGeneratorTarget, PythonRequirementTarget, PythonSourceTarget, @@ -759,6 +763,52 @@ def test_exclude_sources(include_sources: bool, rule_runner: PythonRuleRunner) - assert len(snapshot.files) == (1 if include_sources else 0) +def test_include_sources_without_transitive_package_sources(rule_runner: PythonRuleRunner) -> None: + rule_runner.write_files( + { + "src/app/BUILD": dedent( + """ + python_sources( + name="app", + sources=["app.py"], + dependencies=["//src/dep:pkg"], + ) + """ + ), + "src/app/app.py": "", + "src/dep/BUILD": dedent( + # This test requires a package that has a standard dependencies field. + # 'pex_binary' has a dependencies field; 'archive' does not. + """ + pex_binary(name="pkg", dependencies=[":dep"]) + python_sources(name="dep", sources=["dep.py"]) + """ + ), + "src/dep/dep.py": "", + } + ) + + rule_runner.set_options( + [ + "--backend-packages=pants.backend.python", + "--python-repos-indexes=[]", + ], + env_inherit={"PATH"}, + ) + + request = PexFromTargetsRequest( + [Address("src/app", target_name="app")], + output_filename="demo.pex", + internal_only=True, + include_source_files=True, + ) + pex_request = rule_runner.request(PexRequest, [request]) + snapshot = rule_runner.request(Snapshot, [pex_request.sources]) + + # the packaged transitive dep is excluded + assert snapshot.files == ("app/app.py",) + + @pytest.mark.parametrize("enable_resolves", [False, True]) def test_cross_platform_pex_disables_subsetting( rule_runner: PythonRuleRunner, enable_resolves: bool
`pex_binary` depending on `python_distribution` is consuming transitive deps **Describe the bug** The following repo can be used to reproduce the issue: https://github.com/dimitar-petrov/pants_merge_debug Included is a docker-compose.yml file to be able to set up the environment independently of OS used. ``` ./pants package py/apps/pyapp:venv 14:27:39.91 [ERROR] 1 Exception encountered: Exception: Can only merge Directories with no duplicates, but found 2 duplicate entries in : `MANIFEST.in`: 1.) file digest=64958bd91c39a06f78542a71383436bbf0c798138e4fe46780c8d9c08aa91278 size=179: include README.org LICENSE VERSION include pybind/cnufft/cnufft.c include pybind/cnufft/cnufft.h include pybind/cnufft/libcnufft.so include pybind/cnufft/libfnufft.so prune *.pyc `MANIFEST.in`: 2.) file digest=892591bf1e4c7e1337cfd470096a467805fa2cb6f46b792fe6e3a6a8b0a72e0a size=366: include README.rst include setup.py include nufft/__init__.py include nufft/nufft.py include nufft/nufft.pyf include src/nufft/dfftpack.f include src/nufft/dirft1d.f include src/nufft/dirft2d.f include src/nufft/dirft3d.f include src/nufft/next235.f include src/nufft/nufft1df90.f include src/nufft/nufft2df90.f include src/nufft/nufft3df90.f include pyproject.toml ``` **Pants version** pants_version = "2.12.0rc1" **OS** Linux Issue opened after discussion on slack with: @benjyw, @kaos, @thejcannon `pex_binary` depending on `python_distribution` is consuming transitive deps **Describe the bug** The following repo can be used to reproduce the issue: https://github.com/dimitar-petrov/pants_merge_debug Included is a docker-compose.yml file to be able to set up the environment independently of OS used. ``` ./pants package py/apps/pyapp:venv 14:27:39.91 [ERROR] 1 Exception encountered: Exception: Can only merge Directories with no duplicates, but found 2 duplicate entries in : `MANIFEST.in`: 1.) file digest=64958bd91c39a06f78542a71383436bbf0c798138e4fe46780c8d9c08aa91278 size=179: include README.org LICENSE VERSION include pybind/cnufft/cnufft.c include pybind/cnufft/cnufft.h include pybind/cnufft/libcnufft.so include pybind/cnufft/libfnufft.so prune *.pyc `MANIFEST.in`: 2.) file digest=892591bf1e4c7e1337cfd470096a467805fa2cb6f46b792fe6e3a6a8b0a72e0a size=366: include README.rst include setup.py include nufft/__init__.py include nufft/nufft.py include nufft/nufft.pyf include src/nufft/dfftpack.f include src/nufft/dirft1d.f include src/nufft/dirft2d.f include src/nufft/dirft3d.f include src/nufft/next235.f include src/nufft/nufft1df90.f include src/nufft/nufft2df90.f include src/nufft/nufft3df90.f include pyproject.toml ``` **Pants version** pants_version = "2.12.0rc1" **OS** Linux Issue opened after discussion on slack with: @benjyw, @kaos, @thejcannon
FYI changed the title to reflect the bug The workaround is to use transitive dep excludes, e.g., ``` pex_binary( name="venv", dependencies=[ "py/libs/nufft:nufft_dist", "py/libs/pybind:pybind_dist", "!!py/libs/nufft/MANIFEST.in:nufft_files", "!!py/libs/nufft/README.rst:nufft_files", "!!py/libs/nufft/pyproject.toml:pyproject", "!!py/libs/nufft/setup.py:nufft0", "!!py/libs/pybind/MANIFEST.in:pybind_files", "!!py/libs/pybind/README.rst:pybind_files", "!!py/libs/pybind/pyproject.toml:pyproject", "!!py/libs/pybind/setup.py:pybind0", ] ) ``` (technically you only need to exclude n-1 for an n-way collision, but might as well be symmetric) Obviously this is very unsatisying, but will work until we can fix more effectively. FYI changed the title to reflect the bug The workaround is to use transitive dep excludes, e.g., ``` pex_binary( name="venv", dependencies=[ "py/libs/nufft:nufft_dist", "py/libs/pybind:pybind_dist", "!!py/libs/nufft/MANIFEST.in:nufft_files", "!!py/libs/nufft/README.rst:nufft_files", "!!py/libs/nufft/pyproject.toml:pyproject", "!!py/libs/nufft/setup.py:nufft0", "!!py/libs/pybind/MANIFEST.in:pybind_files", "!!py/libs/pybind/README.rst:pybind_files", "!!py/libs/pybind/pyproject.toml:pyproject", "!!py/libs/pybind/setup.py:pybind0", ] ) ``` (technically you only need to exclude n-1 for an n-way collision, but might as well be symmetric) Obviously this is very unsatisying, but will work until we can fix more effectively.
2023-05-25T17:39:35
pantsbuild/pants
19,161
pantsbuild__pants-19161
[ "249" ]
6cbdd071dae6bb2d372322bff79ce7c4a8c872e2
diff --git a/src/python/pants_release/generate_github_workflows.py b/src/python/pants_release/generate_github_workflows.py --- a/src/python/pants_release/generate_github_workflows.py +++ b/src/python/pants_release/generate_github_workflows.py @@ -5,7 +5,8 @@ import argparse import os -from dataclasses import dataclass +import re +from dataclasses import dataclass, field from enum import Enum from pathlib import Path from textwrap import dedent # noqa: PNT20 @@ -167,7 +168,11 @@ def ensure_category_label() -> Sequence[Step]: def checkout( - *, fetch_depth: int = 10, containerized: bool = False, ref: str | None = None + *, + fetch_depth: int = 10, + containerized: bool = False, + ref: str | None = None, + **extra_opts: object, ) -> Sequence[Step]: """Get prior commits and the commit message.""" fetch_depth_opt: dict[str, Any] = {"fetch-depth": fetch_depth} @@ -181,6 +186,7 @@ def checkout( "with": { **fetch_depth_opt, **({"ref": ref} if ref else {}), + **extra_opts, }, }, ] @@ -275,6 +281,22 @@ def install_rustup() -> Step: } +def install_python(version: str) -> Step: + return { + "name": f"Set up Python {version}", + "uses": "actions/setup-python@v4", + "with": {"python-version": version}, + } + + +def install_node(version: str) -> Step: + return { + "name": f"Set up Node {version}", + "uses": "actions/setup-node@v3", + "with": {"node-version": version}, + } + + def install_jdk() -> Step: return { "name": "Install AdoptJDK", @@ -467,13 +489,7 @@ def setup_primary_python(self) -> Sequence[Step]: # We pre-install Python on our self-hosted platforms. # We must set it up on Github-hosted platforms. if self.platform in GITHUB_HOSTED: - ret.append( - { - "name": f"Set up Python {PYTHON_VERSION}", - "uses": "actions/setup-python@v4", - "with": {"python-version": PYTHON_VERSION}, - } - ) + ret.append(install_python(PYTHON_VERSION)) return ret def expose_all_pythons(self) -> Sequence[Step]: @@ -913,6 +929,7 @@ class WorkflowInput: name: str type_str: str default: str | int | None = None + description: None | str = None def workflow_dispatch_inputs( @@ -923,6 +940,7 @@ def workflow_dispatch_inputs( wi.name.lower(): { "required": (wi.default is None), "type": wi.type_str, + **({} if wi.description is None else {"description": wi.description}), **({} if wi.default is None else {"default": wi.default}), } for wi in workflow_inputs @@ -1101,6 +1119,293 @@ def release_jobs_and_inputs() -> tuple[Jobs, dict[str, Any]]: return jobs, inputs +class DefaultGoals(str, Enum): + tailor_update_build_files = "tailor --check update-build-files --check ::" + lint_check = "lint check ::" + test = "test ::" + package = "package ::" + + +@dataclass +class Repo: + """A specification for an external public repository to run pants' testing against. + + Each repository is tested in two configurations: + + 1. using the repository's default configuration (pants version, no additional settings), as a baseline + + 2. overriding the pants version and potentially setting additional `PANTS_...` environment + variable settings (both specified as workflow inputs) + + The second is the interesting test, to validate whether a particular version/configuration of + Pants runs against this repository. The first/baseline is to make it obvious if the behaviour + _changes_, to avoid trying to analyse problems that already exist upstream. + """ + + name: str + """ + `user/repo`, referring to `https://github.com/user/repo`. (This can be expanded to other services, if required.) + """ + + python_version: str = "3.10" + """ + The Python version to install system-wide for user code to use. + """ + + env: dict[str, str] = field(default_factory=dict) + """ + Any extra environment variables to provide to all pants steps + """ + + install_go: bool = False + """ + Whether to install Go system-wide + """ + + install_thrift: bool = False + """ + Whether to install Thrift system-wide + """ + + node_version: None | str = None + """ + Whether to install Node/NPM system-wide, and which version if so + """ + + checkout_options: dict[str, Any] = field(default_factory=dict) + """ + Any additional options to provide to actions/checkout + """ + + setup_commands: str = "" + """ + Any additional set-up commands to run before pants (e.g. `sudo apt install ...`) + """ + + goals: Sequence[str] = tuple(DefaultGoals) + """ + Which pants goals to run, e.g. `goals=["test some/dir::"]` would only run `pants test some/dir::` + """ + + +PUBLIC_REPOS = [ + # pants' examples + Repo( + name="pantsbuild/example-adhoc", + node_version="20", + goals=[ + # TODO: https://github.com/pantsbuild/pants/issues/14492 means pants can't find the + # `setup-node`-installed node, so we have to exclude `package ::` + DefaultGoals.lint_check, + DefaultGoals.test, + ], + ), + Repo(name="pantsbuild/example-codegen", install_thrift=True), + Repo(name="pantsbuild/example-django", python_version="3.9"), + Repo( + name="pantsbuild/example-docker", + python_version="3.8", + env={"DYNAMIC_TAG": "dynamic-tag-here"}, + ), + Repo(name="pantsbuild/example-golang", install_go=True), + Repo(name="pantsbuild/example-jvm"), + Repo(name="pantsbuild/example-kotlin"), + Repo(name="pantsbuild/example-python", python_version="3.9"), + Repo( + name="pantsbuild/example-visibility", + python_version="3.9", + # skip check + goals=[DefaultGoals.tailor_update_build_files, "lint ::", DefaultGoals.test], + ), + # public repos + Repo(name="Ars-Linguistica/mlconjug3", goals=[DefaultGoals.package]), + Repo( + name="fucina/treb", + env={"GIT_COMMIT": "abcdef1234567890"}, + goals=[ + DefaultGoals.lint_check, + DefaultGoals.test, + DefaultGoals.package, + ], + ), + Repo( + name="ghandic/jsf", + goals=[ + DefaultGoals.test, + DefaultGoals.package, + ], + ), + Repo(name="komprenilo/liga", python_version="3.9", goals=[DefaultGoals.package]), + Repo( + name="lablup/backend.ai", + python_version="3.11.3", + setup_commands="mkdir .tmp", + goals=[ + DefaultGoals.tailor_update_build_files, + DefaultGoals.lint_check, + "test :: -tests/agent/docker:: -tests/client/integration:: -tests/common/redis::", + DefaultGoals.package, + ], + ), + Repo(name="mitodl/ol-infrastructure", goals=[DefaultGoals.package]), + Repo( + name="mitodl/ol-django", + setup_commands="sudo apt-get install pkg-config libxml2-dev libxmlsec1-dev libxmlsec1-openssl", + goals=[DefaultGoals.package], + ), + Repo( + name="naccdata/flywheel-gear-extensions", + goals=[DefaultGoals.test, "package :: -directory_pull::"], + ), + Repo(name="OpenSaMD/OpenSaMD", python_version="3.9.15"), + Repo( + name="StackStorm/st2", + python_version="3.8", + checkout_options={"submodules": "recursive"}, + setup_commands=dedent( + # https://docs.stackstorm.com/development/sources.html + # TODO: install mongo like this doesn't work, see https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/ + """ + sudo apt-get install gcc git make screen libffi-dev libssl-dev python3.8-dev libldap2-dev libsasl2-dev + # sudo apt-get install mongodb mongodb-server + sudo apt-get install rabbitmq-server + """ + ), + goals=[ + DefaultGoals.tailor_update_build_files, + DefaultGoals.lint_check, + # TODO: seems like only st2client tests don't depend on mongo + "test st2client::", + DefaultGoals.package, + ], + ), +] + + +@dataclass +class PublicReposOutput: + jobs: Jobs + inputs: dict[str, Any] + run_name: str + + +def public_repos() -> PublicReposOutput: + """Run tests against public repositories, to validate new versions of Pants. + + See `Repo` for more details. + """ + inputs, env = workflow_dispatch_inputs( + [ + WorkflowInput( + "PANTS_VERSION", + "string", + description="Pants version (for example, `2.16.0`, `2.18.0.dev1`)", + ), + # extra environment variables to pass when running the version under test, + # e.g. `PANTS_SOME_SUBSYSTEM_SOME_SETTING=abc`. NB. we use it in a way that's vulnerable to + # shell injection (there's no validation that it uses A=1 B=2 syntax, it can easily contain + # more commands), but this whole workflow is "run untrusted code as a service", so Pants + # maintainers injecting things is the least of our worries + WorkflowInput( + "EXTRA_ENV", + "string", + default="", + description="Extra environment variables (for example: `PANTS_FOO_BAR=1 PANTS_BAZ_QUX=abc`)", + ), + ] + ) + + def sanitize_name(name: str) -> str: + # IDs may only contain alphanumeric characters, '_', and '-'. + return re.sub("[^A-Za-z0-9_-]+", "_", name) + + def test_job(repo: Repo) -> object: + def gen_goals(use_default_version: bool) -> Sequence[object]: + if use_default_version: + name = "repo-default version (baseline)" + version = "" + env_prefix = "" + else: + name = version = env["PANTS_VERSION"] + env_prefix = env["EXTRA_ENV"] + + return [ + { + "name": f"Run `{goal}` with {name}", + # injecting the input string as just prefices is easier than turning it into + # arguments for `env` + "run": f"{env_prefix} pants {goal}", + # run all the goals, even if there's an earlier failure, because later goals + # might still be interesting (e.g. still run `test` even if `lint` fails) + "if": "success() || failure()", + "env": {"PANTS_VERSION": version}, + } + for goal in ["version", *repo.goals] + ] + + job_env: dict[str, str] = { + **repo.env, + "PANTS_REMOTE_CACHE_READ": "false", + "PANTS_REMOTE_CACHE_WRITE": "false", + } + return { + "name": repo.name, + "runs-on": "ubuntu-latest", + "env": job_env, + # we're running untrusted code, so this token shouldn't be able to do anything. We also + # need to be sure we don't add any secrets to the job + "permissions": {}, + "steps": [ + *checkout(repository=repo.name, **repo.checkout_options), + install_python(repo.python_version), + *([install_go()] if repo.install_go else []), + *([install_node(repo.node_version)] if repo.node_version else []), + *([download_apache_thrift()] if repo.install_thrift else []), + { + "name": "Pants on", + "run": dedent( + # FIXME: save the script somewhere + """ + curl --proto '=https' --tlsv1.2 -fsSL https://static.pantsbuild.org/setup/get-pants.sh | bash - + echo "$HOME/bin" | tee -a $GITHUB_PATH + """ + ), + }, + { + # the pants.ci.toml convention is strong, so check for it dynamically rather + # than force each repo to mark it specifically + "name": "Check for pants.ci.toml", + "run": dedent( + """ + if [[ -f pants.ci.toml ]]; then + echo "PANTS_CONFIG_FILES=pants.ci.toml" | tee -a $GITHUB_ENV + fi + """ + ), + }, + *( + [{"name": "Run set-up", "run": repo.setup_commands}] + if repo.setup_commands + else [] + ), + # first run with the repo's base configuration, as a reference point + *gen_goals(use_default_version=True), + # FIXME: scie-pants issue + { + "name": "Kill pantsd", + "run": "pkill -f pantsd", + "if": "success() || failure()", + }, + # then run with the version under test (simulates an in-place upgrade, locally, too) + *gen_goals(use_default_version=False), + ], + } + + jobs = {sanitize_name(repo.name): test_job(repo) for repo in PUBLIC_REPOS} + run_name = f"Public repos test: version {env['PANTS_VERSION']} {env['EXTRA_ENV']}" + return PublicReposOutput(jobs=jobs, inputs=inputs, run_name=run_name) + + # ---------------------------------------------------------------------- # Main file # ---------------------------------------------------------------------- @@ -1260,11 +1565,23 @@ def generate() -> dict[Path, str]: Dumper=NoAliasDumper, ) + public_repos_output = public_repos() + public_repos_yaml = yaml.dump( + { + "name": "Public repos tests", + "run-name": public_repos_output.run_name, + "on": {"workflow_dispatch": {"inputs": public_repos_output.inputs}}, + "jobs": public_repos_output.jobs, + }, + Dumper=NoAliasDumper, + ) + return { Path(".github/workflows/audit.yaml"): f"{HEADER}\n\n{audit_yaml}", Path(".github/workflows/cache_comparison.yaml"): f"{HEADER}\n\n{cache_comparison_yaml}", Path(".github/workflows/test.yaml"): f"{HEADER}\n\n{test_yaml}", Path(".github/workflows/release.yaml"): f"{HEADER}\n\n{release_yaml}", + Path(".github/workflows/public_repos.yaml"): f"{HEADER}\n\n{public_repos_yaml}", }
Test Pants against public repositories As discussed in: https://groups.google.com/forum/#!topic/pants-devel/MhpY34sGx-g We'd like to beef up the integration tests that ci.sh performs, to catch more breaking changes earlier. One idea is to have ci.sh build actual open source projects. It seems like twitter-commons and aurora are likely candidates: https://reviews.apache.org/r/22662/
This came up recently. It would still be great to do, and there are some examples of projects like Rust doing this.
2023-05-25T23:22:44
pantsbuild/pants
19,179
pantsbuild__pants-19179
[ "7399" ]
fedd4b5583e922acf36f5fa94e5810d32ccd29d8
diff --git a/build-support/bin/release.py b/build-support/bin/release.py --- a/build-support/bin/release.py +++ b/build-support/bin/release.py @@ -389,6 +389,22 @@ def __init__(self) -> None: .stdout.decode() .strip() ) + self._head_committer_date = ( + subprocess.run( + [ + "git", + "show", + "--no-patch", + "--format=%cd", + "--date=format:%Y%m%d%H%M", + self._head_sha, + ], + stdout=subprocess.PIPE, + check=True, + ) + .stdout.decode() + .strip() + ) self.pants_version_file = Path("src/python/pants/VERSION") self.pants_stable_version = self.pants_version_file.read_text().strip() @@ -418,7 +434,9 @@ def deploy_pants_wheel_dir(self) -> Path: @property def pants_unstable_version(self) -> str: - return f"{self.pants_stable_version}+git{self._head_sha[:8]}" + # include the commit's timestamp to make multiple builds of a single stable version more + # easily orderable + return f"{self.pants_stable_version}+{self._head_committer_date}.git{self._head_sha[:8]}" @property def twine_venv_dir(self) -> Path:
generate unstable package versions which can be ordered by timestamp in release.sh CI on master was broken after merging 067238335e8bbe2dacbe6442548dd4ee5a0782df, because when building wheels, our release script sets `PANTS_UNSTABLE_VERSION` to be the version in `src/python/pants/VERSION`, along with the first 8 characters of the commit sha. This should be fine, but not mentioned in https://www.python.org/dev/peps/pep-0440/#local-version-identifiers is that local build tags which consist of only numbers will have leading zeroes truncated, e.g.: ``` X> pex packaging setuptools Python 2.7.15 (default, Jun 20 2018, 17:40:09) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from packaging.version import Version >>> Version('1.15.0.dev4+06723833') <Version('1.15.0.dev4+6723833')> >>> str(Version('1.15.0.dev4+06723833')) '1.15.0.dev4+6723833' ``` This required a fix in #7400 by prefacing the sha with a constant non-numeric string to avoid it getting parsed as a number. While that was fixed, it might also be pretty useful to further modify the `PANTS_UNSTABLE_VERSION`, to add a timestamp before the SHA. This would allow `ls` to ensure the most recently produced wheel would always be at the bottom of the output.
Note that the timestamp component should be relatively easy to generate, but may require coordination between wheel shards in CI to work: see https://github.com/pantsbuild/pants/pull/7400#issuecomment-474121731. This might not be too difficult though. Thinking about this again, it should be possible to deterministically extract the commit timestamp to use here, which avoid needing to coordinate between shards.
2023-05-28T01:16:56
pantsbuild/pants
19,180
pantsbuild__pants-19180
[ "19067" ]
a34feabef5400eb52472c34900ed39438dfa1d55
diff --git a/src/python/pants/backend/python/subsystems/lambdex.py b/src/python/pants/backend/python/subsystems/lambdex.py --- a/src/python/pants/backend/python/subsystems/lambdex.py +++ b/src/python/pants/backend/python/subsystems/lambdex.py @@ -7,6 +7,7 @@ from pants.backend.python.target_types import ConsoleScript from pants.engine.rules import collect_rules from pants.option.option_types import EnumOption +from pants.util.docutil import doc_url from pants.util.strutil import softwrap @@ -40,8 +41,8 @@ class Lambdex(PythonToolBase): ), removal_version="2.19.0.dev0", removal_hint=softwrap( - """ - Remove the whole [lambdex] section, as Lambdex is deprecated and its functionality be + f""" + Remove the whole [lambdex] section, as Lambdex is deprecated and its functionality will be removed. If you have `layout = "zip"`, no further action is required, as you are already using the recommended layout. @@ -50,6 +51,11 @@ class Lambdex(PythonToolBase): as recommended by cloud vendors. (If you are using `python_awslambda`, you will need to also update the handlers configured in the cloud from `lambdex_handler.handler` to `lambda_function.handler`.) + + See the docs for more details: + + * {doc_url('awslambda-python#migrating-from-pants-216-and-earlier')} + * {doc_url('google-cloud-function-python#migrating-from-pants-216-and-earlier')} """ ), )
Update FaaS documentation for new layout="zip" **Is your feature request related to a problem? Please describe.** In #19076, I implement a new method for building AWS Lambda artefacts. This will require changes to https://www.pantsbuild.org/docs/awslambda-python and https://www.pantsbuild.org/docs/google-cloud-function-python. **Describe the solution you'd like** - Update those pages. - Fix typo https://github.com/pantsbuild/pants/pull/19122#discussion_r1205972422 **Describe alternatives you've considered** N/A **Additional context** Potentially also update for #18880, if that's implemented.
2023-05-28T03:36:14
pantsbuild/pants
19,191
pantsbuild__pants-19191
[ "19174" ]
ee3be4d9c11794f3b98cffbf8262d3712c31a740
diff --git a/src/python/pants/engine/internals/graph.py b/src/python/pants/engine/internals/graph.py --- a/src/python/pants/engine/internals/graph.py +++ b/src/python/pants/engine/internals/graph.py @@ -11,7 +11,7 @@ import os.path from dataclasses import dataclass from pathlib import PurePath -from typing import Any, Iterable, Iterator, NamedTuple, Sequence, Type, cast +from typing import Any, Iterable, Iterator, NamedTuple, NewType, Sequence, Type, cast from pants.base.deprecated import warn_or_error from pants.base.specs import AncestorGlobSpec, RawSpecsWithoutFileOwners, RecursiveGlobSpec @@ -896,7 +896,15 @@ class OwnersRequest: match_if_owning_build_file_included_in_sources: bool = False -class Owners(Collection[Address]): +# NB: This was changed from: +# class Owners(Collection[Address]): +# pass +# In https://github.com/pantsbuild/pants/pull/19191 to facilitate surgical warning of deprecation +# of SecondaryOwnerMixin. After the Deprecation ends, it can be changed back. +IsPrimary = NewType("IsPrimary", bool) + + +class Owners(FrozenDict[Address, IsPrimary]): pass @@ -951,7 +959,7 @@ def create_live_and_deleted_gets( ) live_candidate_tgts, deleted_candidate_tgts = await MultiGet(live_get, deleted_get) - matching_addresses: OrderedSet[Address] = OrderedSet() + result = {} unmatched_sources = set(owners_request.sources) for live in (True, False): candidate_tgts: Sequence[Target] @@ -976,6 +984,8 @@ def create_live_and_deleted_gets( matching_files = set( candidate_tgt.get(SourcesField).filespec_matcher.matches(list(sources_set)) ) + is_primary = bool(matching_files) + # Also consider secondary ownership, meaning it's not a `SourcesField` field with # primary ownership, but the target still should match the file. We can't use # `tgt.get()` because this is a mixin, and there technically may be >1 field. @@ -986,8 +996,9 @@ def create_live_and_deleted_gets( ) for secondary_owner_field in secondary_owner_fields: matching_files.update( - *secondary_owner_field.filespec_matcher.matches(list(sources_set)) + secondary_owner_field.filespec_matcher.matches(list(sources_set)) ) + if not matching_files and not ( owners_request.match_if_owning_build_file_included_in_sources and bfa.rel_path in sources_set @@ -995,7 +1006,7 @@ def create_live_and_deleted_gets( continue unmatched_sources -= matching_files - matching_addresses.add(candidate_tgt.address) + result[candidate_tgt.address] = IsPrimary(is_primary) if ( unmatched_sources @@ -1005,7 +1016,7 @@ def create_live_and_deleted_gets( [PurePath(path) for path in unmatched_sources], owners_request.owners_not_found_behavior ) - return Owners(matching_addresses) + return Owners(result) # ----------------------------------------------------------------------------------------------- diff --git a/src/python/pants/engine/internals/specs_rules.py b/src/python/pants/engine/internals/specs_rules.py --- a/src/python/pants/engine/internals/specs_rules.py +++ b/src/python/pants/engine/internals/specs_rules.py @@ -3,6 +3,7 @@ from __future__ import annotations +import collections.abc import dataclasses import itertools import logging @@ -46,7 +47,6 @@ FilteredTargets, NoApplicableTargetsBehavior, RegisteredTargetTypes, - SecondaryOwnerMixin, SourcesField, SourcesPaths, SourcesPathsRequest, @@ -227,7 +227,7 @@ def valid_tgt( @rule(_masked_types=[EnvironmentName]) async def addresses_from_raw_specs_with_only_file_owners( specs: RawSpecsWithOnlyFileOwners, -) -> Addresses: +) -> Owners: """Find the owner(s) for each spec.""" paths_per_include = await MultiGet( Get(Paths, PathGlobs, specs.path_globs_for_spec(spec)) for spec in specs.all_specs() @@ -242,6 +242,11 @@ async def addresses_from_raw_specs_with_only_file_owners( match_if_owning_build_file_included_in_sources=False, ), ) + return owners + + +@rule(_masked_types=[EnvironmentName]) +async def addresses_from_owners(owners: Owners) -> Addresses: return Addresses(sorted(owners)) @@ -482,6 +487,48 @@ def __init__( ) +# NB: Remove when SecondaryOwnerMixin is removed +def _maybe_warn_deprecated_secondary_owner_semantics( + addresses_from_nonfile_specs: Addresses, + owners_from_filespecs: Owners, + matched_addresses: collections.abc.Set[Address], +): + """Warn about deprecated semantics of implicitly referring to a target through "Secondary + Ownership". + + E.g. If there's a `pex_binary` whose entry point is `foo.py`, using `foo.py` as a spec to mean + "package the pex binary" is deprecated, and the caller should specify the binary directly. + + This shouldn't warn if both the primary and secondary owner are in the specs (which is common + with specs like `::` or `dir:`). + """ + problematic_target_specs = { + address.spec + for address in matched_addresses + if address in owners_from_filespecs + and not owners_from_filespecs[address] + and address not in addresses_from_nonfile_specs + } + + if problematic_target_specs: + warn_or_error( + removal_version="2.18.0.dev1", + entity=softwrap( + """ + indirectly referring to a target by using a corresponding file argument, when the + target owning the file isn't applicable + """ + ), + hint=softwrap( + f""" + Refer to the following targets by their addresses: + + {bullet_list(sorted(problematic_target_specs))} + """ + ), + ) + + @rule async def find_valid_field_sets_for_target_roots( request: TargetRootsToFieldSetsRequest, @@ -530,33 +577,25 @@ async def find_valid_field_sets_for_target_roots( ): logger.warning(str(no_applicable_exception)) - secondary_owner_targets = set() - specified_literal_addresses = { - address_literal.to_address() for address_literal in specs.includes.address_literals - } - for tgt, field_sets in targets_to_applicable_field_sets.items(): - is_secondary = any( - isinstance(field, SecondaryOwnerMixin) for field in tgt.field_values.values() - ) - is_explicitly_specified = tgt.address in specified_literal_addresses - if is_secondary and not is_explicitly_specified: - secondary_owner_targets.add(tgt) - if secondary_owner_targets: - warn_or_error( - removal_version="2.18.0.dev1", - entity=softwrap( - """ - indirectly referring to a target by using a corresponding file argument, when the - target owning the file isn't applicable - """ - ), - hint=softwrap( - f""" - Refer to the following targets by their addresses: - - {bullet_list(sorted(tgt.address.spec for tgt in secondary_owner_targets))} - """ + # NB: Remove when SecondaryOwnerMixin is removed + if targets_to_applicable_field_sets: + _maybe_warn_deprecated_secondary_owner_semantics( + # NB: All of these should be memoized, so it's not inappropriate to request simply for warning sake. + *( + await MultiGet( + Get( + Addresses, + RawSpecsWithoutFileOwners, + RawSpecsWithoutFileOwners.from_raw_specs(specs.includes), + ), + Get( + Owners, + RawSpecsWithOnlyFileOwners, + RawSpecsWithOnlyFileOwners.from_raw_specs(specs.includes), + ), + ) ), + {tgt.address for tgt in targets_to_applicable_field_sets}, ) if request.num_shards > 0:
diff --git a/src/python/pants/engine/internals/specs_rules_test.py b/src/python/pants/engine/internals/specs_rules_test.py --- a/src/python/pants/engine/internals/specs_rules_test.py +++ b/src/python/pants/engine/internals/specs_rules_test.py @@ -1132,3 +1132,7 @@ def run_rule(specs: Iterable[Spec]): assert len(caplog.records) == 1 assert "secondary1" not in caplog.text assert "secondary2" in caplog.text + + result = run_rule([RecursiveGlobSpec("")]) + assert len(caplog.records) == 0 + assert result.mapping
Unactionable(?) "indirectly referring to a target" warning for `pants package ::` with pex or FaaS **Describe the bug** Running a goal like `pants package ::` when there's `pex_binary`, `python_awslambda` or `python_google_cloud_function` targets (all of the users of `SecondaryOwnerMixin` fields) gives a warning about indirectly referring to a target: ``` 20:51:16.61 [WARN] DEPRECATED: indirectly referring to a target by using a corresponding file argument, when the target owning the file isn't applicable is scheduled to be removed in version 2.18.0.dev0. Refer to the following targets by their addresses: * //:gcf * //:lambda * //:pex ``` As a user, I'm not sure what I can usefully change to resolve this. Replacing the `::` in the CLI invocation with the individual targets seems to work (`pants package :pex :lambda :gcf`), but: - I don't think we actually want users to be doing this (as a user, I certainly don't want to list out every single target like this) - even if we do want users to be doing this, I don't think it's clear from the error message: I'm _not_ using the corresponding file argument anywhere. I'm assuming this is meant to be catching invocations like `pants package ./file.py` packaging all of those targets, but is getting confused by the use of the `::` glob? Reproducer: ```shell cd $(mktemp -d) cat > pants.toml <<EOF [GLOBAL] pants_version = "2.17.0a1" backend_packages = [ "pants.backend.python", "pants.backend.awslambda.python", "pants.backend.google_cloud_function.python", ] [python] interpreter_constraints = [">=3.8"] [python-infer] use_rust_parser = false EOF echo "def func(): pass" > file.py cat > BUILD <<EOF python_sources(name="py") pex_binary(name="pex", entry_point="file.py") python_awslambda(name="lambda", handler="file.py:func", runtime="python3.9") python_google_cloud_function(name="gcf", handler="file.py:func", runtime="python39", type="event") EOF # BUG: prints `[WARN] DEPRECATED: indirectly referring to a target by using a corresponding file argument ...` pants package :: ``` **Pants version** 2.17.0a1 **OS** macOS **Additional info** #18737
2023-05-30T16:10:29
pantsbuild/pants
19,198
pantsbuild__pants-19198
[ "19067" ]
e99dda5c4a2828cf4756a310515d2baf669f0522
diff --git a/src/python/pants/backend/python/subsystems/lambdex.py b/src/python/pants/backend/python/subsystems/lambdex.py --- a/src/python/pants/backend/python/subsystems/lambdex.py +++ b/src/python/pants/backend/python/subsystems/lambdex.py @@ -8,6 +8,7 @@ from pants.base.deprecated import warn_or_error from pants.engine.rules import collect_rules from pants.option.option_types import EnumOption +from pants.util.docutil import doc_url from pants.util.strutil import softwrap @@ -64,6 +65,11 @@ def warn_for_layout(self, target_alias: str) -> None: You can also explicitly set `layout = "lambdex"` to silence this warning and continue using the Lambdex-based layout in this release of Pants. This layout will disappear in future. + + See the docs for more details: + + * {doc_url('awslambda-python#migrating-from-pants-216-and-earlier')} + * {doc_url('google-cloud-function-python#migrating-from-pants-216-and-earlier')} """ ), )
Update FaaS documentation for new layout="zip" **Is your feature request related to a problem? Please describe.** In #19076, I implement a new method for building AWS Lambda artefacts. This will require changes to https://www.pantsbuild.org/docs/awslambda-python and https://www.pantsbuild.org/docs/google-cloud-function-python. **Describe the solution you'd like** - Update those pages. - Fix typo https://github.com/pantsbuild/pants/pull/19122#discussion_r1205972422 **Describe alternatives you've considered** N/A **Additional context** Potentially also update for #18880, if that's implemented.
2023-05-30T23:18:01
pantsbuild/pants
19,220
pantsbuild__pants-19220
[ "19219" ]
5becc13ebaad5ecdc42228486727da1c20521521
diff --git a/src/python/pants/backend/helm/subsystems/unittest.py b/src/python/pants/backend/helm/subsystems/unittest.py --- a/src/python/pants/backend/helm/subsystems/unittest.py +++ b/src/python/pants/backend/helm/subsystems/unittest.py @@ -2,6 +2,7 @@ # Licensed under the Apache License, Version 2.0 (see LICENSE). from enum import Enum +from typing import ClassVar from pants.backend.helm.util_rules.tool import ( ExternalHelmPlugin, @@ -25,16 +26,20 @@ class HelmUnitTestReportFormat(Enum): class HelmUnitTestSubsystem(ExternalHelmPlugin): options_scope = "helm-unittest" plugin_name = "unittest" - help = "BDD styled unit test framework for Kubernetes Helm charts as a Helm plugin. (https://github.com/quintush/helm-unittest)" + help = "BDD styled unit test framework for Kubernetes Helm charts as a Helm plugin. (https://github.com/helm-unittest)" - default_version = "0.2.8" + default_version = "0.3.3" default_known_versions = [ + "0.3.3|linux_x86_64|8ebe20f77012a5d4e7139760cabe36dd1ea38e40b26f57de3f4165d96bd486ff|21685365", + "0.3.3|linux_arm64 |7f5e4426428cb9678f971576103df410e6fa38dd19b87fce4729f5217bd5c683|19944514", + "0.3.3|macos_x86_64|b2298a513b3cb6482ba2e42079c93ad18be8a31a230bd4dffdeb01ec2881d0f5|21497144", + "0.3.3|macos_arm64 |2365f5b3a99e6fc83218457046378b14039a3992e9ae96a4192bc2e43a33c742|20479438", "0.2.8|linux_x86_64|d7c452559ad4406a1197435394fbcffe51198060de1aa9b4cb6feaf876776ba0|18299096", "0.2.8|linux_arm64 |c793e241b063f0540ad9b4acc0a02e5a101bd9daea5bdf4d8562e9b2337fedb2|16943867", "0.2.8|macos_x86_64|1dc95699320894bdebf055c4f4cc084c2cfa0133d3cb7fd6a4c0adca94df5c96|18161928", "0.2.8|macos_arm64 |436e3167c26f71258b96e32c2877b4f97c051064db941de097cf3db2fc861342|17621648", ] - default_url_template = "https://github.com/quintush/helm-unittest/releases/download/v{version}/helm-unittest-{platform}-{version}.tgz" + default_url_template = "https://github.com/helm-unittest/helm-unittest/releases/download/v{version}/helm-unittest-{platform}-{version}.tgz" default_url_platform_mapping = { "linux_arm64": "linux-arm64", "linux_x86_64": "linux-amd64", @@ -42,6 +47,11 @@ class HelmUnitTestSubsystem(ExternalHelmPlugin): "macos_x86_64": "macos-amd64", } + # TODO Remove after dropping support for the legacy tool + legacy_url_template: ClassVar[ + str + ] = "https://github.com/quintush/helm-unittest/releases/download/v{version}/helm-unittest-{platform}-{version}.tgz" + color = BoolOption( "--color", default=False, @@ -55,6 +65,17 @@ class HelmUnitTestSubsystem(ExternalHelmPlugin): skip = SkipOption("test") + @property + def _is_legacy(self) -> bool: + version_parts = self.version.split(".") + return len(version_parts) >= 2 and version_parts[1] == "2" + + def generate_url(self, plat: Platform) -> str: + if self._is_legacy: + platform = self.url_platform_mapping.get(plat.value, "") + return self.legacy_url_template.format(version=self.version, platform=platform) + return super().generate_url(plat) + def generate_exe(self, _: Platform) -> str: return "./untt" diff --git a/src/python/pants/core/util_rules/external_tool.py b/src/python/pants/core/util_rules/external_tool.py --- a/src/python/pants/core/util_rules/external_tool.py +++ b/src/python/pants/core/util_rules/external_tool.py @@ -340,7 +340,7 @@ class TemplatedExternalTool(ExternalTool, TemplatedExternalToolOptionsMixin): The platform mapping dict is optional. """ - def generate_url(self, plat: Platform): + def generate_url(self, plat: Platform) -> str: platform = self.url_platform_mapping.get(plat.value, "") return self.url_template.format(version=self.version, platform=platform)
diff --git a/src/python/pants/backend/helm/test/unittest.py b/src/python/pants/backend/helm/test/unittest.py --- a/src/python/pants/backend/helm/test/unittest.py +++ b/src/python/pants/backend/helm/test/unittest.py @@ -24,6 +24,7 @@ from pants.backend.helm.util_rules.chart import HelmChart, HelmChartRequest from pants.backend.helm.util_rules.sources import HelmChartRoot, HelmChartRootRequest from pants.backend.helm.util_rules.tool import HelmProcess +from pants.base.deprecated import warn_or_error from pants.core.goals.test import TestFieldSet, TestRequest, TestResult, TestSubsystem from pants.core.target_types import ResourceSourceField from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest @@ -126,15 +127,24 @@ async def run_helm_unittest( ProcessCacheScope.PER_SESSION if test_subsystem.force else ProcessCacheScope.SUCCESSFUL ) - strict = field_set.strict.value + uses_legacy = unittest_subsystem._is_legacy + if uses_legacy: + warn_or_error( + "2.19.0.dev0", + f"[{unittest_subsystem.options_scope}].version < {unittest_subsystem.default_version}", + "You should upgrade your test suites to work with latest version.", + start_version="2.18.0.dev1", + ) + process_result = await Get( FallibleProcessResult, HelmProcess( argv=[ unittest_subsystem.plugin_name, - "--helm3", + # TODO remove this flag once support for legacy unittest tool is dropped. + *(("--helm3",) if uses_legacy else ()), *(("--color",) if unittest_subsystem.color else ()), - *(("--strict",) if strict else ()), + *(("--strict",) if field_set.strict.value else ()), "--output-type", unittest_subsystem.output_type.value, "--output-file", diff --git a/src/python/pants/backend/helm/test/unittest_test.py b/src/python/pants/backend/helm/test/unittest_test.py --- a/src/python/pants/backend/helm/test/unittest_test.py +++ b/src/python/pants/backend/helm/test/unittest_test.py @@ -79,6 +79,46 @@ def test_simple_success(rule_runner: RuleRunner) -> None: assert result.xml_results.files == (f"{target.address.path_safe_spec}.xml",) +def test_simple_success_with_legacy_tool(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "BUILD": "helm_chart(name='mychart')", + "Chart.yaml": HELM_CHART_FILE, + "values.yaml": HELM_VALUES_FILE, + "templates/_helpers.tpl": HELM_TEMPLATE_HELPERS_FILE, + "templates/service.yaml": K8S_SERVICE_TEMPLATE, + "tests/BUILD": "helm_unittest_test(name='test', source='service_test.yaml')", + "tests/service_test.yaml": dedent( + """\ + suite: test service + templates: + - service.yaml + values: + - ../values.yaml + tests: + - it: should work + asserts: + - isKind: + of: Service + - equal: + path: spec.type + value: ClusterIP + """ + ), + } + ) + + rule_runner.set_options(["--helm-unittest-version=0.2.8"]) + target = rule_runner.get_target(Address("tests", target_name="test")) + field_set = HelmUnitTestFieldSet.create(target) + + result = rule_runner.request(TestResult, [HelmUnitTestRequest.Batch("", (field_set,), None)]) + + assert result.exit_code == 0 + assert result.xml_results and result.xml_results.files + assert result.xml_results.files == (f"{target.address.path_safe_spec}.xml",) + + def test_simple_failure(rule_runner: RuleRunner) -> None: rule_runner.write_files( {
Helm unittest subsystem version >0.3.3 support **Is your feature request related to a problem? Please describe.** It seems that [the current project](https://github.com/quintush/helm-unittest) used for helm_unittests is no longer supported. Instead the maintainer proceeds the development in [the following project ](https://github.com/helm-unittest/helm-unittest). **Describe the solution you'd like** Does it make sense to switch unittesting to the project which is actually maintained? Tried to do it within the configfile ```pants.toml [helm-unittest] version = "0.3.3" url_template = "https://github.com/helm-unittest/helm-unittest/releases/download/v{version}/helm-unittest-{platform}-{version}.tgz" use_unsupported_version = "warning" known_versions = [ "0.3.3|linux_x86_64|8ebe20f77012a5d4e7139760cabe36dd1ea38e40b26f57de3f4165d96bd486ff|21685365", "0.3.3|linux_arm64 |7f5e4426428cb9678f971576103df410e6fa38dd19b87fce4729f5217bd5c683|19944514", "0.3.3|macos_x86_64|b2298a513b3cb6482ba2e42079c93ad18be8a31a230bd4dffdeb01ec2881d0f5|21497144", "0.3.3|macos_arm64 |2365f5b3a99e6fc83218457046378b14039a3992e9ae96a4192bc2e43a33c742|20479438" ] ``` Errors occured: ``` 16:07:27.77 [ERROR] Completed: Run Helm Unittest - pupkins/tests/pup_test.yaml - failed (exit code 1). unknown flag: --helm3 Error: unknown flag: --helm3 ```
Welcome to the Pantsbuild Community. This looks like your first issue here. Thanks for taking the time to write it. If you haven't already, feel free to [come say hi on Slack](https://docs.google.com/forms/d/e/1FAIpQLSf9zgf-MXRnVDJbrVEST3urqneq7LCcy0zw8qU-GH4hPMn52A/viewform?usp=sf_link). If you have questions, or just want to surface this issue, check out the `#development` channel. (If you want to check it out without logging in, check out our [Linen mirror](https://chat.pantsbuild.org/)) Thanks again, and we look forward to your next Issue/PR :smile:! Thanks for the issue report. The flag that causes the error comes from the internal implementation in the Helm backend, otherwise it would fail to run unit tests in Helm 3 charts. It seems that this new version should be fully backwards compatible with the previous one, with the exception of the flag. So I don't see any reason to not do the upgrade. Is it possible for you to run your tests using the builtin version or do you really need the most recent one?
2023-06-01T15:30:26
pantsbuild/pants
19,224
pantsbuild__pants-19224
[ "19174" ]
88952f8549f6d2e8e091d65350083ac3b238f1b1
diff --git a/src/python/pants/engine/internals/graph.py b/src/python/pants/engine/internals/graph.py --- a/src/python/pants/engine/internals/graph.py +++ b/src/python/pants/engine/internals/graph.py @@ -11,7 +11,7 @@ import os.path from dataclasses import dataclass from pathlib import PurePath -from typing import Any, Iterable, Iterator, NamedTuple, Sequence, Type, cast +from typing import Any, Iterable, Iterator, NamedTuple, NewType, Sequence, Type, cast from pants.base.deprecated import warn_or_error from pants.base.specs import AncestorGlobSpec, RawSpecsWithoutFileOwners, RecursiveGlobSpec @@ -909,7 +909,15 @@ class OwnersRequest: match_if_owning_build_file_included_in_sources: bool = False -class Owners(Collection[Address]): +# NB: This was changed from: +# class Owners(Collection[Address]): +# pass +# In https://github.com/pantsbuild/pants/pull/19191 to facilitate surgical warning of deprecation +# of SecondaryOwnerMixin. After the Deprecation ends, it can be changed back. +IsPrimary = NewType("IsPrimary", bool) + + +class Owners(FrozenDict[Address, IsPrimary]): pass @@ -964,7 +972,7 @@ def create_live_and_deleted_gets( ) live_candidate_tgts, deleted_candidate_tgts = await MultiGet(live_get, deleted_get) - matching_addresses: OrderedSet[Address] = OrderedSet() + result = {} unmatched_sources = set(owners_request.sources) for live in (True, False): candidate_tgts: Sequence[Target] @@ -989,6 +997,8 @@ def create_live_and_deleted_gets( matching_files = set( candidate_tgt.get(SourcesField).filespec_matcher.matches(list(sources_set)) ) + is_primary = bool(matching_files) + # Also consider secondary ownership, meaning it's not a `SourcesField` field with # primary ownership, but the target still should match the file. We can't use # `tgt.get()` because this is a mixin, and there technically may be >1 field. @@ -999,8 +1009,9 @@ def create_live_and_deleted_gets( ) for secondary_owner_field in secondary_owner_fields: matching_files.update( - *secondary_owner_field.filespec_matcher.matches(list(sources_set)) + secondary_owner_field.filespec_matcher.matches(list(sources_set)) ) + if not matching_files and not ( owners_request.match_if_owning_build_file_included_in_sources and bfa.rel_path in sources_set @@ -1008,7 +1019,7 @@ def create_live_and_deleted_gets( continue unmatched_sources -= matching_files - matching_addresses.add(candidate_tgt.address) + result[candidate_tgt.address] = IsPrimary(is_primary) if ( unmatched_sources @@ -1018,7 +1029,7 @@ def create_live_and_deleted_gets( [PurePath(path) for path in unmatched_sources], owners_request.owners_not_found_behavior ) - return Owners(matching_addresses) + return Owners(result) # ----------------------------------------------------------------------------------------------- diff --git a/src/python/pants/engine/internals/specs_rules.py b/src/python/pants/engine/internals/specs_rules.py --- a/src/python/pants/engine/internals/specs_rules.py +++ b/src/python/pants/engine/internals/specs_rules.py @@ -3,6 +3,7 @@ from __future__ import annotations +import collections.abc import dataclasses import itertools import logging @@ -46,7 +47,6 @@ FilteredTargets, NoApplicableTargetsBehavior, RegisteredTargetTypes, - SecondaryOwnerMixin, SourcesField, SourcesPaths, SourcesPathsRequest, @@ -227,7 +227,7 @@ def valid_tgt( @rule(_masked_types=[EnvironmentName]) async def addresses_from_raw_specs_with_only_file_owners( specs: RawSpecsWithOnlyFileOwners, -) -> Addresses: +) -> Owners: """Find the owner(s) for each spec.""" paths_per_include = await MultiGet( Get(Paths, PathGlobs, specs.path_globs_for_spec(spec)) for spec in specs.all_specs() @@ -242,6 +242,11 @@ async def addresses_from_raw_specs_with_only_file_owners( match_if_owning_build_file_included_in_sources=False, ), ) + return owners + + +@rule(_masked_types=[EnvironmentName]) +async def addresses_from_owners(owners: Owners) -> Addresses: return Addresses(sorted(owners)) @@ -482,6 +487,48 @@ def __init__( ) +# NB: Remove when SecondaryOwnerMixin is removed +def _maybe_warn_deprecated_secondary_owner_semantics( + addresses_from_nonfile_specs: Addresses, + owners_from_filespecs: Owners, + matched_addresses: collections.abc.Set[Address], +): + """Warn about deprecated semantics of implicitly referring to a target through "Secondary + Ownership". + + E.g. If there's a `pex_binary` whose entry point is `foo.py`, using `foo.py` as a spec to mean + "package the pex binary" is deprecated, and the caller should specify the binary directly. + + This shouldn't warn if both the primary and secondary owner are in the specs (which is common + with specs like `::` or `dir:`). + """ + problematic_target_specs = { + address.spec + for address in matched_addresses + if address in owners_from_filespecs + and not owners_from_filespecs[address] + and address not in addresses_from_nonfile_specs + } + + if problematic_target_specs: + warn_or_error( + removal_version="2.18.0.dev1", + entity=softwrap( + """ + indirectly referring to a target by using a corresponding file argument, when the + target owning the file isn't applicable + """ + ), + hint=softwrap( + f""" + Refer to the following targets by their addresses: + + {bullet_list(sorted(problematic_target_specs))} + """ + ), + ) + + @rule async def find_valid_field_sets_for_target_roots( request: TargetRootsToFieldSetsRequest, @@ -530,33 +577,25 @@ async def find_valid_field_sets_for_target_roots( ): logger.warning(str(no_applicable_exception)) - secondary_owner_targets = set() - specified_literal_addresses = { - address_literal.to_address() for address_literal in specs.includes.address_literals - } - for tgt, field_sets in targets_to_applicable_field_sets.items(): - is_secondary = any( - isinstance(field, SecondaryOwnerMixin) for field in tgt.field_values.values() - ) - is_explicitly_specified = tgt.address in specified_literal_addresses - if is_secondary and not is_explicitly_specified: - secondary_owner_targets.add(tgt) - if secondary_owner_targets: - warn_or_error( - removal_version="2.18.0.dev0", - entity=softwrap( - """ - indirectly referring to a target by using a corresponding file argument, when the - target owning the file isn't applicable - """ - ), - hint=softwrap( - f""" - Refer to the following targets by their addresses: - - {bullet_list(sorted(tgt.address.spec for tgt in secondary_owner_targets))} - """ + # NB: Remove when SecondaryOwnerMixin is removed + if targets_to_applicable_field_sets: + _maybe_warn_deprecated_secondary_owner_semantics( + # NB: All of these should be memoized, so it's not inappropriate to request simply for warning sake. + *( + await MultiGet( + Get( + Addresses, + RawSpecsWithoutFileOwners, + RawSpecsWithoutFileOwners.from_raw_specs(specs.includes), + ), + Get( + Owners, + RawSpecsWithOnlyFileOwners, + RawSpecsWithOnlyFileOwners.from_raw_specs(specs.includes), + ), + ) ), + {tgt.address for tgt in targets_to_applicable_field_sets}, ) if request.num_shards > 0:
diff --git a/src/python/pants/engine/internals/specs_rules_test.py b/src/python/pants/engine/internals/specs_rules_test.py --- a/src/python/pants/engine/internals/specs_rules_test.py +++ b/src/python/pants/engine/internals/specs_rules_test.py @@ -1132,3 +1132,7 @@ def run_rule(specs: Iterable[Spec]): assert len(caplog.records) == 1 assert "secondary1" not in caplog.text assert "secondary2" in caplog.text + + result = run_rule([RecursiveGlobSpec("")]) + assert len(caplog.records) == 0 + assert result.mapping
Unactionable(?) "indirectly referring to a target" warning for `pants package ::` with pex or FaaS **Describe the bug** Running a goal like `pants package ::` when there's `pex_binary`, `python_awslambda` or `python_google_cloud_function` targets (all of the users of `SecondaryOwnerMixin` fields) gives a warning about indirectly referring to a target: ``` 20:51:16.61 [WARN] DEPRECATED: indirectly referring to a target by using a corresponding file argument, when the target owning the file isn't applicable is scheduled to be removed in version 2.18.0.dev0. Refer to the following targets by their addresses: * //:gcf * //:lambda * //:pex ``` As a user, I'm not sure what I can usefully change to resolve this. Replacing the `::` in the CLI invocation with the individual targets seems to work (`pants package :pex :lambda :gcf`), but: - I don't think we actually want users to be doing this (as a user, I certainly don't want to list out every single target like this) - even if we do want users to be doing this, I don't think it's clear from the error message: I'm _not_ using the corresponding file argument anywhere. I'm assuming this is meant to be catching invocations like `pants package ./file.py` packaging all of those targets, but is getting confused by the use of the `::` glob? Reproducer: ```shell cd $(mktemp -d) cat > pants.toml <<EOF [GLOBAL] pants_version = "2.17.0a1" backend_packages = [ "pants.backend.python", "pants.backend.awslambda.python", "pants.backend.google_cloud_function.python", ] [python] interpreter_constraints = [">=3.8"] [python-infer] use_rust_parser = false EOF echo "def func(): pass" > file.py cat > BUILD <<EOF python_sources(name="py") pex_binary(name="pex", entry_point="file.py") python_awslambda(name="lambda", handler="file.py:func", runtime="python3.9") python_google_cloud_function(name="gcf", handler="file.py:func", runtime="python39", type="event") EOF # BUG: prints `[WARN] DEPRECATED: indirectly referring to a target by using a corresponding file argument ...` pants package :: ``` **Pants version** 2.17.0a1 **OS** macOS **Additional info** #18737
2023-06-01T20:35:38
pantsbuild/pants
19,225
pantsbuild__pants-19225
[ "19156" ]
11cb1f45ed61acf9c4d41b03fd402a4265aba499
diff --git a/src/python/pants/engine/internals/parser.py b/src/python/pants/engine/internals/parser.py --- a/src/python/pants/engine/internals/parser.py +++ b/src/python/pants/engine/internals/parser.py @@ -401,7 +401,7 @@ def parse( raise defined_symbols.add(bad_symbol) - global_symbols[bad_symbol] = _unrecognized_symbol_func + global_symbols[bad_symbol] = _UnrecognizedSymbol(bad_symbol) self._parse_state.reset( filepath=filepath, is_bootstrap=is_bootstrap, @@ -485,6 +485,38 @@ def _extract_symbol_from_name_error(err: NameError) -> str: return result.group(1) -def _unrecognized_symbol_func(**kwargs): - """Allows us to not choke on unrecognized symbols, including when they're called as - functions.""" +class _UnrecognizedSymbol: + """Allows us to not choke on unrecognized symbols, including when they're called as functions. + + During bootstrap macros are not loaded and if used in field values to environment targets (which + are parsed during the bootstrap phase) those fields will get instances of this class as field + values. + """ + + def __init__(self, name: str) -> None: + self.name = name + self.args: tuple[Any, ...] = () + self.kwargs: dict[str, Any] = {} + + def __call__(self, *args, **kwargs) -> _UnrecognizedSymbol: + self.args = args + self.kwargs = kwargs + return self + + def __eq__(self, other) -> bool: + return ( + isinstance(other, _UnrecognizedSymbol) + and other.name == self.name + and other.args == self.args + and other.kwargs == self.kwargs + ) + + def __repr__(self) -> str: + args = ", ".join(map(repr, self.args)) + kwargs = ", ".join(f"{k}={v!r}" for k, v in self.kwargs.items()) + signature = ", ".join(s for s in (args, kwargs) if s) + return f"{self.name}({signature})" + + +# Customize the type name presented by the InvalidFieldTypeException. +_UnrecognizedSymbol.__name__ = "<unrecognized symbol>" diff --git a/src/python/pants/engine/target.py b/src/python/pants/engine/target.py --- a/src/python/pants/engine/target.py +++ b/src/python/pants/engine/target.py @@ -1592,9 +1592,10 @@ def __init__( expected_type: str, description_of_origin: str | None = None, ) -> None: + raw_type = f"with type `{type(raw_value).__name__}`" 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__}`.", + f"`{repr(raw_value)}` {raw_type}.", description_of_origin=description_of_origin, )
diff --git a/src/python/pants/engine/internals/mapper_test.py b/src/python/pants/engine/internals/mapper_test.py --- a/src/python/pants/engine/internals/mapper_test.py +++ b/src/python/pants/engine/internals/mapper_test.py @@ -22,7 +22,7 @@ DuplicateNameError, SpecsFilter, ) -from pants.engine.internals.parser import BuildFilePreludeSymbols, Parser, _unrecognized_symbol_func +from pants.engine.internals.parser import BuildFilePreludeSymbols, Parser, _UnrecognizedSymbol from pants.engine.internals.target_adaptor import TargetAdaptor as _TargetAdaptor from pants.engine.target import RegisteredTargetTypes, Tags, Target from pants.engine.unions import UnionMembership @@ -95,7 +95,7 @@ def test_address_map_unrecognized_symbol() -> None: address_map = parse_address_map(build_file, ignore_unrecognized_symbols=True) assert { "one": TargetAdaptor(type_alias="thing", name="one"), - "bad": TargetAdaptor(type_alias="thing", name="bad", age=_unrecognized_symbol_func), + "bad": TargetAdaptor(type_alias="thing", name="bad", age=_UnrecognizedSymbol("fake")), "two": TargetAdaptor(type_alias="thing", name="two"), "three": TargetAdaptor( type_alias="thing", diff --git a/src/python/pants/engine/internals/parser_test.py b/src/python/pants/engine/internals/parser_test.py --- a/src/python/pants/engine/internals/parser_test.py +++ b/src/python/pants/engine/internals/parser_test.py @@ -3,6 +3,7 @@ from __future__ import annotations +import re from textwrap import dedent from typing import Any @@ -10,6 +11,7 @@ from pants.build_graph.build_file_aliases import BuildFileAliases from pants.core.target_types import GenericTarget +from pants.engine.addresses import Address from pants.engine.env_vars import EnvironmentVars from pants.engine.internals.defaults import BuildFileDefaults, BuildFileDefaultsParserState from pants.engine.internals.parser import ( @@ -18,7 +20,7 @@ Parser, _extract_symbol_from_name_error, ) -from pants.engine.target import RegisteredTargetTypes +from pants.engine.target import InvalidFieldException, RegisteredTargetTypes, StringField from pants.engine.unions import UnionMembership from pants.testutil.pytest_util import no_exception from pants.util.docutil import doc_url @@ -128,6 +130,47 @@ def perform_test(extra_targets: list[str], dym: str) -> None: perform_test(test_targs, dym_many) +def test_unrecognized_symbol_during_bootstrap_issue_19156( + defaults_parser_state: BuildFileDefaultsParserState, +) -> None: + build_file_aliases = BuildFileAliases( + objects={"obj": 0}, + context_aware_object_factories={"caof": lambda parse_context: lambda _: None}, + ) + parser = Parser( + build_root="", + registered_target_types=RegisteredTargetTypes({"tgt": GenericTarget}), + union_membership=UnionMembership({}), + object_aliases=build_file_aliases, + ignore_unrecognized_symbols=True, + ) + prelude_symbols = BuildFilePreludeSymbols.create({"prelude": 0}, ()) + target_adaptors = parser.parse( + "dir/BUILD", + "tgt(field=fake(42,a=(), b='c'))", + prelude_symbols, + EnvironmentVars({}), + False, + defaults_parser_state, + dependents_rules=None, + dependencies_rules=None, + ) + + assert len(target_adaptors) == 1 + raw_field = target_adaptors[0].kwargs["field"] + assert repr(raw_field) == "fake(42, a=(), b='c')" + + class TestField(StringField): + alias = "field" + + err = re.escape( + f"The 'field' field in target // must be a string, but was `{raw_field!r}` " + "with type `<unrecognized symbol>`." + ) + with pytest.raises(InvalidFieldException, match=err): + TestField(raw_field, Address("")) + + @pytest.mark.parametrize("symbol", ["a", "bad", "BAD", "a___b_c", "a231", "áç"]) def test_extract_symbol_from_name_error(symbol: str) -> None: assert _extract_symbol_from_name_error(NameError(f"name '{symbol}' is not defined")) == symbol
TypeError when using macro in root BUILD file **Describe the bug** Given `BUILD.pants`: ```python docker_environment( name="focal-docker", image=wo_get_pinned_name("ubuntu:focal") ) ``` and macro: ```python def wo_get_pinned_name(x): return x ``` **Pants version** 2.16.0rc2 **OS** Linux **Additional info** ``` Exception caught: (pants.engine.internals.scheduler.ExecutionError) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/bin/pants", line 8, in <module> sys.exit(main()) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 123, in main PantsLoader.main() File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 110, in main cls.run_default_entrypoint() File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 92, in run_default_entrypoint exit_code = runner.run(start_time) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/bin/pants_runner.py", line 99, in run runner = LocalPantsRunner.create( File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/bin/local_pants_runner.py", line 90, in create build_config = options_initializer.build_config(options_bootstrapper, env) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/init/options_initializer.py", line 111, in build_config return _initialize_build_configuration(self._plugin_resolver, options_bootstrapper, env) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/init/options_initializer.py", line 48, in _initialize_build_configuration working_set = plugin_resolver.resolve(options_bootstrapper, env) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/init/plugin_resolver.py", line 137, in resolve for resolved_plugin_location in self._resolve_plugins( File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/init/plugin_resolver.py", line 161, in _resolve_plugins params = Params(request, determine_bootstrap_environment(session)) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/core/util_rules/environments.py", line 443, in determine_bootstrap_environment session.product_request(ChosenLocalEnvironmentName, [Params()])[0], File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 569, in product_request return self.execute(request) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 513, in execute self._raise_on_error([t for _, t in throws]) File "/home/josh/.cache/nce/ae553d873185fa750061b1a3d4226442fb99fb55d4403b0227ec972406554da3/bindings/venvs/2.16.0rc2/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 497, in _raise_on_error raise ExecutionError( Exception message: 1 Exception encountered: MappingError: Failed to parse ./BUILD.pants: TypeError: _unrecognized_symbol_func() takes 0 positional arguments but 1 was given ```
2023-06-01T21:13:11
pantsbuild/pants
19,263
pantsbuild__pants-19263
[ "19257" ]
2103025bac48421d1bfa9c544b137f195333bf7f
diff --git a/src/python/pants/backend/helm/dependency_inference/deployment.py b/src/python/pants/backend/helm/dependency_inference/deployment.py --- a/src/python/pants/backend/helm/dependency_inference/deployment.py +++ b/src/python/pants/backend/helm/dependency_inference/deployment.py @@ -132,7 +132,7 @@ async def first_party_helm_deployment_mapping( docker_target_addresses = {tgt.address.spec: tgt.address for tgt in docker_targets} def lookup_docker_addreses(image_ref: str) -> tuple[str, Address] | None: - addr = docker_target_addresses.get(str(image_ref), None) + addr = docker_target_addresses.get(image_ref, None) if addr: return image_ref, addr return None
diff --git a/src/python/pants/backend/helm/test/unittest.py b/src/python/pants/backend/helm/test/unittest.py --- a/src/python/pants/backend/helm/test/unittest.py +++ b/src/python/pants/backend/helm/test/unittest.py @@ -26,8 +26,9 @@ from pants.backend.helm.util_rules.tool import HelmProcess from pants.base.deprecated import warn_or_error from pants.core.goals.test import TestFieldSet, TestRequest, TestResult, TestSubsystem -from pants.core.target_types import ResourceSourceField +from pants.core.target_types import FileSourceField, ResourceSourceField from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest +from pants.core.util_rules.stripped_source_files import StrippedSourceFiles from pants.engine.addresses import Address from pants.engine.fs import AddPrefix, Digest, MergeDigests, RemovePrefix, Snapshot from pants.engine.process import FallibleProcessResult, ProcessCacheScope @@ -89,21 +90,18 @@ async def run_helm_unittest( raise MissingUnitTestChartDependency(field_set.address) chart_target = chart_targets[0] - chart, chart_root, test_files = await MultiGet( + chart, chart_root, test_files, extra_files = await MultiGet( Get(HelmChart, HelmChartRequest, HelmChartRequest.from_target(chart_target)), Get(HelmChartRoot, HelmChartRootRequest(chart_target[HelmChartMetaSourceField])), Get( SourceFiles, + SourceFilesRequest(sources_fields=[field_set.source]), + ), + Get( + StrippedSourceFiles, SourceFilesRequest( - sources_fields=[ - field_set.source, - *( - tgt.get(SourcesField) - for tgt in transitive_targets.dependencies - if not HelmChartFieldSet.is_applicable(tgt) - ), - ], - for_sources_types=(HelmUnitTestSourceField, ResourceSourceField), + sources_fields=[tgt.get(SourcesField) for tgt in transitive_targets.dependencies], + for_sources_types=(ResourceSourceField, FileSourceField), enable_codegen=True, ), ), @@ -118,7 +116,7 @@ async def run_helm_unittest( merged_digests = await Get( Digest, - MergeDigests([chart.snapshot.digest, stripped_test_files]), + MergeDigests([chart.snapshot.digest, stripped_test_files, extra_files.snapshot.digest]), ) input_digest = await Get(Digest, AddPrefix(merged_digests, chart.name)) diff --git a/src/python/pants/backend/helm/test/unittest_test.py b/src/python/pants/backend/helm/test/unittest_test.py --- a/src/python/pants/backend/helm/test/unittest_test.py +++ b/src/python/pants/backend/helm/test/unittest_test.py @@ -5,8 +5,12 @@ import pytest -from pants.backend.helm.target_types import HelmChartTarget, HelmUnitTestTestTarget -from pants.backend.helm.target_types import rules as target_types_rules +from pants.backend.helm.target_types import ( + HelmChartTarget, + HelmUnitTestTestsGeneratorTarget, + HelmUnitTestTestTarget, +) +from pants.backend.helm.target_types import rules as helm_target_types_rules from pants.backend.helm.test.unittest import HelmUnitTestFieldSet, HelmUnitTestRequest from pants.backend.helm.test.unittest import rules as unittest_rules from pants.backend.helm.testutil import ( @@ -17,7 +21,14 @@ ) from pants.backend.helm.util_rules import chart from pants.core.goals.test import TestResult -from pants.core.util_rules import external_tool, source_files +from pants.core.target_types import ( + FilesGeneratorTarget, + FileTarget, + RelocatedFiles, + ResourcesGeneratorTarget, +) +from pants.core.target_types import rules as target_types_rules +from pants.core.util_rules import external_tool, source_files, stripped_source_files from pants.engine.addresses import Address from pants.engine.rules import QueryRule from pants.source.source_root import rules as source_root_rules @@ -27,13 +38,23 @@ @pytest.fixture def rule_runner() -> RuleRunner: return RuleRunner( - target_types=[HelmChartTarget, HelmUnitTestTestTarget], + target_types=[ + HelmChartTarget, + HelmUnitTestTestTarget, + HelmUnitTestTestsGeneratorTarget, + ResourcesGeneratorTarget, + FileTarget, + FilesGeneratorTarget, + RelocatedFiles, + ], rules=[ *external_tool.rules(), *chart.rules(), *unittest_rules(), *source_files.rules(), *source_root_rules(), + *helm_target_types_rules(), + *stripped_source_files.rules(), *target_types_rules(), QueryRule(TestResult, (HelmUnitTestRequest.Batch,)), ], @@ -153,3 +174,241 @@ def test_simple_failure(rule_runner: RuleRunner) -> None: result = rule_runner.request(TestResult, [HelmUnitTestRequest.Batch("", (field_set,), None)]) assert result.exit_code == 1 + + +def test_test_with_local_resource_file(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "BUILD": "helm_chart(name='mychart')", + "Chart.yaml": HELM_CHART_FILE, + "templates/configmap.yaml": dedent( + """\ + apiVersion: v1 + kind: ConfigMap + metadata: + name: foo-config + data: + foo_key: {{ .Values.input }} + """ + ), + "tests/BUILD": dedent( + """\ + helm_unittest_test(name="test", source="configmap_test.yaml", dependencies=[":values"]) + + resources(name="values", sources=["general-values.yml"]) + """ + ), + "tests/configmap_test.yaml": dedent( + """\ + suite: test config map + templates: + - configmap.yaml + values: + - general-values.yml + tests: + - it: should work + asserts: + - equal: + path: data.foo_key + value: bar_input + """ + ), + "tests/general-values.yml": dedent( + """\ + input: bar_input + """ + ), + } + ) + + target = rule_runner.get_target(Address("tests", target_name="test")) + field_set = HelmUnitTestFieldSet.create(target) + + result = rule_runner.request(TestResult, [HelmUnitTestRequest.Batch("", (field_set,), None)]) + assert result.exit_code == 0 + + +def test_test_with_non_local_resource_file(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "src/helm/BUILD": "helm_chart(name='mychart')", + "src/helm/Chart.yaml": HELM_CHART_FILE, + "src/helm/templates/configmap.yaml": dedent( + """\ + apiVersion: v1 + kind: ConfigMap + metadata: + name: foo-config + data: + foo_key: {{ .Values.input }} + """ + ), + "src/helm/tests/BUILD": dedent( + """\ + helm_unittest_test( + name="test", + source="configmap_test.yaml", + dependencies=["//resources/data:values"] + ) + """ + ), + "src/helm/tests/configmap_test.yaml": dedent( + """\ + suite: test config map + templates: + - configmap.yaml + values: + - ../data/general-values.yml + tests: + - it: should work + asserts: + - equal: + path: data.foo_key + value: bar_input + """ + ), + "resources/data/BUILD": dedent( + """\ + resources(name="values", sources=["general-values.yml"]) + """ + ), + "resources/data/general-values.yml": dedent( + """\ + input: bar_input + """ + ), + } + ) + + source_roots = ["resources"] + rule_runner.set_options([f"--source-root-patterns={repr(source_roots)}"]) + target = rule_runner.get_target(Address("src/helm/tests", target_name="test")) + field_set = HelmUnitTestFieldSet.create(target) + + result = rule_runner.request(TestResult, [HelmUnitTestRequest.Batch("", (field_set,), None)]) + assert result.exit_code == 0 + + +def test_test_with_global_file(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "src/helm/BUILD": "helm_chart(name='mychart')", + "src/helm/Chart.yaml": HELM_CHART_FILE, + "src/helm/templates/configmap.yaml": dedent( + """\ + apiVersion: v1 + kind: ConfigMap + metadata: + name: foo-config + data: + foo_key: {{ .Values.input }} + """ + ), + "src/helm/tests/BUILD": dedent( + """\ + helm_unittest_test( + name="test", + source="configmap_test.yaml", + dependencies=["//files/data:values"] + ) + """ + ), + "src/helm/tests/configmap_test.yaml": dedent( + """\ + suite: test config map + templates: + - configmap.yaml + values: + - ../files/data/general-values.yml + tests: + - it: should work + asserts: + - equal: + path: data.foo_key + value: bar_input + """ + ), + "files/data/BUILD": dedent( + """\ + files(name="values", sources=["general-values.yml"]) + """ + ), + "files/data/general-values.yml": dedent( + """\ + input: bar_input + """ + ), + } + ) + + target = rule_runner.get_target(Address("src/helm/tests", target_name="test")) + field_set = HelmUnitTestFieldSet.create(target) + + result = rule_runner.request(TestResult, [HelmUnitTestRequest.Batch("", (field_set,), None)]) + assert result.exit_code == 0 + + +def test_test_with_relocated_file(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "src/helm/BUILD": "helm_chart(name='mychart')", + "src/helm/Chart.yaml": HELM_CHART_FILE, + "src/helm/templates/configmap.yaml": dedent( + """\ + apiVersion: v1 + kind: ConfigMap + metadata: + name: foo-config + data: + foo_key: {{ .Values.input }} + """ + ), + "src/helm/tests/BUILD": dedent( + """\ + helm_unittest_test( + name="test", + source="configmap_test.yaml", + dependencies=[":relocated"] + ) + + relocated_files( + name="relocated", + files_targets=["//files/data:values"], + src="files/data", + dest="tests" + ) + """ + ), + "src/helm/tests/configmap_test.yaml": dedent( + """\ + suite: test config map + templates: + - configmap.yaml + values: + - general-values.yml + tests: + - it: should work + asserts: + - equal: + path: data.foo_key + value: bar_input + """ + ), + "files/data/BUILD": dedent( + """\ + files(name="values", sources=["general-values.yml"]) + """ + ), + "files/data/general-values.yml": dedent( + """\ + input: bar_input + """ + ), + } + ) + + target = rule_runner.get_target(Address("src/helm/tests", target_name="test")) + field_set = HelmUnitTestFieldSet.create(target) + + result = rule_runner.request(TestResult, [HelmUnitTestRequest.Batch("", (field_set,), None)]) + assert result.exit_code == 0
Helm Unittest values and snapshot testing issue **Describe the bug** Helm unittesting doesn't work if [`values` section](https://github.com/quintush/helm-unittest/blob/master/DOCUMENT.md#test-job) is present in *_test.yaml instead of `set`. Another point is that if [snapshotting testing](https://github.com/quintush/helm-unittest#snapshot-testing) is used it seems that snapshots in `__snapshot__/` directory are ignored and any changes to tests or values in `set` section doesn't affect the tests run - it's still successful. **Pants version** 2.15.1 **OS** both **Additional info** 1. Consider the following setup ``` # deployment_test.yaml tests: - it: checks correct number of replicas asserts: - equal: path: spec.replicas value: 2 values: - general_values.yaml # IF COMMENT `values` section and uncomment `set` - it works fine. # set: # replicaCount: 2 # BUILD helm_unittest_tests( sources=[ "*_test.yaml", "general_values.yaml" ] ) # general_values.yaml replicaCount: 2 serviceAccount: name: opa ``` The error occurs: ``` pants test :: 13:07:38.10 [INFO] Completed: Running Helm unittest suite awesome/tests/deployment_test.yaml 13:07:38.11 [ERROR] Completed: Run Helm Unittest - awesome/tests/deployment_test.yaml - failed (exit code 1). ### Chart [ awesome ] awesome FAIL test deployment awesome/tests/deployment_test.yaml - checks correct number of replicas Error: open awesome/tests/general_values.yaml: no such file or directory ``` 2. Snapshot testing is also behaves not as expected. So, according to the documentation you need to generate `.snap` file and put it into `__snapshot__` directory. When test runs it compares the output value with the snapshot. While the manifest is generated during the run it doesn't seem to actually compare the result with the snapshot, because any changes to either to snapshot or to values in `set` section doesn't doesn't impact test results - it's always successful. Might be related - https://github.com/pantsbuild/pants/issues/16532 --- I believe both cases are might be related to the same issue and it's related to missing logic on how unittests are integrated into pants. Though I might missing some piece of documentation as well, in that case would appreciate any help :)
2023-06-07T07:38:24
pantsbuild/pants
19,271
pantsbuild__pants-19271
[ "18345" ]
362fe1b93505235fa07987b76b4742d732a63b3f
diff --git a/src/python/pants/backend/helm/target_types.py b/src/python/pants/backend/helm/target_types.py --- a/src/python/pants/backend/helm/target_types.py +++ b/src/python/pants/backend/helm/target_types.py @@ -8,6 +8,7 @@ from pants.backend.helm.resolve.remotes import ALL_DEFAULT_HELM_REGISTRIES from pants.base.deprecated import warn_or_error +from pants.base.glob_match_error_behavior import GlobMatchErrorBehavior from pants.core.goals.package import OutputPathField from pants.core.goals.test import TestTimeoutField from pants.engine.internals.native_engine import AddressInput @@ -444,6 +445,7 @@ class HelmDeploymentSkipCrdsField(BoolField): class HelmDeploymentSourcesField(MultipleSourcesField): default = ("*.yaml", "*.yml") expected_file_extensions = (".yaml", ".yml") + default_glob_match_error_behavior = GlobMatchErrorBehavior.ignore help = "Helm configuration files for a given deployment."
"Dependencies with docker_image targets" shorthand example doesn't find the image dependency **Describe the bug** https://www.pantsbuild.org/docs/helm-deployments#dependencies-with-docker_image-targets ``` $ cat src/deployment/BUILD #Overrides the `image` value for the chart using the target address for the first-party docker image. helm_deployment(dependencies=["src/chart"], sources=["common-values.yaml"], values={"image": "src/docker"}) $ ./pants dependencies src/deployment:deployment src/chart:chart $ cat src/deployment/BUILD #Overrides the `image` value for the chart using the target address for the first-party docker image. helm_deployment(dependencies=["src/chart"], sources=["common-values.yaml"], values={"image": "src/docker:docker"}) $ ./pants dependencies src/deployment:deployment src/chart:chart src/docker:docker ``` Note the need for `:docker`, which is not in the example. **Pants version** 2.16.0.dev7 **OS** Linux **Additional info** https://github.com/cburroughs/example-python/commit/1289d12c9a0c2620add1a6230fb985c8dad6d38f
2023-06-08T00:23:32
pantsbuild/pants
19,294
pantsbuild__pants-19294
[ "18618" ]
5a59c6024a1bbe434e881f85f1aec96d34a1cc9d
diff --git a/src/python/pants/backend/python/lint/isort/rules.py b/src/python/pants/backend/python/lint/isort/rules.py --- a/src/python/pants/backend/python/lint/isort/rules.py +++ b/src/python/pants/backend/python/lint/isort/rules.py @@ -14,9 +14,10 @@ from pants.core.util_rules.config_files import ConfigFiles, ConfigFilesRequest from pants.core.util_rules.partitions import PartitionerType from pants.engine.fs import Digest, MergeDigests -from pants.engine.process import ProcessResult +from pants.engine.process import ProcessExecutionFailure, ProcessResult from pants.engine.rules import Get, MultiGet, collect_rules, rule from pants.engine.target import FieldSet, Target +from pants.option.global_options import KeepSandboxes from pants.util.logging import LogLevel from pants.util.strutil import pluralize @@ -62,7 +63,9 @@ def generate_argv( @rule(desc="Format with isort", level=LogLevel.DEBUG) -async def isort_fmt(request: IsortRequest.Batch, isort: Isort) -> FmtResult: +async def isort_fmt( + request: IsortRequest.Batch, isort: Isort, keep_sandboxes: KeepSandboxes +) -> FmtResult: isort_pex_get = Get(VenvPex, PexRequest, isort.to_pex_request()) config_files_get = Get( ConfigFiles, ConfigFilesRequest, isort.config_request(request.snapshot.dirs) @@ -80,6 +83,7 @@ async def isort_fmt(request: IsortRequest.Batch, isort: Isort) -> FmtResult: Digest, MergeDigests((request.snapshot.digest, config_files.snapshot.digest)) ) + description = f"Run isort on {pluralize(len(request.files), 'file')}." result = await Get( ProcessResult, VenvPexProcess( @@ -87,10 +91,20 @@ async def isort_fmt(request: IsortRequest.Batch, isort: Isort) -> FmtResult: argv=generate_argv(request.files, isort, is_isort5=is_isort5), input_digest=input_digest, output_files=request.files, - description=f"Run isort on {pluralize(len(request.files), 'file')}.", + description=description, level=LogLevel.DEBUG, ), ) + + if b"Failed to pull configuration information" in result.stderr: + raise ProcessExecutionFailure( + -1, + result.stdout, + result.stderr, + description, + keep_sandboxes=keep_sandboxes, + ) + return await FmtResult.create(request, result, strip_chroot_path=True)
diff --git a/src/python/pants/backend/python/lint/isort/rules_integration_test.py b/src/python/pants/backend/python/lint/isort/rules_integration_test.py --- a/src/python/pants/backend/python/lint/isort/rules_integration_test.py +++ b/src/python/pants/backend/python/lint/isort/rules_integration_test.py @@ -3,6 +3,9 @@ from __future__ import annotations +import re +from textwrap import dedent + import pytest from pants.backend.python import target_types_rules @@ -15,6 +18,7 @@ from pants.core.util_rules import config_files, source_files from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest from pants.engine.addresses import Address +from pants.engine.internals.scheduler import ExecutionError from pants.engine.target import Target from pants.testutil.python_interpreter_selection import all_major_minor_python_versions from pants.testutil.rule_runner import QueryRule, RuleRunner @@ -137,6 +141,32 @@ def test_config_file(rule_runner: RuleRunner, path: str, extra_args: list[str]) assert fmt_result.did_change is True +def test_invalid_config_file(rule_runner: RuleRunner) -> None: + """Reference https://github.com/pantsbuild/pants/issues/18618.""" + + rule_runner.write_files( + { + ".isort.cfg": dedent( + """\ + [settings] + force_single_line = true + # invalid setting: + no_sections = this should be a bool, but isnt + """ + ), + "example.py": "from foo import bar, baz", + "BUILD": "python_sources()", + } + ) + tgt = rule_runner.get_target((Address("", relative_file_path="example.py"))) + with pytest.raises(ExecutionError) as isort_error: + run_isort(rule_runner, [tgt]) + assert any( + re.search(r"Failed to pull configuration information from .*\.isort\.cfg", arg) + for arg in isort_error.value.args + ) + + def test_passthrough_args(rule_runner: RuleRunner) -> None: rule_runner.write_files({"f.py": NEEDS_CONFIG_FILE, "BUILD": "python_sources(name='t')"}) tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py"))
Invalid isort configuration is silently ignored **Describe the bug** When an isort config file (`.isort.cfg` or `pyproject.toml`) is invalid, `isort` just emits a warning, and the whole invocation succeeds (exit code = 0). The invocation succeeding means `pants fmt ::` won't surface the warning, and thus people may be unintentionally running with a default isort configuration if they made a mistake while editing the configuration. NB. fixing this to be an error instead may be a breaking change, since `pants fmt ::` invocations with invalid config were previously succeeding and would start failing. Reproducer, configured to generate an invalid `.isort.cfg` by default, but can be switched to `pyproject.toml`: ```shell cat > pants.toml <<EOF [GLOBAL] pants_version = "2.15.0" backend_packages = [ "pants.backend.python", "pants.backend.python.lint.isort", ] [anonymous-telemetry] enabled = false EOF if true; then # switch to false to generate pyproject.toml cat > .isort.cfg <<EOF [settings] force_single_line = true # invalid setting: no_sections = this should be a bool, but isnt EOF else cat > pyproject.toml <<EOF [tool.isort] force_single_line = true # invalid setting: no_sections = "this should be a bool, but isnt" EOF fi cat > example.py <<EOF from foo import bar, baz EOF echo "BUG: this does _NOT_ fix example.py" pants fmt :: cat example.py echo "Running outside of pants:" pants export --resolve=isort dist/export/python/virtualenvs/isort/*/bin/isort . ``` Running `bash run.sh` gives output: ``` BUG: this does _NOT_ fix example.py 09:12:01.84 [INFO] Initializing scheduler... 09:12:02.27 [INFO] Scheduler initialized. from foo import bar, baz ``` ``` Running outside of pants: Wrote mutable virtualenv for isort (using Python 3.7.13) to dist/export/python/virtualenvs/isort /private/var/folders/sv/vd266m4d4lvctgs2wpnhjs9w0000gn/T/tmp.0BEDipYZ/dist/export/python/virtualenvs/isort/3.7.13/lib/python3.7/site-packages/isort/settings.py:771: UserWarning: Failed to pull configuration information from /private/var/folders/sv/vd266m4d4lvctgs2wpnhjs9w0000gn/T/tmp.0BEDipYZ/.isort.cfg warn(f"Failed to pull configuration information from {potential_config_file}") Skipped 2 files ``` In particular, note: - the `example.py` isn't changed: it _should_ become `from foo import bar` `from foo import baz` on separate lines due to `force_single_line = true` - running isort directly gives a `Failed to pull configuration information from ...` _warning_ **Pants version** 2.15.0 **OS** macOS **Additional info** N/A
In general we should be surfacing warnings from any process, I think. Certainly from any linter.
2023-06-11T18:55:11
pantsbuild/pants
19,296
pantsbuild__pants-19296
[ "17805" ]
670fb96b38e612d382466a435862242ae686bc05
diff --git a/src/python/pants/backend/python/goals/tailor.py b/src/python/pants/backend/python/goals/tailor.py --- a/src/python/pants/backend/python/goals/tailor.py +++ b/src/python/pants/backend/python/goals/tailor.py @@ -13,6 +13,9 @@ from pants.backend.python.dependency_inference.module_mapper import module_from_stripped_path from pants.backend.python.macros.pipenv_requirements import parse_pipenv_requirements from pants.backend.python.macros.poetry_requirements import PyProjectToml, parse_pyproject_toml +from pants.backend.python.macros.python_requirements import ( + parse_pyproject_toml as parse_pep621_pyproject_toml, +) from pants.backend.python.subsystems.setup import PythonSetup from pants.backend.python.target_types import ( PexBinary, @@ -200,7 +203,7 @@ def add_req_targets(files: Iterable[FileContent], alias: str, target_name: str) path, name = os.path.split(fp) try: - validate(fp, contents[fp], alias) + validate(fp, contents[fp], alias, target_name) except Exception as e: logger.warning( f"An error occurred when validating `{fp}`: {e}.\n\n" @@ -225,8 +228,10 @@ def add_req_targets(files: Iterable[FileContent], alias: str, target_name: str) ) ) - def validate(path: str, contents: bytes, alias: str) -> None: + def validate(path: str, contents: bytes, alias: str, target_name: str) -> None: if alias == "python_requirements": + if path.endswith("pyproject.toml"): + return validate_pep621_requirements(path, contents) return validate_python_requirements(path, contents) elif alias == "pipenv_requirements": return validate_pipenv_requirements(contents) @@ -237,6 +242,9 @@ def validate_python_requirements(path: str, contents: bytes) -> None: for _ in parse_requirements_file(contents.decode(), rel_path=path): pass + def validate_pep621_requirements(path: str, contents: bytes) -> None: + list(parse_pep621_pyproject_toml(contents.decode(), rel_path=path)) + def validate_pipenv_requirements(contents: bytes) -> None: parse_pipenv_requirements(contents) @@ -252,6 +260,21 @@ def validate_poetry_requirements(contents: bytes) -> None: "poetry", ) + def pyproject_toml_has_pep621(fc) -> bool: + try: + return ( + len(list(parse_pep621_pyproject_toml(fc.content.decode(), rel_path=fc.path))) + > 0 + ) + except Exception: + return False + + add_req_targets( + {fc for fc in all_pyproject_toml_contents if pyproject_toml_has_pep621(fc)}, + "python_requirements", + "reqs", + ) + if python_setup.tailor_pex_binary_targets: # Find binary targets.
diff --git a/src/python/pants/backend/python/goals/tailor_test.py b/src/python/pants/backend/python/goals/tailor_test.py --- a/src/python/pants/backend/python/goals/tailor_test.py +++ b/src/python/pants/backend/python/goals/tailor_test.py @@ -69,6 +69,15 @@ def test_find_putative_targets(rule_runner: RuleRunner) -> None: "3rdparty/Pipfile.lock": "{}", "3rdparty/pyproject.toml": "[tool.poetry]", "3rdparty/requirements-test.txt": "", + "pep621/pyproject.toml": textwrap.dedent( + """\ + [project] + dependencies = [ + "ansicolors>=1.18.0", + ] + """ + ), + "pep621/requirements.txt": "", # requirements in same dir as pep621 pyproject.toml causes conflict for name "already_owned/requirements.txt": "", "already_owned/Pipfile.lock": "", "already_owned/pyproject.toml": "[tool.poetry]", @@ -92,7 +101,14 @@ def test_find_putative_targets(rule_runner: RuleRunner) -> None: PutativeTargets, [ PutativePythonTargetsRequest( - ("3rdparty", "already_owned", "no_match", "src/python/foo", "src/python/foo/bar") + ( + "3rdparty", + "already_owned", + "no_match", + "src/python/foo", + "src/python/foo/bar", + "pep621", + ) ), AllOwnedSources( [ @@ -127,6 +143,19 @@ def test_find_putative_targets(rule_runner: RuleRunner) -> None: triggering_sources=["3rdparty/requirements-test.txt"], kwargs={"source": "requirements-test.txt"}, ), + PutativeTarget.for_target_type( + PythonRequirementsTargetGenerator, + path="pep621", + name="reqs", + triggering_sources=["pep621/pyproject.toml"], + kwargs={"source": "pyproject.toml"}, + ), + PutativeTarget.for_target_type( + PythonRequirementsTargetGenerator, + path="pep621", + name="reqs", + triggering_sources=["pep621/requirements.txt"], + ), PutativeTarget.for_target_type( PythonSourcesGeneratorTarget, "src/python/foo", None, ["__init__.py"] ),
Hook up python_requirements and pyproject.toml to tailor **Is your feature request related to a problem? Please describe.** PR #16932 added a PEP 621 parser for `python_requirement`s coming from a `pyproject.toml` file. At the moment, users must explicitly give the source as `pyproject.toml` since there's only logic to search for `requirements.txt` files as the source. In the PR, @Eric-Arellano [suggested](https://github.com/pantsbuild/pants/pull/16932#pullrequestreview-1199652866) that I open an issue to track automatically adding `pyproject.toml` as the source of the `python_requirements` target when it makes sense to do so. **Describe the solution you'd like** If I specify a `python_requirements` target, and there is no `requirements.txt` file present, I would like pantsbuild to automatically add `pyproject.toml` as the source file, presuming one exists. **Describe alternatives you've considered** The alternative, which works currently, is to manually add `pyproject.toml` as the `source.
Thanks! Specifically, I recommend we hook this up with `tailor` here: https://github.com/pantsbuild/pants/blob/2d8f1e34fee52aec7437c21da425eeb67d17306d/src/python/pants/backend/python/goals/tailor.py#L156-L225 I think the default `source` field for `python_requirements` is good, and in fact we can't set the default to be A or B. It has to be one value. Help definitely appreciated if you're interested in working on this :)
2023-06-12T03:57:18
pantsbuild/pants
19,302
pantsbuild__pants-19302
[ "17934" ]
2910fa60d0d88b53a6c7ca064862bc6d763fd49e
diff --git a/src/python/pants/backend/helm/subsystems/helm.py b/src/python/pants/backend/helm/subsystems/helm.py --- a/src/python/pants/backend/helm/subsystems/helm.py +++ b/src/python/pants/backend/helm/subsystems/helm.py @@ -23,6 +23,7 @@ _VALID_PASSTHROUGH_FLAGS = [ "--atomic", "--cleanup-on-fail", + "--create-namespace", "--debug", "--dry-run", "--force", diff --git a/src/python/pants/backend/helm/target_types.py b/src/python/pants/backend/helm/target_types.py --- a/src/python/pants/backend/helm/target_types.py +++ b/src/python/pants/backend/helm/target_types.py @@ -5,9 +5,10 @@ import logging from dataclasses import dataclass +from typing import Mapping from pants.backend.helm.resolve.remotes import ALL_DEFAULT_HELM_REGISTRIES -from pants.base.deprecated import warn_or_error +from pants.base.deprecated import deprecated, warn_or_error from pants.base.glob_match_error_behavior import GlobMatchErrorBehavior from pants.core.goals.package import OutputPathField from pants.core.goals.test import TestTimeoutField @@ -38,6 +39,7 @@ generate_multiple_sources_field_help_message, ) from pants.util.docutil import bin_name +from pants.util.memo import memoized_method from pants.util.strutil import help_text, softwrap from pants.util.value_interpolation import InterpolationContext, InterpolationError @@ -429,7 +431,7 @@ class HelmDeploymentReleaseNameField(StringField): class HelmDeploymentNamespaceField(StringField): alias = "namespace" - help = "Kubernetes namespace for the given deployment." + help = help_text("""Kubernetes namespace for the given deployment.""") class HelmDeploymentDependenciesField(Dependencies): @@ -449,7 +451,7 @@ class HelmDeploymentSourcesField(MultipleSourcesField): help = "Helm configuration files for a given deployment." -class HelmDeploymentValuesField(DictStringToStringField): +class HelmDeploymentValuesField(DictStringToStringField, AsyncFieldMixin): alias = "values" required = False help = help_text( @@ -472,7 +474,7 @@ class HelmDeploymentValuesField(DictStringToStringField): ``` helm_deployment( values={ - "configmap.deployedAt": "{env.DEPLOY_TIME}", + "configmap.deployedAt": f"{env('DEPLOY_TIME')}", }, ) ``` @@ -482,12 +484,56 @@ class HelmDeploymentValuesField(DictStringToStringField): """ ) + @memoized_method + @deprecated("2.19.0.dev0", start_version="2.18.0.dev0") + def format_with( + self, interpolation_context: InterpolationContext, *, ignore_missing: bool = False + ) -> dict[str, str]: + source = InterpolationContext.TextSource( + self.address, + target_alias=HelmDeploymentTarget.alias, + field_alias=HelmDeploymentValuesField.alias, + ) + + def format_value(text: str) -> str | None: + try: + return interpolation_context.format( + text, + source=source, + ) + except InterpolationError as err: + if ignore_missing: + return None + raise err + + result = {} + default_curr_value: dict[str, str] = {} + current_value: Mapping[str, str] = self.value or default_curr_value + for key, value in current_value.items(): + formatted_value = format_value(value) + if formatted_value is not None: + result[key] = formatted_value + + if result != current_value: + warn_or_error( + "2.19.0.dev0", + "Using the {env.VAR_NAME} interpolation syntax", + "Use the new `f\"prefix-{env('VAR_NAME')}\" syntax for interpolating values from environment variables.", + start_version="2.18.0.dev0", + ) + + return result + class HelmDeploymentCreateNamespaceField(BoolField): alias = "create_namespace" default = False help = "If true, the namespace will be created if it doesn't exist." + removal_version = "2.19.0.dev0" + # TODO This causes and error in the parser as it believes it is using it as the `removal_version` attribute. + # removal_hint = "Use the passthrough argument `--create-namespace` instead." + class HelmDeploymentNoHooksField(BoolField): alias = "no_hooks" @@ -563,33 +609,13 @@ class HelmDeploymentFieldSet(FieldSet): post_renderers: HelmDeploymentPostRenderersField enable_dns: HelmDeploymentEnableDNSField + @deprecated( + "2.19.0.dev0", "Use `field_set.values.format_with()` instead.", start_version="2.18.0.dev0" + ) def format_values( self, interpolation_context: InterpolationContext, *, ignore_missing: bool = False ) -> dict[str, str]: - source = InterpolationContext.TextSource( - self.address, - target_alias=HelmDeploymentTarget.alias, - field_alias=HelmDeploymentValuesField.alias, - ) - - def format_value(text: str) -> str | None: - try: - return interpolation_context.format( - text, - source=source, - ) - except InterpolationError as err: - if ignore_missing: - return None - raise err - - result = {} - for key, value in (self.values.value or {}).items(): - formatted_value = format_value(value) - if formatted_value is not None: - result[key] = formatted_value - - return result + return self.values.format_with(interpolation_context, ignore_missing=ignore_missing) class AllHelmDeploymentTargets(Targets): diff --git a/src/python/pants/backend/helm/util_rules/renderer.py b/src/python/pants/backend/helm/util_rules/renderer.py --- a/src/python/pants/backend/helm/util_rules/renderer.py +++ b/src/python/pants/backend/helm/util_rules/renderer.py @@ -305,14 +305,16 @@ async def setup_render_helm_deployment_process( merged_digests = await Get(Digest, MergeDigests(input_digests)) + # Calculate values that may depend on the interpolation context interpolation_context = await _build_interpolation_context(helm_subsystem) + is_render_cmd = request.cmd == HelmDeploymentCmd.RENDER release_name = ( request.field_set.release_name.value or request.field_set.address.target_name.replace("_", "-") ) - inline_values = request.field_set.format_values( - interpolation_context, ignore_missing=request.cmd == HelmDeploymentCmd.RENDER + inline_values = request.field_set.values.format_with( + interpolation_context, ignore_missing=is_render_cmd ) def maybe_escape_string_value(value: str) -> str: @@ -328,6 +330,11 @@ def maybe_escape_string_value(value: str) -> str: if request.post_renderer else ProcessCacheScope.SUCCESSFUL ) + + extra_args = list(request.extra_argv) + if "--create-namespace" not in extra_args and request.field_set.create_namespace.value: + extra_args.append("--create-namespace") + process = HelmProcess( argv=[ request.cmd.value, @@ -343,7 +350,6 @@ def maybe_escape_string_value(value: str) -> str: if request.field_set.namespace.value else () ), - *(("--create-namespace",) if request.field_set.create_namespace.value else ()), *(("--skip-crds",) if request.field_set.skip_crds.value else ()), *(("--no-hooks",) if request.field_set.no_hooks.value else ()), *(("--output-dir", output_dir) if output_dir else ()), @@ -362,7 +368,7 @@ def maybe_escape_string_value(value: str) -> str: if inline_values else () ), - *request.extra_argv, + *extra_args, ], extra_env=env, extra_immutable_input_digests=immutable_input_digests,
diff --git a/src/python/pants/backend/helm/goals/deploy_test.py b/src/python/pants/backend/helm/goals/deploy_test.py --- a/src/python/pants/backend/helm/goals/deploy_test.py +++ b/src/python/pants/backend/helm/goals/deploy_test.py @@ -67,8 +67,7 @@ def test_run_helm_deploy(rule_runner: RuleRunner) -> None: helm_deployment( name="foo", description="Foo deployment", - namespace="uat", - create_namespace=True, + namespace=f"uat-{env('NS_SUFFIX')}", skip_crds=True, no_hooks=True, dependencies=["//src/chart", "//src/docker/myimage"], @@ -77,7 +76,7 @@ def test_run_helm_deploy(rule_runner: RuleRunner) -> None: "key": "foo", "amount": "300", "long_string": "This is a long string", - "build_number": "{env.BUILD_NUMBER}", + "build_number": f"{env('BUILD_NUMBER')}", }, timeout=150, ) @@ -105,6 +104,7 @@ def test_run_helm_deploy(rule_runner: RuleRunner) -> None: ) expected_build_number = "34" + expected_ns_suffix = "quxx" expected_value_files_order = [ "common.yaml", "bar.yaml", @@ -116,14 +116,13 @@ def test_run_helm_deploy(rule_runner: RuleRunner) -> None: "subdir/last.yaml", ] - extra_env_vars = ["BUILD_NUMBER"] - deploy_args = ["--kubeconfig", "./kubeconfig"] + deploy_args = ["--kubeconfig", "./kubeconfig", "--create-namespace"] deploy_process = _run_deployment( rule_runner, "src/deployment", "foo", - args=[f"--helm-args={repr(deploy_args)}", f"--helm-extra-env-vars={repr(extra_env_vars)}"], - env={"BUILD_NUMBER": expected_build_number}, + args=[f"--helm-args={repr(deploy_args)}"], + env={"BUILD_NUMBER": expected_build_number, "NS_SUFFIX": expected_ns_suffix}, ) helm = rule_runner.request(HelmBinary, []) @@ -137,8 +136,7 @@ def test_run_helm_deploy(rule_runner: RuleRunner) -> None: "--description", '"Foo deployment"', "--namespace", - "uat", - "--create-namespace", + f"uat-{expected_ns_suffix}", "--skip-crds", "--no-hooks", "--post-renderer", @@ -160,6 +158,7 @@ def test_run_helm_deploy(rule_runner: RuleRunner) -> None: "150s", "--kubeconfig", "./kubeconfig", + "--create-namespace", )
support some sort of interpolation or dynamic generation of helm deployment namespace **Is your feature request related to a problem? Please describe.** We have some shared environments like `qa` or `stage` where we generally would expect fixed namespaces to exist in k8s. However, in `dev` we have both "shared" environments (team A deploys service foo from CI and team B expects to be able to integrate against it) and "playground" style namespaces like `devname-tmp-trying-out-deploying-with-pants`. I'd like some way of deploying a cool new service to a "playground/personal" namespace, show it to another engineer who can do the same without conflict, while still having defined in pants the Official Namespace for CI/production. **Describe the solution you'd like** Some sort of string interpolation or other environmental variable injection to `helm_deployment.namespace` **Describe alternatives you've considered** * passing `-- --namespace=mynamesapce` which results in `InvalidHelmPassthroughArgs` * Settings kube contexts as described in https://www.pantsbuild.org/docs/helm-deployments#deploying This works great for a single chart, but has fricting when working on multiple applications since you need to either keep track of the current active context as you twiddle the namespaces, or (outside of pants in bash or whatnot) manage target:namespace mappings. **Additional context** New to both helm and the pants integration, but it is very spiffy!
`env()` isn't exactly what the ticket is asking for, but I think that helps reduce the toe stepping problem. I"m not sure if the original interpolation request is more generally useful in helm-land. I think this should be possible and easy to implement, it's something that could not just be useful when combined with the `create_namespace=True` setting, but also in CI cases in which the name of the namespace could depend on the value of an environment variable. Something that I'm having in my mind on how to support this is something like: ```python helm_deployment( namespace="prefix-{env.NAMESPACE_SUFFIX}" ) ``` Is that the same you were thinking of or there is a different approach that could work better?
2023-06-13T10:05:02
pantsbuild/pants
19,315
pantsbuild__pants-19315
[ "15293" ]
b865f15d9a75cc7b197a5d1f49b4d80b7ed768f0
diff --git a/src/python/pants/backend/python/util_rules/pex.py b/src/python/pants/backend/python/util_rules/pex.py --- a/src/python/pants/backend/python/util_rules/pex.py +++ b/src/python/pants/backend/python/util_rules/pex.py @@ -1030,6 +1030,7 @@ async def create_venv_pex( additional_args=pex_request.additional_args + ( "--venv", + "prepend", "--seed", "verbose", pex_environment.venv_site_packages_copies_option(
Failure to running requirement's binary scripts using subprocess.run or os.system or ... (FileNotFoundError: [Errno 2] No such file or directory: '...') **Bug description** I believe this issue is very similar to the https://github.com/pantsbuild/pants/issues/12651 issue. Consider the following example: ``` . ├── BUILD ├── main.py ├── pants.toml └── test_main.py ``` ```toml # pants.toml [GLOBAL] pants_version = '2.10.0' backend_packages = ['pants.backend.python'] ``` ```starlark # BUILD python_requirement(name='python_requirement', requirements=['cowsay']) python_sources(name='python_sources') python_tests(name='python_tests') ``` ```python # main.py import subprocess import cowsay def cowsay_hello_using_subprocess(): subprocess.run(['cowsay', 'hello']) def cowsay_hello_using_module(): cowsay.cow('hello') ``` ```python # test_main.py import main def test_cowsay_hello_using_subprocess(): main.cowsay_hello_using_subprocess() def test_cowsay_hello_using_module(): main.cowsay_hello_using_module() ``` Running the `./pants test :python_tests` results `1 failed, 1 passed`. The `test_cowsay_hello_using_subprocess` test fails: ```FileNotFoundError: [Errno 2] No such file or directory: 'cowsay'``` Actually, a similar issue occurred if we define `pex_binary` for the source code. But, thanks to https://github.com/pantsbuild/pants/issues/12651, using `execution_mode='venv'` solves the issue there. In my opinion, there should be a similar solution for the intermediate pex files created for other goals and targets. Am I thinking right? **Pants version**: 2.10.0 **OS**: Ubuntu 20.04.3 LTS
> In my opinion, there should be a similar solution for the intermediate pex files created for other goals and targets. Am I thinking right? I think so. That would just mean changing `"--venv"` here to `"--venv", "prepend"` (or "append"): https://github.com/pantsbuild/pants/blob/000be2f3aa40ae1545f2dd70b3517298595b9aaf/src/python/pants/backend/python/util_rules/pex.py#L772-L785 I can't think of any likely trouble this may cause; so it probably could just be added with no ability to toggle needed. I am also interested in this. We currently have python tests that rely on scripts from 3rdparty deps being on the path. @mpcusack-color do you want to try tackling the suggested change above? My current workaround is using `[join(sys.prefix, 'bin', 'command')]` inside `subprocess.run`. The problem remains if the sub-process uses sub-process too (but it works most of the time).
2023-06-15T00:23:02
pantsbuild/pants
19,344
pantsbuild__pants-19344
[ "19338" ]
c7b6187dfa5baa1f6aa23cc6c60de57094673bbf
diff --git a/src/python/pants/backend/docker/registries.py b/src/python/pants/backend/docker/registries.py --- a/src/python/pants/backend/docker/registries.py +++ b/src/python/pants/backend/docker/registries.py @@ -8,6 +8,7 @@ from pants.option.parser import Parser from pants.util.frozendict import FrozenDict +from pants.util.strutil import softwrap ALL_DEFAULT_REGISTRIES = "<all default registries>" @@ -24,6 +25,18 @@ def __init__(self, message): ) +class DockerRegistryAddressCollisionError(DockerRegistryError): + def __init__(self, first, second): + message = softwrap( + f""" + Duplicated docker registry address for aliases: {first.alias}, {second.alias}. + Each registry `address` in `[docker].registries` must be unique. + """ + ) + + super().__init__(message) + + @dataclass(frozen=True) class DockerRegistryOptions: address: str @@ -49,6 +62,9 @@ def from_dict(cls, alias: str, d: dict[str, Any]) -> DockerRegistryOptions: ) def register(self, registries: dict[str, DockerRegistryOptions]) -> None: + if self.address in registries: + collision = registries[self.address] + raise DockerRegistryAddressCollisionError(collision, self) registries[self.address] = self if self.alias: registries[f"@{self.alias}"] = self
diff --git a/src/python/pants/backend/docker/registries_test.py b/src/python/pants/backend/docker/registries_test.py --- a/src/python/pants/backend/docker/registries_test.py +++ b/src/python/pants/backend/docker/registries_test.py @@ -5,6 +5,7 @@ from pants.backend.docker.registries import ( DockerRegistries, + DockerRegistryAddressCollisionError, DockerRegistryOptions, DockerRegistryOptionsNotFoundError, ) @@ -96,3 +97,15 @@ def test_repository() -> None: ) (reg1,) = registries.get("@reg1") assert reg1.repository == "{name}/foo" + + +def test_registries_must_be_unique() -> None: + with pytest.raises(DockerRegistryAddressCollisionError) as e: + DockerRegistries.from_dict( + { + "reg1": {"address": "mydomain:port"}, + "reg2": {"address": "mydomain:port"}, + } + ) + + assert e.match("Duplicated docker registry address for aliases: reg1, reg2.")
Allow multiple registry configurations with the same address **Is your feature request related to a problem? Please describe.** I am pushing images to a central AWS account, the registry address is the same for all repositories in the account: $ACCOUNT_ID.dkr.ecr.eu-west-1.amazonaws.com. I have some repositories that engineers can push to directly, and others that limit writes to the CI principals. For example, I have a docker image that we use as an environment for some build steps. I would like to build this image in CI and make it available to engineers, but they should not be able to push new versions. **Describe the solution you'd like** I would like to have two registry configurations, one exclusively for CI and one for tinkering, pointing to the same address. That allows me to mark some repositories as `skip_push` in pants.toml, but enable push from pants.ci.toml **Describe alternatives you've considered** I can just mark each image as skip_push and then push them manually from the CI host, but it's ungainly. I could set up a DNS name for the protected registry so that they're disambiguated. I'm probably going to add a tag to the targets that should only run on CI and disable them in pants.toml **Additional context** There's a repo [here](https://github.com/bobthemighty/pants-docker-registry-collision) showing the problem, from what I can tell, the addresses collide because they're used to match the registry with tags [here](https://github.com/pantsbuild/pants/blob/main/src/python/pants/backend/docker/goals/publish.py#L87) in the publish goal.
I'm unsure this *is* a bug. I think my mental model was wrong here. In the sample repo, the two toml entries clearly point to the same actual registry. I'm trying to use the "registry" as an arbitrary group of docker targets, but idiomatically I think that should be a target tag. With my proposal, the end user will still build the unpushed images locally with `pants package ::`, which clearly isn't what I want. I think this might be better handled with an error from the config validator to assert that registry addresses must be unique, and maybe a helpful hint in the docs about target selection. I'm happy to make that change with some guidance on warnings vs errors for breaking changes. > I'm happy to make that change with some guidance on warnings vs errors for breaking changes. Awesome. Good points. To solve this by actively rejecting duplicated registry addresses in the configuration works for me. I think we can safely error in this case as if there are users out there with duplicated addresses in their configuration, they're broken any way.
2023-06-17T10:52:34
pantsbuild/pants
19,366
pantsbuild__pants-19366
[ "19348" ]
b6ec890797088bc974404125ffcf2a580f0be99a
diff --git a/src/python/pants/backend/python/goals/pytest_runner.py b/src/python/pants/backend/python/goals/pytest_runner.py --- a/src/python/pants/backend/python/goals/pytest_runner.py +++ b/src/python/pants/backend/python/goals/pytest_runner.py @@ -29,8 +29,9 @@ PythonLockfileMetadataV2, PythonLockfileMetadataV3, ) -from pants.backend.python.util_rules.pex import Pex, PexRequest, VenvPex, VenvPexProcess +from pants.backend.python.util_rules.pex import Pex, PexRequest, ReqStrings, VenvPex, VenvPexProcess from pants.backend.python.util_rules.pex_from_targets import RequirementsPexRequest +from pants.backend.python.util_rules.pex_requirements import PexRequirements from pants.backend.python.util_rules.python_sources import ( PythonSourceFiles, PythonSourceFilesRequest, @@ -217,7 +218,8 @@ def _count_pytest_tests(contents: DigestContents) -> int: async def validate_pytest_cov_included(_pytest: PyTest): if _pytest.requirements: # We'll only be using this subset of the lockfile. - requirements = {PipRequirement.parse(req) for req in _pytest.requirements} + req_strings = (await Get(ReqStrings, PexRequirements(_pytest.requirements))).req_strings + requirements = {PipRequirement.parse(req_string) for req_string in req_strings} else: # We'll be using the entire lockfile. lockfile_metadata = await get_lockfile_metadata(_pytest)
diff --git a/src/python/pants/backend/python/goals/pytest_runner_test.py b/src/python/pants/backend/python/goals/pytest_runner_test.py --- a/src/python/pants/backend/python/goals/pytest_runner_test.py +++ b/src/python/pants/backend/python/goals/pytest_runner_test.py @@ -1,8 +1,30 @@ # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). -from pants.backend.python.goals.pytest_runner import _count_pytest_tests +from __future__ import annotations + +import pytest + +from pants.backend.python.goals.pytest_runner import ( + _count_pytest_tests, + validate_pytest_cov_included, +) +from pants.backend.python.pip_requirement import PipRequirement +from pants.backend.python.subsystems.pytest import PyTest +from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints +from pants.backend.python.util_rules.lockfile_metadata import PythonLockfileMetadataV3 +from pants.backend.python.util_rules.pex import ReqStrings +from pants.backend.python.util_rules.pex_requirements import ( + LoadedLockfile, + LoadedLockfileRequest, + Lockfile, + PexRequirements, + Resolve, +) from pants.engine.fs import DigestContents, FileContent +from pants.engine.internals.native_engine import EMPTY_DIGEST +from pants.testutil.option_util import create_subsystem +from pants.testutil.rule_runner import MockGet, run_rule_with_mocks EXAMPLE_TEST1 = b""" def test_foo(): @@ -54,3 +76,56 @@ def test_count_pytest_tests_multiple() -> None: ) test_count = _count_pytest_tests(digest_contents) assert test_count == 3 + + [email protected]("entire_lockfile", [False, True]) +def test_validate_pytest_cov_included(entire_lockfile: bool) -> None: + def validate(reqs: list[str]) -> None: + if entire_lockfile: + tool = create_subsystem( + PyTest, + lockfile="dummy.lock", + install_from_resolve="dummy_resolve", + requirements=[], + ) + else: + tool = create_subsystem( + PyTest, + lockfile="dummy.lock", + install_from_resolve="dummy_resolve", + requirements=reqs, + ) + lockfile = Lockfile("dummy_url", "dummy_description_of_origin", "dummy_resolve") + metadata = PythonLockfileMetadataV3( + valid_for_interpreter_constraints=InterpreterConstraints(), + requirements={PipRequirement.parse(req) for req in reqs}, + manylinux=None, + requirement_constraints=set(), + only_binary=set(), + no_binary=set(), + ) + loaded_lockfile = LoadedLockfile(EMPTY_DIGEST, "", metadata, 0, True, None, lockfile) + run_rule_with_mocks( + validate_pytest_cov_included, + rule_args=[tool], + mock_gets=[ + MockGet(ReqStrings, (PexRequirements,), lambda x: ReqStrings(tuple(reqs))), + MockGet(Lockfile, (Resolve,), lambda x: lockfile), + MockGet( + LoadedLockfile, + (LoadedLockfileRequest,), + lambda x: loaded_lockfile if x.lockfile == lockfile else None, + ), + ], + ) + + # Canonicalize project name. + validate(["PyTeST_cOV"]) + + with pytest.raises(ValueError) as exc: + validate([]) + assert "missing `pytest-cov`" in str(exc.value) + + with pytest.raises(ValueError) as exc: + validate(["custom-plugin"]) + assert "missing `pytest-cov`" in str(exc.value) diff --git a/src/python/pants/backend/python/subsystems/pytest_runner_test.py b/src/python/pants/backend/python/subsystems/pytest_runner_test.py deleted file mode 100644 --- a/src/python/pants/backend/python/subsystems/pytest_runner_test.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). -# Licensed under the Apache License, Version 2.0 (see LICENSE). - -from __future__ import annotations - -import pytest - -from pants.backend.python.goals.pytest_runner import validate_pytest_cov_included -from pants.backend.python.pip_requirement import PipRequirement -from pants.backend.python.subsystems.pytest import PyTest -from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints -from pants.backend.python.util_rules.lockfile_metadata import PythonLockfileMetadataV3 -from pants.backend.python.util_rules.pex_requirements import ( - LoadedLockfile, - LoadedLockfileRequest, - Lockfile, - Resolve, -) -from pants.engine.internals.native_engine import EMPTY_DIGEST -from pants.testutil.option_util import create_subsystem -from pants.testutil.rule_runner import MockGet, run_rule_with_mocks - - [email protected]("entire_lockfile", [False, True]) -def test_validate_pytest_cov_included(entire_lockfile: bool) -> None: - def validate(reqs: list[str]) -> None: - if entire_lockfile: - tool = create_subsystem( - PyTest, - lockfile="dummy.lock", - install_from_resolve="dummy_resolve", - requirements=[], - ) - else: - tool = create_subsystem( - PyTest, - lockfile="dummy.lock", - install_from_resolve="dummy_resolve", - requirements=reqs, - ) - lockfile = Lockfile("dummy_url", "dummy_description_of_origin", "dummy_resolve") - metadata = PythonLockfileMetadataV3( - valid_for_interpreter_constraints=InterpreterConstraints(), - requirements={PipRequirement.parse(req) for req in reqs}, - manylinux=None, - requirement_constraints=set(), - only_binary=set(), - no_binary=set(), - ) - loaded_lockfile = LoadedLockfile(EMPTY_DIGEST, "", metadata, 0, True, None, lockfile) - run_rule_with_mocks( - validate_pytest_cov_included, - rule_args=[tool], - mock_gets=[ - MockGet(Lockfile, (Resolve,), lambda x: lockfile), - MockGet( - LoadedLockfile, - (LoadedLockfileRequest,), - lambda x: loaded_lockfile if x.lockfile == lockfile else None, - ), - ], - ) - - # Canonicalize project name. - validate(["PyTeST_cOV"]) - - with pytest.raises(ValueError) as exc: - validate([]) - assert "missing `pytest-cov`" in str(exc.value) - - with pytest.raises(ValueError) as exc: - validate(["custom-plugin"]) - assert "missing `pytest-cov`" in str(exc.value)
Internal pants test with coverage option fails with requirements parse error **Describe the bug** I'm getting this error ValueError: Invalid requirement '//3rdparty/python:pytest': Parse error at "'//3rdpar'": Expected W:(0-9A-Za-z) running test with coverage ./pants test --test-use-coverage src/python/pants/backend/docker/: in the pants repo. If I comment out [this line](https://github.com/pantsbuild/pants/blob/d5812af250f13477588de610c5e59aeb56101eaf/pants.toml#L179), it works. **Pants version** Latest `main` as of about three days ago. **OS** MacOS **Additional info** Stack trace: ``` ./pants test --test-use-coverage src/python/pants/backend/docker/: There is no pantsd metadata at /Users/rhys.madigan/repos/pants/.pids/d54692e05ced/pantsd. 18:17:49.39 [INFO] waiting for pantsd to start... 18:17:49.60 [INFO] pantsd started 18:17:56.46 [INFO] Initializing scheduler... 18:18:07.55 [INFO] Scheduler initialized. 18:18:18.58 [ERROR] 1 Exception encountered: Engine traceback: in select .. in pants.core.goals.test.run_tests `test` goal Traceback (most recent call last): File "/Users/rhys.madigan/.cache/pants/pants_dev_deps/5709c1a054ca5899853199a432062f92bb7571eb.venv/lib/python3.9/site-packages/pkg_resources/_vendor/packaging/requirements.py", line 102, in __init__ req = REQUIREMENT.parseString(requirement_string) File "/Users/rhys.madigan/.cache/pants/pants_dev_deps/5709c1a054ca5899853199a432062f92bb7571eb.venv/lib/python3.9/site-packages/pkg_resources/_vendor/pyparsing/core.py", line 1141, in parse_string raise exc.with_traceback(None) pkg_resources._vendor.pyparsing.exceptions.ParseException: Expected W:(0-9A-Za-z), found '/' (at char 0), (line:1, col:1) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/rhys.madigan/repos/pants/src/python/pants/backend/python/pip_requirement.py", line 21, in parse return cls(pkg_resources.Requirement.parse(line)) File "/Users/rhys.madigan/.cache/pants/pants_dev_deps/5709c1a054ca5899853199a432062f92bb7571eb.venv/lib/python3.9/site-packages/pkg_resources/__init__.py", line 3147, in parse req, = parse_requirements(s) File "/Users/rhys.madigan/.cache/pants/pants_dev_deps/5709c1a054ca5899853199a432062f92bb7571eb.venv/lib/python3.9/site-packages/pkg_resources/__init__.py", line 3102, in __init__ super(Requirement, self).__init__(requirement_string) File "/Users/rhys.madigan/.cache/pants/pants_dev_deps/5709c1a054ca5899853199a432062f92bb7571eb.venv/lib/python3.9/site-packages/pkg_resources/_vendor/packaging/requirements.py", line 104, in __init__ raise InvalidRequirement( pkg_resources.extern.packaging.requirements.InvalidRequirement: Parse error at "'//3rdpar'": Expected W:(0-9A-Za-z) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/rhys.madigan/repos/pants/src/python/pants/engine/internals/selectors.py", line 626, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/rhys.madigan/repos/pants/src/python/pants/core/goals/test.py", line 889, in run_tests results = await MultiGet( File "/Users/rhys.madigan/repos/pants/src/python/pants/engine/internals/selectors.py", line 361, in MultiGet return await _MultiGet(tuple(__arg0)) File "/Users/rhys.madigan/repos/pants/src/python/pants/engine/internals/selectors.py", line 168, in __await__ result = yield self.gets File "/Users/rhys.madigan/repos/pants/src/python/pants/engine/internals/selectors.py", line 626, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/rhys.madigan/repos/pants/src/python/pants/backend/python/goals/pytest_runner.py", line 503, in run_python_tests setup = await Get( File "/Users/rhys.madigan/repos/pants/src/python/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File "/Users/rhys.madigan/repos/pants/src/python/pants/engine/internals/selectors.py", line 626, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File "/Users/rhys.madigan/repos/pants/src/python/pants/backend/python/goals/pytest_runner.py", line 373, in setup_pytest_for_target await validate_pytest_cov_included(pytest) File "/Users/rhys.madigan/repos/pants/src/python/pants/backend/python/goals/pytest_runner.py", line 220, in validate_pytest_cov_included requirements = {PipRequirement.parse(req) for req in _pytest.requirements} File "/Users/rhys.madigan/repos/pants/src/python/pants/backend/python/goals/pytest_runner.py", line 220, in <setcomp> requirements = {PipRequirement.parse(req) for req in _pytest.requirements} File "/Users/rhys.madigan/repos/pants/src/python/pants/backend/python/pip_requirement.py", line 49, in parse raise ValueError(f"Invalid requirement '{line}'{origin_str}: {e}") ValueError: Invalid requirement '//3rdparty/python:pytest': Parse error at "'//3rdpar'": Expected W:(0-9A-Za-z) ```
2023-06-22T16:41:03
pantsbuild/pants
19,413
pantsbuild__pants-19413
[ "19347" ]
25699f449caf6e73157026ccca5077682168d168
diff --git a/src/python/pants/backend/adhoc/target_types.py b/src/python/pants/backend/adhoc/target_types.py --- a/src/python/pants/backend/adhoc/target_types.py +++ b/src/python/pants/backend/adhoc/target_types.py @@ -82,9 +82,12 @@ class AdhocToolOutputDependenciesField(AdhocToolDependenciesField): alias: ClassVar[str] = "output_dependencies" help = help_text( - lambda: """ + lambda: f""" Any dependencies that need to be present (as transitive dependencies) whenever the outputs of this target are consumed (including as dependencies). + + See also `{AdhocToolExecutionDependenciesField.alias}` and + `{AdhocToolRunnableDependenciesField.alias}`. """ ) @@ -106,6 +109,9 @@ class AdhocToolExecutionDependenciesField(SpecialCasedDependencies): If this field is specified, dependencies from `{AdhocToolOutputDependenciesField.alias}` will not be added to the execution sandbox. + + See also `{AdhocToolOutputDependenciesField.alias}` and + `{AdhocToolRunnableDependenciesField.alias}`. """ ) @@ -117,7 +123,7 @@ class AdhocToolRunnableDependenciesField(SpecialCasedDependencies): help = help_text( lambda: f""" - The execution dependencies for this command. + The runnable dependencies for this command. Dependencies specified here are those required to exist on the `PATH` to make the command complete successfully (interpreters specified in a `#!` command, etc). Note that these diff --git a/src/python/pants/backend/shell/target_types.py b/src/python/pants/backend/shell/target_types.py --- a/src/python/pants/backend/shell/target_types.py +++ b/src/python/pants/backend/shell/target_types.py @@ -293,10 +293,38 @@ class ShellCommandExecutionDependenciesField(AdhocToolExecutionDependenciesField pass +class RunShellCommandExecutionDependenciesField(ShellCommandExecutionDependenciesField): + help = help_text( + lambda: f""" + The execution dependencies for this command. + + Dependencies specified here are those required to make the command complete successfully + (e.g. file inputs, packages compiled from other targets, etc), but NOT required to make + the outputs of the command useful. + + See also `{RunShellCommandRunnableDependenciesField.alias}`. + """ + ) + + class ShellCommandRunnableDependenciesField(AdhocToolRunnableDependenciesField): pass +class RunShellCommandRunnableDependenciesField(ShellCommandRunnableDependenciesField): + help = help_text( + lambda: f""" + The runnable dependencies for this command. + + Dependencies specified here are those required to exist on the `PATH` to make the command + complete successfully (interpreters specified in a `#!` command, etc). Note that these + dependencies will be made available on the `PATH` with the name of the target. + + See also `{RunShellCommandExecutionDependenciesField.alias}`. + """ + ) + + class ShellCommandSourcesField(MultipleSourcesField): # We solely register this field for codegen to work. alias = "_sources" @@ -400,8 +428,8 @@ class ShellCommandRunTarget(Target): alias = "run_shell_command" core_fields = ( *COMMON_TARGET_FIELDS, - ShellCommandExecutionDependenciesField, - ShellCommandRunnableDependenciesField, + RunShellCommandExecutionDependenciesField, + RunShellCommandRunnableDependenciesField, ShellCommandCommandField, RunShellCommandWorkdirField, )
run_shell_command - documentation page is confusing **Describe the bug** The [documentation page](https://www.pantsbuild.org/docs/reference-run_shell_command) for "run_shell_command" is a bit confusing. - The description for the `execution_dependencies` field and the `runnable_dependencies` field starts the same way. - The description for these fields refers to `output_dependencies`, which is not there. - There is a typo under `runnable_dependencies` - missing backtick in the last line. **Pants version** 2.16 **Additional info** I apologize if this is not the way to report issues in the documentation.
Thanks for reporting. This is the right place for doc issues!
2023-07-05T22:13:06
pantsbuild/pants
19,421
pantsbuild__pants-19421
[ "19347" ]
b11fb6a273ae8c9f9a4638e053c1aa414d180d22
diff --git a/src/python/pants/backend/adhoc/target_types.py b/src/python/pants/backend/adhoc/target_types.py --- a/src/python/pants/backend/adhoc/target_types.py +++ b/src/python/pants/backend/adhoc/target_types.py @@ -82,9 +82,12 @@ class AdhocToolOutputDependenciesField(AdhocToolDependenciesField): alias: ClassVar[str] = "output_dependencies" help = help_text( - lambda: """ + lambda: f""" Any dependencies that need to be present (as transitive dependencies) whenever the outputs of this target are consumed (including as dependencies). + + See also `{AdhocToolExecutionDependenciesField.alias}` and + `{AdhocToolRunnableDependenciesField.alias}`. """ ) @@ -106,6 +109,9 @@ class AdhocToolExecutionDependenciesField(SpecialCasedDependencies): If this field is specified, dependencies from `{AdhocToolOutputDependenciesField.alias}` will not be added to the execution sandbox. + + See also `{AdhocToolOutputDependenciesField.alias}` and + `{AdhocToolRunnableDependenciesField.alias}`. """ ) @@ -117,7 +123,7 @@ class AdhocToolRunnableDependenciesField(SpecialCasedDependencies): help = help_text( lambda: f""" - The execution dependencies for this command. + The runnable dependencies for this command. Dependencies specified here are those required to exist on the `PATH` to make the command complete successfully (interpreters specified in a `#!` command, etc). Note that these diff --git a/src/python/pants/backend/shell/target_types.py b/src/python/pants/backend/shell/target_types.py --- a/src/python/pants/backend/shell/target_types.py +++ b/src/python/pants/backend/shell/target_types.py @@ -293,10 +293,38 @@ class ShellCommandExecutionDependenciesField(AdhocToolExecutionDependenciesField pass +class RunShellCommandExecutionDependenciesField(ShellCommandExecutionDependenciesField): + help = help_text( + lambda: f""" + The execution dependencies for this command. + + Dependencies specified here are those required to make the command complete successfully + (e.g. file inputs, packages compiled from other targets, etc), but NOT required to make + the outputs of the command useful. + + See also `{RunShellCommandRunnableDependenciesField.alias}`. + """ + ) + + class ShellCommandRunnableDependenciesField(AdhocToolRunnableDependenciesField): pass +class RunShellCommandRunnableDependenciesField(ShellCommandRunnableDependenciesField): + help = help_text( + lambda: f""" + The runnable dependencies for this command. + + Dependencies specified here are those required to exist on the `PATH` to make the command + complete successfully (interpreters specified in a `#!` command, etc). Note that these + dependencies will be made available on the `PATH` with the name of the target. + + See also `{RunShellCommandExecutionDependenciesField.alias}`. + """ + ) + + class ShellCommandSourcesField(MultipleSourcesField): # We solely register this field for codegen to work. alias = "_sources" @@ -404,8 +432,8 @@ class ShellCommandRunTarget(Target): deprecated_alias_removal_version = "2.18.0.dev0" core_fields = ( *COMMON_TARGET_FIELDS, - ShellCommandExecutionDependenciesField, - ShellCommandRunnableDependenciesField, + RunShellCommandExecutionDependenciesField, + RunShellCommandRunnableDependenciesField, ShellCommandCommandField, RunShellCommandWorkdirField, )
run_shell_command - documentation page is confusing **Describe the bug** The [documentation page](https://www.pantsbuild.org/docs/reference-run_shell_command) for "run_shell_command" is a bit confusing. - The description for the `execution_dependencies` field and the `runnable_dependencies` field starts the same way. - The description for these fields refers to `output_dependencies`, which is not there. - There is a typo under `runnable_dependencies` - missing backtick in the last line. **Pants version** 2.16 **Additional info** I apologize if this is not the way to report issues in the documentation.
Thanks for reporting. This is the right place for doc issues!
2023-07-06T21:58:16
pantsbuild/pants
19,422
pantsbuild__pants-19422
[ "19347" ]
9dfb1e930b64096a71787475291183b85f012297
diff --git a/src/python/pants/backend/adhoc/target_types.py b/src/python/pants/backend/adhoc/target_types.py --- a/src/python/pants/backend/adhoc/target_types.py +++ b/src/python/pants/backend/adhoc/target_types.py @@ -90,6 +90,9 @@ class AdhocToolOutputDependenciesField(AdhocToolDependenciesField): To enable legacy use cases, if `{AdhocToolExecutionDependenciesField.alias}` is `None`, these dependencies will be materialized in the execution sandbox. This behavior is deprecated, and will be removed in version 2.17.0.dev0. + + See also `{AdhocToolExecutionDependenciesField.alias}` and + `{AdhocToolRunnableDependenciesField.alias}`. """ ) @@ -111,6 +114,9 @@ class AdhocToolExecutionDependenciesField(SpecialCasedDependencies): If this field is specified, dependencies from `{AdhocToolOutputDependenciesField.alias}` will not be added to the execution sandbox. + + See also `{AdhocToolOutputDependenciesField.alias}` and + `{AdhocToolRunnableDependenciesField.alias}`. """ ) @@ -122,7 +128,7 @@ class AdhocToolRunnableDependenciesField(SpecialCasedDependencies): help = help_text( lambda: f""" - The execution dependencies for this command. + The runnable dependencies for this command. Dependencies specified here are those required to exist on the `PATH` to make the command complete successfully (interpreters specified in a `#!` command, etc). Note that these diff --git a/src/python/pants/backend/shell/target_types.py b/src/python/pants/backend/shell/target_types.py --- a/src/python/pants/backend/shell/target_types.py +++ b/src/python/pants/backend/shell/target_types.py @@ -309,10 +309,38 @@ class ShellCommandExecutionDependenciesField(AdhocToolExecutionDependenciesField pass +class RunShellCommandExecutionDependenciesField(ShellCommandExecutionDependenciesField): + help = help_text( + lambda: f""" + The execution dependencies for this command. + + Dependencies specified here are those required to make the command complete successfully + (e.g. file inputs, packages compiled from other targets, etc), but NOT required to make + the outputs of the command useful. + + See also `{RunShellCommandRunnableDependenciesField.alias}`. + """ + ) + + class ShellCommandRunnableDependenciesField(AdhocToolRunnableDependenciesField): pass +class RunShellCommandRunnableDependenciesField(ShellCommandRunnableDependenciesField): + help = help_text( + lambda: f""" + The runnable dependencies for this command. + + Dependencies specified here are those required to exist on the `PATH` to make the command + complete successfully (interpreters specified in a `#!` command, etc). Note that these + dependencies will be made available on the `PATH` with the name of the target. + + See also `{RunShellCommandExecutionDependenciesField.alias}`. + """ + ) + + class ShellCommandSourcesField(MultipleSourcesField): # We solely register this field for codegen to work. alias = "_sources" @@ -421,8 +449,8 @@ class ShellCommandRunTarget(Target): deprecated_alias_removal_version = "2.18.0.dev0" core_fields = ( *COMMON_TARGET_FIELDS, - ShellCommandExecutionDependenciesField, - ShellCommandRunnableDependenciesField, + RunShellCommandExecutionDependenciesField, + RunShellCommandRunnableDependenciesField, ShellCommandCommandField, RunShellCommandWorkdirField, )
run_shell_command - documentation page is confusing **Describe the bug** The [documentation page](https://www.pantsbuild.org/docs/reference-run_shell_command) for "run_shell_command" is a bit confusing. - The description for the `execution_dependencies` field and the `runnable_dependencies` field starts the same way. - The description for these fields refers to `output_dependencies`, which is not there. - There is a typo under `runnable_dependencies` - missing backtick in the last line. **Pants version** 2.16 **Additional info** I apologize if this is not the way to report issues in the documentation.
Thanks for reporting. This is the right place for doc issues!
2023-07-06T22:07:00
pantsbuild/pants
19,437
pantsbuild__pants-19437
[ "19390" ]
21182f3187503f58c83406b59d88f741c6fc06c7
diff --git a/src/python/pants/backend/visibility/glob.py b/src/python/pants/backend/visibility/glob.py --- a/src/python/pants/backend/visibility/glob.py +++ b/src/python/pants/backend/visibility/glob.py @@ -225,9 +225,9 @@ def parse(cls: type[TargetGlob], spec: str | Mapping[str, Any], base: str) -> Ta raise ValueError(f"Target spec must not be empty. {spec!r}") return cls.create( # type: ignore[call-arg] - type_=spec_dict.get("type"), - name=spec_dict.get("name"), - path=spec_dict.get("path"), + type_=str(spec_dict["type"]) if "type" in spec_dict else None, + name=str(spec_dict["name"]) if "name" in spec_dict else None, + path=str(spec_dict["path"]) if "path" in spec_dict else None, base=base, tags=cls._parse_tags(spec_dict.get("tags")), )
diff --git a/src/python/pants/backend/visibility/rule_types_test.py b/src/python/pants/backend/visibility/rule_types_test.py --- a/src/python/pants/backend/visibility/rule_types_test.py +++ b/src/python/pants/backend/visibility/rule_types_test.py @@ -931,3 +931,24 @@ def test_single_rules_declaration_per_build_file(rule_runner: RuleRunner) -> Non rule_runner, "test", ) + + +def test_target_type_in_verbose_selector_issue_19390(rule_runner: RuleRunner) -> None: + """This test is logically a better fit in `./glob_test.py:test_target_glob_parse_spec` but I + want to avoid hard coding any assumptions regarding a target types representation in the BUILD + file (the `Registrar` type).""" + rule_runner.write_files( + { + "test/BUILD": dedent( + """ + target(name="test") + + __dependencies_rules__( + ({"type": files}, "*"), + ) + """ + ), + }, + ) + + assert_dependency_rules(rule_runner, "test")
Can not use target type in visibility rule selector. **Describe the bug** > the example given in the docs, {"type": python_sources}, but the parsing breaks with an error of "TypeError: decoding to str: need a bytes-like object, Registrar found", **Pants version** 2.17.0rc1 **OS** n/a **Additional info** https://pantsbuild.slack.com/archives/C046T6T9U/p1687953070098239
2023-07-08T20:22:57
pantsbuild/pants
19,446
pantsbuild__pants-19446
[ "19158" ]
1b14f2240d188489482de8b9b00c31a7f726b813
diff --git a/src/python/pants/engine/internals/defaults.py b/src/python/pants/engine/internals/defaults.py --- a/src/python/pants/engine/internals/defaults.py +++ b/src/python/pants/engine/internals/defaults.py @@ -114,7 +114,7 @@ def set_defaults( all: SetDefaultsValueT | None = None, extend: bool = False, ignore_unknown_fields: bool = False, - **kwargs, + ignore_unknown_targets: bool = False, ) -> None: defaults: dict[str, dict[str, Any]] = ( {} if not extend else {k: dict(v) for k, v in self.defaults.items()} @@ -125,10 +125,16 @@ def set_defaults( defaults, {tuple(self.registered_target_types.aliases): all}, ignore_unknown_fields=True, + ignore_unknown_targets=ignore_unknown_targets, ) for arg in args: - self._process_defaults(defaults, arg, ignore_unknown_fields=ignore_unknown_fields) + self._process_defaults( + defaults, + arg, + ignore_unknown_fields=ignore_unknown_fields, + ignore_unknown_targets=ignore_unknown_targets, + ) # Update with new defaults, dropping targets without any default values. for tgt, default in defaults.items(): @@ -148,6 +154,7 @@ def _process_defaults( defaults: dict[str, dict[str, Any]], targets_defaults: SetDefaultsT, ignore_unknown_fields: bool = False, + ignore_unknown_targets: bool = False, ): if not isinstance(targets_defaults, dict): raise ValueError( @@ -168,6 +175,8 @@ def _process_defaults( for target_alias in map(str, targets): if target_alias in types: target_type = types[target_alias] + elif ignore_unknown_targets: + continue else: raise ValueError(f"Unrecognized target type {target_alias} in {self.address}.") diff --git a/src/python/pants/engine/internals/parser.py b/src/python/pants/engine/internals/parser.py --- a/src/python/pants/engine/internals/parser.py +++ b/src/python/pants/engine/internals/parser.py @@ -199,10 +199,17 @@ def get_env(self, name: str, *args, **kwargs) -> Any: """ ) def set_defaults( - self, *args: SetDefaultsT, ignore_unknown_fields: bool = False, **kwargs + self, + *args: SetDefaultsT, + ignore_unknown_fields: bool = False, + ignore_unknown_targets: bool = False, + **kwargs, ) -> None: self.defaults.set_defaults( - *args, ignore_unknown_fields=self.is_bootstrap or ignore_unknown_fields, **kwargs + *args, + ignore_unknown_fields=self.is_bootstrap or ignore_unknown_fields, + ignore_unknown_targets=self.is_bootstrap or ignore_unknown_targets, + **kwargs, ) def set_dependents_rules(self, *args, **kwargs) -> None: @@ -498,6 +505,9 @@ def __init__(self, name: str) -> None: self.args: tuple[Any, ...] = () self.kwargs: dict[str, Any] = {} + def __hash__(self) -> int: + return hash(self.name) + def __call__(self, *args, **kwargs) -> _UnrecognizedSymbol: self.args = args self.kwargs = kwargs
diff --git a/src/python/pants/engine/internals/parser_test.py b/src/python/pants/engine/internals/parser_test.py --- a/src/python/pants/engine/internals/parser_test.py +++ b/src/python/pants/engine/internals/parser_test.py @@ -171,6 +171,28 @@ class TestField(StringField): TestField(raw_field, Address("")) +def test_unknown_target_for_defaults_during_bootstrap_issue_19445( + defaults_parser_state: BuildFileDefaultsParserState, +) -> None: + parser = Parser( + build_root="", + registered_target_types=RegisteredTargetTypes({}), + union_membership=UnionMembership({}), + object_aliases=BuildFileAliases(), + ignore_unrecognized_symbols=True, + ) + parser.parse( + "BUILD", + "__defaults__({'type_1': dict(), type_2: dict()})", + BuildFilePreludeSymbols.create({}, ()), + EnvironmentVars({}), + True, + defaults_parser_state, + dependents_rules=None, + dependencies_rules=None, + ) + + @pytest.mark.parametrize("symbol", ["a", "bad", "BAD", "a___b_c", "a231", "áç"]) def test_extract_symbol_from_name_error(symbol: str) -> None: assert _extract_symbol_from_name_error(NameError(f"name '{symbol}' is not defined")) == symbol
`__defaults__` silently allows-and-ignores fallthrough kwargs **Describe the bug** I was trying to do: ```python __defaults__(python_test=dict(environment="focal-docker")) ``` and getting frustrated it wasn't working. Turns out it just gets collected and ignored: https://github.com/pantsbuild/pants/blob/3ce90948d2dc49dd525ca4a10daeaba98068a8e0/src/python/pants/engine/internals/defaults.py#L117 **Pants version** `2.16.0rc2` **OS** N/A **Additional info** N/A
2023-07-11T03:08:08
pantsbuild/pants
19,455
pantsbuild__pants-19455
[ "18359" ]
9f49668dcfb3cc9ae877850d14e66dbe7045f3df
diff --git a/src/python/pants/backend/helm/dependency_inference/deployment.py b/src/python/pants/backend/helm/dependency_inference/deployment.py --- a/src/python/pants/backend/helm/dependency_inference/deployment.py +++ b/src/python/pants/backend/helm/dependency_inference/deployment.py @@ -21,10 +21,11 @@ RenderedHelmFiles, ) from pants.backend.helm.utils.yaml import FrozenYamlIndex, MutableYamlIndex +from pants.build_graph.address import MaybeAddress from pants.engine.addresses import Address from pants.engine.engine_aware import EngineAwareParameter, EngineAwareReturnType from pants.engine.fs import Digest, DigestEntries, FileEntry -from pants.engine.internals.native_engine import AddressInput +from pants.engine.internals.native_engine import AddressInput, AddressParseException from pants.engine.rules import Get, MultiGet, collect_rules, rule from pants.engine.target import ( DependenciesRequest, @@ -88,12 +89,12 @@ async def analyse_deployment(request: AnalyseHelmDeploymentRequest) -> HelmDeplo # Build YAML index of Docker image refs for future processing during depedendecy inference or post-rendering. image_refs_index: MutableYamlIndex[str] = MutableYamlIndex() for manifest in parsed_manifests: - for idx, path, image_ref in manifest.found_image_refs: + for entry in manifest.found_image_refs: image_refs_index.insert( file_path=PurePath(manifest.filename), - document_index=idx, - yaml_path=path, - item=image_ref, + document_index=entry.document_index, + yaml_path=entry.path, + item=entry.unparsed_image_ref, ) return HelmDeploymentReport( @@ -129,18 +130,47 @@ async def first_party_helm_deployment_mapping( deployment_report = await Get( HelmDeploymentReport, AnalyseHelmDeploymentRequest(request.field_set) ) - docker_target_addresses = {tgt.address.spec: tgt.address for tgt in docker_targets} - def lookup_docker_addreses(image_ref: str) -> tuple[str, Address] | None: - addr = docker_target_addresses.get(image_ref, None) - if addr: - return image_ref, addr - return None + def image_ref_to_address_input(image_ref: str) -> tuple[str, AddressInput] | None: + try: + return image_ref, AddressInput.parse( + image_ref, + description_of_origin=f"the helm_deployment at {request.field_set.address}", + relative_to=request.field_set.address.spec_path, + ) + except AddressParseException: + return None + + indexed_address_inputs = deployment_report.image_refs.transform_values( + image_ref_to_address_input + ) + maybe_addresses = await MultiGet( + Get(MaybeAddress, AddressInput, ai) for _, ai in indexed_address_inputs.values() + ) + + docker_target_addresses = {tgt.address for tgt in docker_targets} + maybe_addresses_by_ref = { + ref: maybe_addr + for ((ref, _), maybe_addr) in zip(indexed_address_inputs.values(), maybe_addresses) + } + + def image_ref_to_actual_address( + image_ref_ai: tuple[str, AddressInput] + ) -> tuple[str, Address] | None: + image_ref, _ = image_ref_ai + maybe_addr = maybe_addresses_by_ref.get(image_ref) + if not maybe_addr: + return None + if not isinstance(maybe_addr.val, Address): + return None + if maybe_addr.val not in docker_target_addresses: + return None + return image_ref, maybe_addr.val return FirstPartyHelmDeploymentMapping( address=request.field_set.address, - indexed_docker_addresses=deployment_report.image_refs.transform_values( - lookup_docker_addreses + indexed_docker_addresses=indexed_address_inputs.transform_values( + image_ref_to_actual_address ), ) diff --git a/src/python/pants/backend/helm/subsystems/k8s_parser.py b/src/python/pants/backend/helm/subsystems/k8s_parser.py --- a/src/python/pants/backend/helm/subsystems/k8s_parser.py +++ b/src/python/pants/backend/helm/subsystems/k8s_parser.py @@ -78,10 +78,17 @@ def metadata(self) -> dict[str, Any] | None: return {"file": self.file} +@dataclass(frozen=True) +class ParsedImageRefEntry: + document_index: int + path: YamlPath + unparsed_image_ref: str + + @dataclass(frozen=True) class ParsedKubeManifest(EngineAwareReturnType): filename: str - found_image_refs: tuple[tuple[int, YamlPath, str], ...] + found_image_refs: tuple[ParsedImageRefEntry, ...] def level(self) -> LogLevel | None: return LogLevel.DEBUG @@ -115,7 +122,7 @@ async def parse_kube_manifest( if result.exit_code == 0: output = result.stdout.decode("utf-8").splitlines() - image_refs: list[tuple[int, YamlPath, str]] = [] + image_refs: list[ParsedImageRefEntry] = [] for line in output: parts = line.split(",") if len(parts) != 3: @@ -128,7 +135,13 @@ async def parse_kube_manifest( ) ) - image_refs.append((int(parts[0]), YamlPath.parse(parts[1]), parts[2])) + image_refs.append( + ParsedImageRefEntry( + document_index=int(parts[0]), + path=YamlPath.parse(parts[1]), + unparsed_image_ref=parts[2], + ) + ) return ParsedKubeManifest(filename=request.file.path, found_image_refs=tuple(image_refs)) else:
diff --git a/src/python/pants/backend/helm/dependency_inference/deployment_test.py b/src/python/pants/backend/helm/dependency_inference/deployment_test.py --- a/src/python/pants/backend/helm/dependency_inference/deployment_test.py +++ b/src/python/pants/backend/helm/dependency_inference/deployment_test.py @@ -86,7 +86,7 @@ def test_deployment_dependencies_report(rule_runner: RuleRunner) -> None: image: example.com/containers/busybox:1.28 """ ), - "src/deployment/BUILD": "helm_deployment(name='foo', dependencies=['//src/mychart'])", + "src/deployment/BUILD": "helm_deployment(name='foo', chart='//src/mychart')", } ) @@ -142,6 +142,70 @@ def test_inject_chart_into_deployment_dependencies(rule_runner: RuleRunner) -> N assert list(inferred_dependencies.include)[0] == Address("src/mychart") +def test_resolve_relative_docker_addresses_to_deployment(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "src/mychart/BUILD": "helm_chart()", + "src/mychart/Chart.yaml": HELM_CHART_FILE, + "src/mychart/values.yaml": dedent( + """\ + container: + image_ref: docker/image:latest + """ + ), + "src/mychart/templates/_helpers.tpl": HELM_TEMPLATE_HELPERS_FILE, + "src/mychart/templates/pod.yaml": dedent( + """\ + apiVersion: v1 + kind: Pod + metadata: + name: {{ template "fullname" . }} + labels: + chart: "{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}" + spec: + containers: + - name: myapp-container + image: {{ .Values.container.image_ref }} + """ + ), + "src/deployment/BUILD": dedent( + """\ + docker_image(name="myapp") + + helm_deployment( + name="foo", + chart="//src/mychart", + values={ + "container.image_ref": ":myapp" + } + ) + """ + ), + "src/deployment/Dockerfile": "FROM busybox:1.28", + } + ) + + source_root_patterns = ("src/*",) + rule_runner.set_options( + [f"--source-root-patterns={repr(source_root_patterns)}"], + env_inherit=PYTHON_BOOTSTRAP_ENV, + ) + + deployment_addr = Address("src/deployment", target_name="foo") + tgt = rule_runner.get_target(deployment_addr) + field_set = HelmDeploymentFieldSet.create(tgt) + + expected_image_ref = ":myapp" + expected_dependency_addr = Address("src/deployment", target_name="myapp") + + mapping = rule_runner.request( + FirstPartyHelmDeploymentMapping, [FirstPartyHelmDeploymentMappingRequest(field_set)] + ) + assert list(mapping.indexed_docker_addresses.values()) == [ + (expected_image_ref, expected_dependency_addr) + ] + + def test_inject_deployment_dependencies(rule_runner: RuleRunner) -> None: rule_runner.write_files( { @@ -163,7 +227,7 @@ def test_inject_deployment_dependencies(rule_runner: RuleRunner) -> None: image: src/image:myapp """ ), - "src/deployment/BUILD": "helm_deployment(name='foo', dependencies=['//src/mychart'])", + "src/deployment/BUILD": "helm_deployment(name='foo', chart='//src/mychart')", "src/image/BUILD": "docker_image(name='myapp')", "src/image/Dockerfile": "FROM busybox:1.28", } @@ -194,8 +258,9 @@ def test_inject_deployment_dependencies(rule_runner: RuleRunner) -> None: [InferHelmDeploymentDependenciesRequest(field_set)], ) - assert len(inferred_dependencies.include) == 1 - assert list(inferred_dependencies.include)[0] == expected_dependency_addr + # The Helm chart dependency is part of the inferred dependencies + assert len(inferred_dependencies.include) == 2 + assert expected_dependency_addr in inferred_dependencies.include def test_disambiguate_docker_dependency(rule_runner: RuleRunner) -> None: @@ -223,8 +288,8 @@ def test_disambiguate_docker_dependency(rule_runner: RuleRunner) -> None: """\ helm_deployment( name="foo", + chart="//src/mychart", dependencies=[ - "//src/mychart", "!//registry/image:latest", ] ) @@ -249,4 +314,6 @@ def test_disambiguate_docker_dependency(rule_runner: RuleRunner) -> None: [InferHelmDeploymentDependenciesRequest(HelmDeploymentFieldSet.create(tgt))], ) - assert len(inferred_dependencies.include) == 0 + # Assert only the Helm chart dependency has been inferred + assert len(inferred_dependencies.include) == 1 + assert set(inferred_dependencies.include) == {Address("src/mychart")} diff --git a/src/python/pants/backend/helm/subsystems/k8s_parser_test.py b/src/python/pants/backend/helm/subsystems/k8s_parser_test.py --- a/src/python/pants/backend/helm/subsystems/k8s_parser_test.py +++ b/src/python/pants/backend/helm/subsystems/k8s_parser_test.py @@ -9,7 +9,11 @@ import pytest from pants.backend.helm.subsystems import k8s_parser -from pants.backend.helm.subsystems.k8s_parser import ParsedKubeManifest, ParseKubeManifestRequest +from pants.backend.helm.subsystems.k8s_parser import ( + ParsedImageRefEntry, + ParsedKubeManifest, + ParseKubeManifestRequest, +) from pants.backend.helm.testutil import K8S_POD_FILE from pants.backend.helm.utils.yaml import YamlPath from pants.engine.fs import CreateDigest, Digest, DigestEntries, FileContent, FileEntry @@ -45,8 +49,8 @@ def test_parser_can_run(rule_runner: RuleRunner) -> None: ) expected_image_refs = [ - (0, YamlPath.parse("/spec/containers/0/image"), "busybox:1.28"), - (0, YamlPath.parse("/spec/initContainers/0/image"), "busybox:1.29"), + ParsedImageRefEntry(0, YamlPath.parse("/spec/containers/0/image"), "busybox:1.28"), + ParsedImageRefEntry(0, YamlPath.parse("/spec/initContainers/0/image"), "busybox:1.29"), ] assert parsed_manifest.found_image_refs == tuple(expected_image_refs)
support relative docker_image target syntax for helm interpolated images values **Is your feature request related to a problem? Please describe.** ``` docker_image(name='tmp-example') helm_deployment(dependencies=["src/chart"], sources=["common-values.yaml"], values={"image": "src/docker:tmp-example"}) ``` ``` $ ./pants experimental-deploy src/deployment:deployment -- --debug | grep image ... # Uses the `image` value entry from the deployment inputs image: corp.registry.example/tmp-example:localdev ``` But ``` docker_image(name='tmp-example') helm_deployment(dependencies=["src/chart"], sources=["common-values.yaml"], values={"image": ":tmp-example"}) ``` Gives ``` $ ./pants experimental-deploy src/deployment:deployment -- --debug | grep image # Uses the `image` value entry from the deployment inputs image: :tmp-example ``` **Describe the solution you'd like** I'd like the `:foo` target syntax to work. **Describe alternatives you've considered** Always using the fully qualified targets. Version: 2.16.0.dev7
2023-07-13T09:26:10
pantsbuild/pants
19,456
pantsbuild__pants-19456
[ "19390" ]
d6705202591b8b2e73ff332105038c2971fc8dfd
diff --git a/src/python/pants/backend/visibility/glob.py b/src/python/pants/backend/visibility/glob.py --- a/src/python/pants/backend/visibility/glob.py +++ b/src/python/pants/backend/visibility/glob.py @@ -225,9 +225,9 @@ def parse(cls: type[TargetGlob], spec: str | Mapping[str, Any], base: str) -> Ta raise ValueError(f"Target spec must not be empty. {spec!r}") return cls.create( # type: ignore[call-arg] - type_=spec_dict.get("type"), - name=spec_dict.get("name"), - path=spec_dict.get("path"), + type_=str(spec_dict["type"]) if "type" in spec_dict else None, + name=str(spec_dict["name"]) if "name" in spec_dict else None, + path=str(spec_dict["path"]) if "path" in spec_dict else None, base=base, tags=cls._parse_tags(spec_dict.get("tags")), )
diff --git a/src/python/pants/backend/visibility/rule_types_test.py b/src/python/pants/backend/visibility/rule_types_test.py --- a/src/python/pants/backend/visibility/rule_types_test.py +++ b/src/python/pants/backend/visibility/rule_types_test.py @@ -931,3 +931,24 @@ def test_single_rules_declaration_per_build_file(rule_runner: RuleRunner) -> Non rule_runner, "test", ) + + +def test_target_type_in_verbose_selector_issue_19390(rule_runner: RuleRunner) -> None: + """This test is logically a better fit in `./glob_test.py:test_target_glob_parse_spec` but I + want to avoid hard coding any assumptions regarding a target types representation in the BUILD + file (the `Registrar` type).""" + rule_runner.write_files( + { + "test/BUILD": dedent( + """ + target(name="test") + + __dependencies_rules__( + ({"type": files}, "*"), + ) + """ + ), + }, + ) + + assert_dependency_rules(rule_runner, "test")
Can not use target type in visibility rule selector. **Describe the bug** > the example given in the docs, {"type": python_sources}, but the parsing breaks with an error of "TypeError: decoding to str: need a bytes-like object, Registrar found", **Pants version** 2.17.0rc1 **OS** n/a **Additional info** https://pantsbuild.slack.com/archives/C046T6T9U/p1687953070098239
2023-07-13T14:27:15
pantsbuild/pants
19,457
pantsbuild__pants-19457
[ "19390" ]
147845d6a1541b73f7cfb4889b1872c8a231eaec
diff --git a/src/python/pants/backend/visibility/glob.py b/src/python/pants/backend/visibility/glob.py --- a/src/python/pants/backend/visibility/glob.py +++ b/src/python/pants/backend/visibility/glob.py @@ -225,9 +225,9 @@ def parse(cls: type[TargetGlob], spec: str | Mapping[str, Any], base: str) -> Ta raise ValueError(f"Target spec must not be empty. {spec!r}") return cls.create( # type: ignore[call-arg] - type_=spec_dict.get("type"), - name=spec_dict.get("name"), - path=spec_dict.get("path"), + type_=str(spec_dict["type"]) if "type" in spec_dict else None, + name=str(spec_dict["name"]) if "name" in spec_dict else None, + path=str(spec_dict["path"]) if "path" in spec_dict else None, base=base, tags=cls._parse_tags(spec_dict.get("tags")), )
diff --git a/src/python/pants/backend/visibility/rule_types_test.py b/src/python/pants/backend/visibility/rule_types_test.py --- a/src/python/pants/backend/visibility/rule_types_test.py +++ b/src/python/pants/backend/visibility/rule_types_test.py @@ -927,3 +927,24 @@ def test_single_rules_declaration_per_build_file(rule_runner: RuleRunner) -> Non rule_runner, "test", ) + + +def test_target_type_in_verbose_selector_issue_19390(rule_runner: RuleRunner) -> None: + """This test is logically a better fit in `./glob_test.py:test_target_glob_parse_spec` but I + want to avoid hard coding any assumptions regarding a target types representation in the BUILD + file (the `Registrar` type).""" + rule_runner.write_files( + { + "test/BUILD": dedent( + """ + target(name="test") + + __dependencies_rules__( + ({"type": files}, "*"), + ) + """ + ), + }, + ) + + assert_dependency_rules(rule_runner, "test")
Can not use target type in visibility rule selector. **Describe the bug** > the example given in the docs, {"type": python_sources}, but the parsing breaks with an error of "TypeError: decoding to str: need a bytes-like object, Registrar found", **Pants version** 2.17.0rc1 **OS** n/a **Additional info** https://pantsbuild.slack.com/archives/C046T6T9U/p1687953070098239
2023-07-13T14:27:15
pantsbuild/pants
19,478
pantsbuild__pants-19478
[ "16315" ]
05afd8bb9f48d1fcf08b66023ef234a881879159
diff --git a/src/python/pants/goal/builtins.py b/src/python/pants/goal/builtins.py --- a/src/python/pants/goal/builtins.py +++ b/src/python/pants/goal/builtins.py @@ -7,6 +7,7 @@ from pants.build_graph.build_configuration import BuildConfiguration from pants.goal import help from pants.goal.builtin_goal import BuiltinGoal +from pants.goal.completion import CompletionBuiltinGoal from pants.goal.explorer import ExplorerBuiltinGoal from pants.goal.migrate_call_by_name import MigrateCallByNameBuiltinGoal @@ -18,6 +19,7 @@ def register_builtin_goals(build_configuration: BuildConfiguration.Builder) -> N def builtin_goals() -> tuple[type[BuiltinGoal], ...]: return ( BSPGoal, + CompletionBuiltinGoal, ExplorerBuiltinGoal, MigrateCallByNameBuiltinGoal, help.AllHelpBuiltinGoal, diff --git a/src/python/pants/goal/completion.py b/src/python/pants/goal/completion.py new file mode 100644 --- /dev/null +++ b/src/python/pants/goal/completion.py @@ -0,0 +1,184 @@ +# Copyright 2024 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +# TODO: This was written as a port of the original bash script, but since we have +# more knowledge of the options and goals, we can make this more robust and accurate (after tests are written). + +from __future__ import annotations + +import logging +from enum import Enum + +from pants.base.exiter import PANTS_SUCCEEDED_EXIT_CODE, ExitCode +from pants.base.specs import Specs +from pants.build_graph.build_configuration import BuildConfiguration +from pants.engine.unions import UnionMembership +from pants.goal.builtin_goal import BuiltinGoal +from pants.init.engine_initializer import GraphSession +from pants.option.option_types import EnumOption +from pants.option.options import Options +from pants.option.scope import GLOBAL_SCOPE +from pants.util.resources import read_resource +from pants.util.strutil import softwrap + +_COMPLETIONS_PACKAGE = "pants.goal" + +logger = logging.getLogger(__name__) + + +class Shell(Enum): + BASH = "bash" + ZSH = "zsh" + + +class CompletionBuiltinGoal(BuiltinGoal): + name = "complete" + help = softwrap( + """ + Generates a completion script for the specified shell. The script is printed to stdout. + + For example, `pants complete --zsh > pants-completions.zsh` will generate a zsh + completion script and write it to the file `my-pants-completions.zsh`. You can then + source this file in your `.zshrc` file to enable completion for Pants. + + This command is also used by the completion scripts to generate the completion options using + passthrough options. This usage is not intended for use by end users, but could be + useful for building custom completion scripts. + + An example of this usage is in the bash completion script, where we use the following command: + `pants complete -- ${COMP_WORDS[@]}`. This will generate the completion options for the + current args, and then pass them to the bash completion script. + """ + ) + + shell = EnumOption( + default=Shell.BASH, + help="Which shell completion type should be printed to stdout.", + ) + + def run( + self, + *, + build_config: BuildConfiguration, + graph_session: GraphSession, + options: Options, + specs: Specs, + union_membership: UnionMembership, + ) -> ExitCode: + """This function is called under two main circumstances. + + - By a user generating a completion script for their shell (e.g. `pants complete --zsh > pants-completions.zsh`) + - By the shell completions script when the user attempts a tab completion (e.g. `pants <tab>`, `pants fmt lint che<tab>`, etc...) + + In the first case, we should generate a completion script for the specified shell and print it to stdout. + In the second case, we should generate the completion options for the current command and print them to stdout. + + The trigger to determine which case we're in is the presence of the passthrough arguments. If there are passthrough + arguments, then we're generating completion options. If there are no passthrough arguments, then we're generating + a completion script. + """ + if options._passthru: + completion_options = self._generate_completion_options(options) + if completion_options: + print("\n".join(completion_options)) + return PANTS_SUCCEEDED_EXIT_CODE + + script = self._generate_completion_script(self.shell) + print(script) + return PANTS_SUCCEEDED_EXIT_CODE + + def _generate_completion_script(self, shell: Shell) -> str: + """Generate a completion script for the specified shell. + + Implementation note: In practice, we're just going to read in + and return the contents of the appropriate static completion script file. + + :param shell: The shell to generate a completion script for. + :return: The completion script for the specified shell. + """ + if shell == Shell.ZSH: + return read_resource(_COMPLETIONS_PACKAGE, "pants-completion.zsh").decode("utf-8") + else: + return read_resource(_COMPLETIONS_PACKAGE, "pants-completion.bash").decode("utf-8") + + def _generate_completion_options(self, options: Options) -> list[str]: + """Generate the completion options for the specified args. + + We're guaranteed to have at least two arguments (`["pants", ""]`). If there are only two arguments, + then we're at the top-level Pants command, and we should show all goals. + - `pants <tab>` -> `... fmt fix lint list repl run test ...` + + If we're at the top-level and the user has typed a hyphen, then we should show global options. + - `pants -<tab>` -> `... --pants-config-files --pants-distdir --pants-ignore ...` + + As we add goals, we should show the remaining goals that are available. + - `pants fmt fix lint <tab>` -> `... list repl run test ...` + + If there is a goal in the list of arguments and the user has typed a hyphen, then we should + show the available scoped options for the previous goal. + - `pants fmt -<tab>` -> `... --only ...` + + :param options: The options object for the current Pants run. + :return: A list of candidate completion options. + """ + logger.debug(f"Completion passthrough options: {options._passthru}") + args = [arg for arg in options._passthru if arg != "pants"] + current_word = args.pop() + previous_goal = self._get_previous_goal(args) + logger.debug(f"Current word is '{current_word}', and previous goal is '{previous_goal}'") + + all_goals = sorted([k for k, v in options.known_scope_to_info.items() if v.is_goal]) + + # If there is no previous goal, then we're at the top-level Pants command, so show all goals or global options + if not previous_goal: + if current_word.startswith("-"): + global_options = self._build_options_for_goal(options) + candidate_options = [o for o in global_options if o.startswith(current_word)] + return candidate_options + + candidate_goals = [g for g in all_goals if g.startswith(current_word)] + return candidate_goals + + # If there is already a previous goal and current_word starts with a hyphen, then show scoped options for that goal + if current_word.startswith("-"): + scoped_options = self._build_options_for_goal(options, previous_goal) + candidate_options = [o for o in scoped_options if o.startswith(current_word)] + return candidate_options + + # If there is a previous goal and current_word does not start with a hyphen, then show remaining goals + # excluding the goals that are already in the command + candidate_goals = [ + g for g in all_goals if g.startswith(current_word) and g not in options._passthru + ] + return candidate_goals + + def _get_previous_goal(self, args: list[str]) -> str | None: + """Get the most recent goal in the command arguments, so options can be correctly applied. + + A "goal" in the context of completions is simply an arg where the first character is alphanumeric. + This under-specifies the goal, because detecting whether an arg is an "actual" goal happens elsewhere. + + :param args: The list of arguments to search for the previous goal. + :return: The previous goal, or None if there is no previous goal. + """ + return next((arg for arg in reversed(args) if arg[:1].isalnum()), None) + + def _build_options_for_goal(self, options: Options, goal: str = "") -> list[str]: + """Build a list of stringified options for the specified goal, prefixed by `--`. + + :param options: The options object for the current Pants run. + :param goal: The goal to build options for. Defaults to "" for the global scope. + :return: A list of options for the specified goal. + """ + + if goal == GLOBAL_SCOPE: + global_options = sorted(options.for_global_scope().as_dict().keys()) + return [f"--{o}" for o in global_options] + + try: + scoped_options = sorted(options.for_scope(goal).as_dict().keys()) + return [f"--{o}" for o in scoped_options] + except Exception: + # options.for_scope will throw if the goal is unknown, so we'll just return an empty list + # Since this is used for user-entered tab completion, it's not a warning or error + return [] diff --git a/src/python/pants/option/options.py b/src/python/pants/option/options.py --- a/src/python/pants/option/options.py +++ b/src/python/pants/option/options.py @@ -274,7 +274,12 @@ def register(*args, **kwargs): return register def get_parser(self, scope: str) -> Parser: - """Returns the parser for the given scope, so code can register on it directly.""" + """Returns the parser for the given scope, so code can register on it directly. + + :param scope: The scope to retrieve the parser for. + :return: The parser for the given scope. + :raises pants.option.errors.ConfigValidationError: if the scope is not known. + """ try: return self._parser_by_scope[scope] except KeyError: @@ -350,6 +355,10 @@ def for_scope( Computed lazily per scope. :API: public + :param scope: The scope to get options for. + :param check_deprecations: Whether to check for any deprecations conditions. + :return: An OptionValueContainer representing the option values for the given scope. + :raises pants.option.errors.ConfigValidationError: if the scope is unknown. """ values_builder = OptionValueContainerBuilder()
diff --git a/src/python/pants/goal/completion_integration_test.py b/src/python/pants/goal/completion_integration_test.py new file mode 100644 --- /dev/null +++ b/src/python/pants/goal/completion_integration_test.py @@ -0,0 +1,92 @@ +# Copyright 2024 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from pants.goal.completion import CompletionBuiltinGoal +from pants.option.option_value_container import OptionValueContainer +from pants.testutil.pants_integration_test import PantsResult, run_pants + + +def test_get_previous_goal(): + helper = CompletionBuiltinGoal(OptionValueContainer({})) + assert helper._get_previous_goal([""]) is None + assert helper._get_previous_goal(["--keep_sandboxes=always"]) is None + assert helper._get_previous_goal(["--keep_sandboxes=always", "fmt"]) == "fmt" + assert helper._get_previous_goal(["--keep_sandboxes=always", "fmt", "--only"]) == "fmt" + assert helper._get_previous_goal(["--keep_sandboxes=always", "fmt", "--only", "lint"]) == "lint" + assert ( + helper._get_previous_goal(["--keep_sandboxes=always", "fmt", "--only", "lint", "::"]) + == "lint" + ) + + +def run_pants_complete(args: list[str]) -> PantsResult: + """While there may be a way to test tab-completion directly in pytest, that feels too clever. + + We can equivalently test the command that the tab-completion will call. + + Note: The "pants" after "--" is intentional, as that's how the completion script would call it. + """ + return run_pants(["pants", "complete", "--", "pants", *args]) + + +def test_completion_script_generation(): + default_result = run_pants(["complete"]) + default_result.assert_success() + + bash_result = run_pants(["complete", "--shell=bash"]) + bash_result.assert_success() + assert "COMPREPLY" in bash_result.stdout + + zsh_result = run_pants(["complete", "--shell=zsh"]) + zsh_result.assert_success() + assert "compdef" in zsh_result.stdout + + other_result = run_pants(["complete", "--shell=gibberish"]) + other_result.assert_failure() + + +def test_completions_with_global_options(): + result = run_pants_complete(["-"]) + result.assert_success() + lines = result.stdout.splitlines() + assert all(line.startswith("--") for line in lines) + assert all(o in lines for o in ("--backend_packages", "--colors", "--loop")) # Spot check + + +def test_completions_with_all_goals(): + result = run_pants_complete([""]) + result.assert_success() + lines = result.stdout.splitlines() + assert all(not line.startswith("-") for line in lines) + assert all(o in lines for o in ("check", "help", "version")) # Spot check + + +def test_completions_with_all_goals_excluding_previous_goals(): + result = run_pants_complete(["check", ""]) + result.assert_success() + lines = result.stdout.splitlines() + assert all(not line.startswith("-") for line in lines) + assert all(o in lines for o in ("help", "version")) # Spot check + assert "check" not in lines + + # Check that multiple goals are excluded + result = run_pants_complete(["check", "help", ""]) + result.assert_success() + lines = result.stdout.splitlines() + assert all(not line.startswith("-") for line in lines) + assert "version" in lines # Spot check + assert all(o not in lines for o in ("check", "help")) + + +def test_completions_with_goal_options(): + result = run_pants_complete(["fmt", "-"]) + result.assert_success() + lines = result.stdout.splitlines() + assert all(line.startswith("--") for line in lines) + assert all(o in lines for o in ("--batch_size", "--only")) # Spot check + + +def test_completions_with_options_on_invalid_goal(): + result = run_pants_complete(["unknown-goal", "-"]) + result.assert_success() + assert result.stdout == ""
Integrate shell-completion with Pants Since #16200 has landed, integration with Pants should be the next focus (plus dedicated ZSH completions wouldn't hurt). The merged PR was strictly a Python script to generate bash completions. The outstanding questions are: - Which goal does this fall under? - Is there any way to auto-generate completions when `pants.toml` is changed? - Can the completions be auto-sourced after the first Pants run?
@Eric-Arellano @benjyw Any thoughts on the outstanding questions? I'm not really sure in which direction I can take this to integrate with Pants. From the Slack conversations, `export` would seem like a decent goal, but not today's version of export, which is more related to `venv`s With all the API discussions we've had the past few weeks and my general dislike of API bloat, I'd rather this not be a new goal, but somehow be shoe-horned into something else. I can take a crack at something, but I don't yet know what that "thing" is. Alternatively (and I'm not super into this either) I could intermezzo this with an `experimental-completions` goal with the knowledge that "experimental-" prefixed goals will be changed when they graduate. I'd love to play with this, but it wasn't working for me, as we discussed on Slack or on the ticket, I forget which... Has anything been fixed there? Once I get to using it regularly I can form opinions about how to proceed... Yep, just pushed two fixes: https://github.com/pantsbuild/pants/pull/16442 Works on Mac and Debian Bullseye for me now, no warnings/complaints. I think we should redesign `export`, possibly merging `export-codegen` into it. If you don't want to be blocked, you could call it `experimental-shell-autocomplete`. > Is there any way to auto-generate completions when pants.toml is changed? This would be https://github.com/pantsbuild/pants/issues/12014 > I'm fine with a long-term alias. And it is worth rethinking the "temporary name while a feature is experimental" [habit]? >> Maybe we should get more cozy with "experimental" in general? > Or less... Re: https://github.com/pantsbuild/pants/pull/16397 @benjyw Thoughts? I don't want to start creating new experimentally-namespaced goals, while discussing in another ticket whether we should have them or not. Here's my entirely selfish perspective of my DX workflow over the last couple weeks. From mainline Pants, I've generated the most thorough `completion.bash` I can (`python3 build-support/bin/generate_completions.py > pants-completions.bash`), and aliased it into my user's completions folder. So, while I may not have the same tools/plugins as mainline in any given repo, I know enough that I can use my auto-complete without any problems. This isn't the best, as it doesn't react to my `pants.toml`... But so be it, it's already miles ahead of me trying to remember something, or jumping into help to find the letters to type. The biggest reason for completions for me was related to introspection commands, which I'm trying to solve by creating that super trivial VSCode extension, so introspection tools are always visible. This is all to say that I'm totally fine not creating any custom goals until `export` or whatever is sorted out. Personally, I'm in no rush and any Pants maintainers/contributors can probably end up in the same boat. The completions might be much more useful for new/casual Pants users, who don't have all the commands memorized. For that case, we could even do something similar to what I'm doing - which is to generate a single, massive completions file, host that on the website and let users know that it might not all work, depending on their pants.toml. Ugly workaround? Sure - but better than touching the public API in my mind. I want to play with this for a couple of days (now that it should work, after your recent changes), and hopefully that will give me ideas. Just so this isn't fully lost to Slack history (between Stu and I): > So what about doing something more like `--version`? ./pants --completions ? > this would work too probably. goals don’t have access to the help APIs in general, but “BuiltinGoals” do. so a ./pants completions would be possible. I'll take a crack at this, and see if I can get anything created by Pants for arbitrary repos, and then we can work on naming. Thanks a lot @sureshjoshi! @stuhood No problem, but we still need an endgame here wrt my Slack thread (https://pantsbuild.slack.com/archives/C0D7TNJHL/p1664221191673119). > However, this leaves me with a couple outstanding questions: > 1. What should the completions "goal" be called? ./pants completions - even if it's contrived, I like the idea of something like ./pants --completions which kinda indicates that it's acting on the pants instance itself, rather than being a verb for some other work > 2. What should the output of said pseudo-goal be? Print the completions to the console? Export to dist? This is probably a per-repo file, since it depends on what the installed backend packages are - so it may not be something trivially exported to a completions folder somewhere on the user's filesystem > 3. Can this be auto-updated if the backend-packages change? According to Eric, 3 relates to https://github.com/pantsbuild/pants/issues/12014 > > 2. What should the output of said pseudo-goal be? Print the completions to the console? Export to dist? This is probably a per-repo file, since it depends on what the installed backend packages are - so it may not be something trivially exported to a completions folder somewhere on the user's filesystem This is an important question, yea. Looking around at prior art would be good here, as I don't know how tools do this in general. But do note that one annoying issue in this case is that each repo on your system might be using a different version of pants. Any bit of automation that attempted to write out a global config would need to be version aware (and perhaps have a shim at the top level to decide which copy of the completions to use?) Or we could recommend that people use `direnv`, perhaps. > > 3. Can this be auto-updated if the backend-packages change? > > According to Eric, 3 relates to #12014 I don't think that it needs to be: because this would be a built-in goal, it would not be running as `@rule` code, and so it would not be subject to restrictions on what it could read/write to the filesystem (with the caveat that it would need to invent its own memoization if you wanted to avoid checking the filesystem on each run). > > 1. What should the completions "goal" be called? ./pants completions - even if it's contrived, I like the idea of something like ./pants --completions which kinda indicates that it's acting on the pants instance itself, rather than being a verb for some other work If it ends up auto-updated, then I don't think that it would need a goal name: rather, an option name? But perhaps you'd still need a goal for the initial install of completions. It's also possible though that the [installation script](https://www.pantsbuild.org/v2.14/docs/installation) could bootstrap what is needed there. > This is an important question, yea. Looking around at prior art would be good here, as I don't know how tools do this in general. For, let's say, "static" tooling - it often comes down at installation time. e.g. `/usr/local/Cellar/git/2.37.3/share/zsh/site-functions/git-completion.bash` which can be symlinked into wherever (I seem to have completions in like, 10 folders on my machine). `/usr/local/share/zsh/site-functions` `/usr/local/etc/bash_completion.d/` For something a bit more dynamic, `python-fire` has a command to generate them and then you pipe those completions wherever you want them: https://github.com/google/python-fire/blob/master/docs/using-cli.md#completion-flag > It's also possible though that the [installation script](https://www.pantsbuild.org/v2.14/docs/installation) could bootstrap what is needed there. My original idea in the long long ago times was that it would be part of the installation script somehow, which also might give us some ability to hook into changes to the backend packages. Felt both like a good and bad idea to be in that script, if we could enable/disable it to the user's preference. Whether it's a good idea or not, I was thinking that you could source the repo's completions after your first `./pants` command, and then the completions would be available and ready-sourced. > Any bit of automation that attempted to write out a global config would need to be version aware (and perhaps have a shim at the top level to decide which copy of the completions to use?) This is something I didn't think too much about - I'd never seen it done (at least, I don't think I have). If we could dynamically re-direct to the current directory's `dist` from a global shim, that would be interesting. > This is something I didn't think too much about - I'd never seen it done (at least, I don't think I have). If we could dynamically re-direct to the current directory's `dist` from a global shim, that would be interesting. Yea... this would be a bit like a custom implementation of `direnv` I suppose? Oh yeah, I guess so. I don't currently use `direnv` (or any shell extensions, actually). Do we have any idea on the ratios of users to number of Pants repos a given user works on? For me, it's about 10:1 repos per SJ, but I would think that in companies focusing on monorepos, it might be less. So, if there is a default single-repo path, and then "here is a tool/way/mechanism for a multi-repo case"? For the single-repo case, I think just printing to console, and then letting the user pipe wherever they so choose could make sense. Hmm, though, this kinda falls over to backend-package changes... Blah. Ok; so... coming in here like a buffoon and probably asking questions you've talked about elsewhere... Wouldn't going for fully dynamic completion be somewhat easier (from a user viewpoint, not necessarily tech)? :-) ```bash _pants () { pants="${COMP_WORDS[0]}"; local words=("${COMP_WORDS[@]}") local completions=$($pants --complete --word $COMP_CWARD --point $COMP_POINT "${words[@]}") COMPREPLY=( $(compgen -W "$completions" -- "$word") ) } complete -F _pants pants ``` Works for `./pants`, `../pants`, `foobar/pants`, and so on. Solves the "which pants repo" since it'll use the one the user is using. Avoids the whole "is it up to date" conundrum. Even if implementing it like this might turn out too complicated, one could take the "which pants" approach and use that to refresh the list on each run. Thanks for the feedback, and yeah, we briefly talked about this yesterday on the slack channel. In short, it's not a bad idea to do that on `tab`, BUT, you're at the mercy of the time taken to re-run the pants process on each `tab`. On my machine (6-core i5 Mac Mini), I think it ended up somewhere between 0.5-2 seconds per call - with the daemon running, and that's without any real substantial changes to the code base. If calling `./pants --complete` was essentially a no-op, it would be a great approach, but it's a bit more involved. Also, backend packages don't really change frequently, so the "is it up-to-date" should be a rare (but important) check... In lieu of fully dynamic, as you suggested, putting something in the pants script would be the intermezzo - but I'm just not sure how that would look, with config as well. > On my machine (6-core i5 Mac Mini), I think it ended up somewhere between 0.5-2 seconds per call - with the daemon running, and that's without any real substantial changes to the code base. Finishing shipping [#7369](https://github.com/pantsbuild/pants/issues/7369#issuecomment-1217432512) will unblock improving latency, because it will ease shipping the native-client that is already implemented. It will also touch the `pants` script. That will still only be for the "warm `pantsd`" case, but an approach which can _evolve_ into dynamic would be great. > Thanks for the feedback, and yeah, we briefly talked about this yesterday on the slack channel. > > In short, it's not a bad idea to do that on tab, BUT, you're at the mercy of the time taken to re-run the pants process on each tab. > > On my machine (6-core i5 Mac Mini), I think it ended up somewhere between 0.5-2 seconds per call - with the daemon running, and that's without any real substantial changes to the code base. Figured as much, but wanted to check. Mine doesn't take that long (<0.5s) which IMO is fine, but 2s would be a bit annoying if it's every tab. > If calling ./pants --complete was essentially a no-op, it would be a great approach, but it's a bit more involved. Also, backend packages don't really change frequently, so the "is it up-to-date" should be a rare (but important) check... > > In lieu of fully dynamic, as you suggested, putting something in the pants script would be the intermezzo - but I'm just not sure how that would look, with config as well. My primary use-case isn't goals, it's targets[^1]. Finding the right target in a directory, finding out which ones exist, etc. That's going to change much more often. I had a bit of a check in how Buck and Bazel do it; and they seem to both have options for either querying via the tool or dumb grepping for targets. Both seem to depend on some known lists of commands and flags as well; likely shipped with the binary. But since both goals and targets (and which goals affect which target) can change (plus depending on location), that is a bit more complex for Pants. Spitballing here; could the list be maintained by the daemon? So instead of `./pants` calling the daemon, the daemon pushes a file to `.pants.d`? [^1]: At least from my experience with Bazel, which admittedly overloads the targets much more than the verbs. That's great information! This **first** version of the completions only cover the goals/options/subsystems/etc - targets are a step two, as other than filesystem targets, those internal to BUILD files are going to need to be more clever (which is another good use case for dynamically created completions!)
2023-07-16T19:03:41
pantsbuild/pants
19,533
pantsbuild__pants-19533
[ "19350" ]
e394c8ca37097daf5cefc60af76ff379da5389b6
diff --git a/src/python/pants/backend/docker/goals/package_image.py b/src/python/pants/backend/docker/goals/package_image.py --- a/src/python/pants/backend/docker/goals/package_image.py +++ b/src/python/pants/backend/docker/goals/package_image.py @@ -313,6 +313,7 @@ def get_build_options( field_set: DockerPackageFieldSet, global_target_stage_option: str | None, global_build_hosts_options: dict | None, + global_build_no_cache_option: bool | None, target: Target, ) -> Iterator[str]: # Build options from target fields inheriting from DockerBuildOptionFieldMixin @@ -355,6 +356,9 @@ def get_build_options( if target_stage: yield from ("--target", target_stage) + if global_build_no_cache_option: + yield "--no-cache" + @rule async def build_docker_image( @@ -418,6 +422,7 @@ async def build_docker_image( field_set=field_set, global_target_stage_option=options.build_target_stage, global_build_hosts_options=options.build_hosts, + global_build_no_cache_option=options.build_no_cache, target=wrapped_target.target, ) ), diff --git a/src/python/pants/backend/docker/subsystems/docker_options.py b/src/python/pants/backend/docker/subsystems/docker_options.py --- a/src/python/pants/backend/docker/subsystems/docker_options.py +++ b/src/python/pants/backend/docker/subsystems/docker_options.py @@ -191,6 +191,10 @@ def env_vars(self) -> tuple[str, ...]: """ ), ) + build_no_cache = BoolOption( + default=False, + help="Do not use the Docker cache when building images.", + ) build_verbose = BoolOption( default=False, help="Whether to log the Docker output to the console. If false, only the image ID is logged.",
diff --git a/src/python/pants/backend/docker/goals/package_image_test.py b/src/python/pants/backend/docker/goals/package_image_test.py --- a/src/python/pants/backend/docker/goals/package_image_test.py +++ b/src/python/pants/backend/docker/goals/package_image_test.py @@ -170,6 +170,7 @@ def mock_get_info_file(request: CreateDigest) -> Digest: opts.setdefault("build_target_stage", None) opts.setdefault("build_hosts", None) opts.setdefault("build_verbose", False) + opts.setdefault("build_no_cache", False) opts.setdefault("env_vars", []) docker_options = create_subsystem( @@ -1011,6 +1012,45 @@ def check_docker_proc(process: Process): ) +def test_docker_build_no_cache_option(rule_runner: RuleRunner) -> None: + rule_runner.set_options( + [], + env={ + "PANTS_DOCKER_BUILD_NO_CACHE": "true", + }, + ) + rule_runner.write_files( + { + "docker/test/BUILD": dedent( + """\ + docker_image( + name="img1", + ) + """ + ), + } + ) + + def check_docker_proc(process: Process): + assert process.argv == ( + "/dummy/docker", + "build", + "--pull=False", + "--no-cache", + "--tag", + "img1:latest", + "--file", + "docker/test/Dockerfile", + ".", + ) + + assert_build( + rule_runner, + Address("docker/test", target_name="img1"), + process_assertions=check_docker_proc, + ) + + def test_docker_build_hosts_option(rule_runner: RuleRunner) -> None: rule_runner.set_options( [],
Support for additional Docker build options **Is your feature request related to a problem? Please describe.** Pants users have requested support for passing additional options to Docker build. - request for `--platform` option - https://github.com/pantsbuild/pants/issues/17539 - request for network and host override - https://pantsbuild.slack.com/archives/C046T6T9U/p1680209250680309 - request for `--no-cache` - https://pantsbuild.slack.com/archives/C046T6T9U/p1686776926633339 Creating this issue as I am happy to volunteer to implement these, but I think it's worth deciding on an approach first. **Describe the solution you'd like** It would be desirable for these options to be available on the `docker_image` target. In some cases, being able to set the option globally via docker backend config may also be helpful. Based on analysis below and requests above, the following options should be prioritised: - additional host ip mappings - network mode - no-cache - platform **Describe alternatives you've considered** It is possible to use a shim script around the Docker CLI as described here - https://pantsbuild.slack.com/archives/C046T6T9U/p1680209250680309, however it is more difficult to use. **Additional context** Support for [buildx](https://docs.docker.com/engine/reference/commandline/buildx_build/) has also been [requested](https://github.com/pantsbuild/pants/issues/15199). The buildx build command has different options to the [standard](https://docs.docker.com/engine/reference/commandline/build/) build command. Here is an [analysis of the options across both commands](https://docs.google.com/spreadsheets/d/1anjf-Y1Z5ft-uazABiAb54gJ6CxlV1g1o9-yljB8u9c/edit?usp=sharing), along with some suggested names (aliases) for new options. **Scope considerations** Buildx build is now the default in the latest Docker Desktop - it would be better to focus on supporting that going forward - i.e. don't implement options that are only in the standard build command. Recommend keeping cache options out of scope of this issue as buildx support should probably be implemented first, and then need to look at implementation of `--cache-from` and `--cache-to` with Pants targets.
2023-07-29T12:41:13
pantsbuild/pants
19,555
pantsbuild__pants-19555
[ "19273" ]
fa5cf61a1c32ab45bbef55d01e83436510beacae
diff --git a/build-support/bin/generate_docs.py b/build-support/bin/generate_docs.py --- a/build-support/bin/generate_docs.py +++ b/build-support/bin/generate_docs.py @@ -196,8 +196,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.experimental.python", "pants.backend.experimental.python.framework.stevedore", "pants.backend.experimental.python.lint.add_trailing_comma", - "pants.backend.experimental.python.lint.autoflake", - "pants.backend.experimental.python.lint.pyupgrade", + "pants.backend.experimental.python.lint.ruff", "pants.backend.experimental.python.packaging.pyoxidizer", "pants.backend.experimental.scala", "pants.backend.experimental.scala.lint.scalafmt", @@ -207,6 +206,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.google_cloud_function.python", "pants.backend.plugin_development", "pants.backend.python", + "pants.backend.python.lint.autoflake", "pants.backend.python.lint.bandit", "pants.backend.python.lint.black", "pants.backend.python.lint.docformatter", @@ -214,6 +214,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.python.lint.isort", "pants.backend.python.lint.pydocstyle", "pants.backend.python.lint.pylint", + "pants.backend.python.lint.pyupgrade", "pants.backend.python.lint.yapf", "pants.backend.python.mixed_interpreter_constraints", "pants.backend.python.typecheck.mypy",
`ruff` backend missing from 2.16.x docs **Describe the bug** See https://www.pantsbuild.org/v2.16/docs/reference-all-subsystems. I think it's just missing from docs because I see it in the wheel.
guess it's another list it needs to be a member of for that: https://github.com/pantsbuild/pants/blob/ad20ba4d303cf293b0bf0ed5d18280f725b11c27/build-support/bin/generate_docs.py#L232-L241 we really ought to generate these lists from an authoritative source where we list all backends and have options like: * [ ] include in dist * [ ] include in docs * [ ] ....
2023-08-06T04:38:40
pantsbuild/pants
19,576
pantsbuild__pants-19576
[ "19273" ]
b32c84d2c4a179cdf8db1e78214cc7e79cb47927
diff --git a/build-support/bin/generate_docs.py b/build-support/bin/generate_docs.py --- a/build-support/bin/generate_docs.py +++ b/build-support/bin/generate_docs.py @@ -196,8 +196,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.experimental.python", "pants.backend.experimental.python.framework.stevedore", "pants.backend.experimental.python.lint.add_trailing_comma", - "pants.backend.experimental.python.lint.autoflake", - "pants.backend.experimental.python.lint.pyupgrade", + "pants.backend.experimental.python.lint.ruff", "pants.backend.experimental.python.packaging.pyoxidizer", "pants.backend.experimental.scala", "pants.backend.experimental.scala.lint.scalafmt", @@ -207,6 +206,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.google_cloud_function.python", "pants.backend.plugin_development", "pants.backend.python", + "pants.backend.python.lint.autoflake", "pants.backend.python.lint.bandit", "pants.backend.python.lint.black", "pants.backend.python.lint.docformatter", @@ -214,6 +214,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.python.lint.isort", "pants.backend.python.lint.pydocstyle", "pants.backend.python.lint.pylint", + "pants.backend.python.lint.pyupgrade", "pants.backend.python.lint.yapf", "pants.backend.python.mixed_interpreter_constraints", "pants.backend.python.typecheck.mypy",
`ruff` backend missing from 2.16.x docs **Describe the bug** See https://www.pantsbuild.org/v2.16/docs/reference-all-subsystems. I think it's just missing from docs because I see it in the wheel.
guess it's another list it needs to be a member of for that: https://github.com/pantsbuild/pants/blob/ad20ba4d303cf293b0bf0ed5d18280f725b11c27/build-support/bin/generate_docs.py#L232-L241 we really ought to generate these lists from an authoritative source where we list all backends and have options like: * [ ] include in dist * [ ] include in docs * [ ] ....
2023-08-08T23:06:08
pantsbuild/pants
19,577
pantsbuild__pants-19577
[ "19273" ]
6183f1050f54385f76d5819d9085dec7b54d8baa
diff --git a/build-support/bin/generate_docs.py b/build-support/bin/generate_docs.py --- a/build-support/bin/generate_docs.py +++ b/build-support/bin/generate_docs.py @@ -196,8 +196,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.experimental.python", "pants.backend.experimental.python.framework.stevedore", "pants.backend.experimental.python.lint.add_trailing_comma", - "pants.backend.experimental.python.lint.autoflake", - "pants.backend.experimental.python.lint.pyupgrade", + "pants.backend.experimental.python.lint.ruff", "pants.backend.experimental.python.packaging.pyoxidizer", "pants.backend.experimental.scala", "pants.backend.experimental.scala.lint.scalafmt", @@ -206,6 +205,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.google_cloud_function.python", "pants.backend.plugin_development", "pants.backend.python", + "pants.backend.python.lint.autoflake", "pants.backend.python.lint.bandit", "pants.backend.python.lint.black", "pants.backend.python.lint.docformatter", @@ -213,6 +213,7 @@ def run_pants_help_all() -> dict[str, Any]: "pants.backend.python.lint.isort", "pants.backend.python.lint.pydocstyle", "pants.backend.python.lint.pylint", + "pants.backend.python.lint.pyupgrade", "pants.backend.python.lint.yapf", "pants.backend.python.mixed_interpreter_constraints", "pants.backend.python.typecheck.mypy",
`ruff` backend missing from 2.16.x docs **Describe the bug** See https://www.pantsbuild.org/v2.16/docs/reference-all-subsystems. I think it's just missing from docs because I see it in the wheel.
guess it's another list it needs to be a member of for that: https://github.com/pantsbuild/pants/blob/ad20ba4d303cf293b0bf0ed5d18280f725b11c27/build-support/bin/generate_docs.py#L232-L241 we really ought to generate these lists from an authoritative source where we list all backends and have options like: * [ ] include in dist * [ ] include in docs * [ ] ....
2023-08-08T23:06:31
pantsbuild/pants
19,654
pantsbuild__pants-19654
[ "19600" ]
8ababcb54230bd2b200fba82a57dab5ecdbffd02
diff --git a/src/python/pants/bin/pants_runner.py b/src/python/pants/bin/pants_runner.py --- a/src/python/pants/bin/pants_runner.py +++ b/src/python/pants/bin/pants_runner.py @@ -8,6 +8,9 @@ from dataclasses import dataclass from typing import List, Mapping +from packaging.version import Version + +from pants.base.deprecated import warn_or_error from pants.base.exception_sink import ExceptionSink from pants.base.exiter import ExitCode from pants.engine.env_vars import CompleteEnvironmentVars @@ -20,6 +23,10 @@ logger = logging.getLogger(__name__) +# Pants 2.18 is using a new distribution model, that's only supported in 0.9.0 (this is 0.9.2, +# because _detecting_ the version is only supported from 0.9.2), so people should upgrade +MINIMUM_SCIE_PANTS_VERSION = Version("0.9.2") + @dataclass(frozen=True) class PantsRunner: @@ -80,7 +87,11 @@ def run(self, start_time: float) -> ExitCode: stdout_fileno=stdout_fileno, stderr_fileno=stderr_fileno, ): - if "SCIE" not in os.environ and "NO_SCIE_WARNING" not in os.environ: + run_via_scie = "SCIE" in os.environ + enable_scie_warning = "NO_SCIE_WARNING" not in os.environ + scie_pants_version = os.environ.get("SCIE_PANTS_VERSION") + + if not run_via_scie and enable_scie_warning: raise RuntimeError( softwrap( f""" @@ -90,6 +101,27 @@ def run(self, start_time: float) -> ExitCode: ), ) + if run_via_scie and ( + # either scie-pants is too old to communicate its version: + scie_pants_version is None + # or the version itself is too old: + or Version(scie_pants_version) < MINIMUM_SCIE_PANTS_VERSION + ): + current_version_text = ( + f"The current version of the `pants` launcher binary is {scie_pants_version}" + if scie_pants_version + else "Run `PANTS_BOOTSTRAP_VERSION=report pants` to see the current version of the `pants` launcher binary" + ) + warn_or_error( + "2.18.0.dev6", + f"using a `pants` launcher binary older than {MINIMUM_SCIE_PANTS_VERSION}", + softwrap( + f""" + {current_version_text}, and see {doc_url("installation")} for how to upgrade. + """ + ), + ) + # N.B. We inline imports to speed up the python thin client run, and avoids importing # engine types until after the runner has had a chance to set __PANTS_BIN_NAME. if self._should_run_with_pantsd(global_bootstrap_options):
detect older versions of scie-pants and emit deprecation warning if too old With the source of truth for Pants releases moving to GitHub from PyPi, `scie-pants` will need to be upgraded to v0.9.x(?) in order to consume GitHub releases. To help inform users, we should consider having Pants detect the scie-pants versions it is running under and emit a deprecation warning to inform the user about the need to upgrade.
I'm going to add this to 2.17.x unless we decide otherwise so that it doesn't slip through the cracks. @thejcannon suggests a good place to start for this would be: https://github.com/pantsbuild/pants/blob/06321e5edf3f648f39f0abc7b11d348181a15a31/src/python/pants/bin/pants_runner.py#L83 I'll see if I have time for this later today.
2023-08-23T01:46:53
pantsbuild/pants
19,655
pantsbuild__pants-19655
[ "19600" ]
98bd5a8bcf6a9373b12dbf26191abadd2b1291d5
diff --git a/src/python/pants/bin/pants_runner.py b/src/python/pants/bin/pants_runner.py --- a/src/python/pants/bin/pants_runner.py +++ b/src/python/pants/bin/pants_runner.py @@ -8,6 +8,8 @@ from dataclasses import dataclass from typing import List, Mapping +from packaging.version import Version + from pants.base.deprecated import warn_or_error from pants.base.exception_sink import ExceptionSink from pants.base.exiter import ExitCode @@ -21,6 +23,10 @@ logger = logging.getLogger(__name__) +# Pants 2.18 is using a new distribution model, that's only supported in 0.9.0 (this is 0.9.2, +# because _detecting_ the version is only supported from 0.9.2), so people should upgrade +MINIMUM_SCIE_PANTS_VERSION = Version("0.9.2") + @dataclass(frozen=True) class PantsRunner: @@ -83,7 +89,11 @@ def run(self, start_time: float) -> ExitCode: ): # N.B. We inline imports to speed up the python thin client run, and avoids importing # engine types until after the runner has had a chance to set __PANTS_BIN_NAME. - if "SCIE" not in os.environ and "NO_SCIE_WARNING" not in os.environ: + run_via_scie = "SCIE" in os.environ + enable_scie_warning = "NO_SCIE_WARNING" not in os.environ + scie_pants_version = os.environ.get("SCIE_PANTS_VERSION") + + if not run_via_scie and enable_scie_warning: warn_or_error( "2.18.0.dev0", f"Running Pants in an external Python interpreter via a `{bin_name()}` script", @@ -95,6 +105,27 @@ def run(self, start_time: float) -> ExitCode: ), ) + if run_via_scie and ( + # either scie-pants is too old to communicate its version: + scie_pants_version is None + # or the version itself is too old: + or Version(scie_pants_version) < MINIMUM_SCIE_PANTS_VERSION + ): + current_version_text = ( + f"The current version of the `pants` launcher binary is {scie_pants_version}" + if scie_pants_version + else "Run `PANTS_BOOTSTRAP_VERSION=report pants` to see the current version of the `pants` launcher binary" + ) + warn_or_error( + "2.18.0.dev6", + f"using a `pants` launcher binary older than {MINIMUM_SCIE_PANTS_VERSION}", + softwrap( + f""" + {current_version_text}, and see {doc_url("installation")} for how to upgrade. + """ + ), + ) + if self._should_run_with_pantsd(global_bootstrap_options): from pants.bin.remote_pants_runner import RemotePantsRunner
detect older versions of scie-pants and emit deprecation warning if too old With the source of truth for Pants releases moving to GitHub from PyPi, `scie-pants` will need to be upgraded to v0.9.x(?) in order to consume GitHub releases. To help inform users, we should consider having Pants detect the scie-pants versions it is running under and emit a deprecation warning to inform the user about the need to upgrade.
I'm going to add this to 2.17.x unless we decide otherwise so that it doesn't slip through the cracks. @thejcannon suggests a good place to start for this would be: https://github.com/pantsbuild/pants/blob/06321e5edf3f648f39f0abc7b11d348181a15a31/src/python/pants/bin/pants_runner.py#L83 I'll see if I have time for this later today.
2023-08-23T03:57:17
pantsbuild/pants
19,694
pantsbuild__pants-19694
[ "19600" ]
f1ec650c329742ff8ba46b68a805bf259aea51a6
diff --git a/src/python/pants/bin/pants_runner.py b/src/python/pants/bin/pants_runner.py --- a/src/python/pants/bin/pants_runner.py +++ b/src/python/pants/bin/pants_runner.py @@ -8,6 +8,9 @@ from dataclasses import dataclass from typing import List, Mapping +from packaging.version import Version + +from pants.base.deprecated import warn_or_error from pants.base.exception_sink import ExceptionSink from pants.base.exiter import ExitCode from pants.engine.env_vars import CompleteEnvironmentVars @@ -20,6 +23,10 @@ logger = logging.getLogger(__name__) +# Pants 2.18 is using a new distribution model, that's only supported in 0.9.0 (this is 0.9.2, +# because _detecting_ the version is only supported from 0.9.2), so people should upgrade +MINIMUM_SCIE_PANTS_VERSION = Version("0.9.2") + @dataclass(frozen=True) class PantsRunner: @@ -80,7 +87,11 @@ def run(self, start_time: float) -> ExitCode: stdout_fileno=stdout_fileno, stderr_fileno=stderr_fileno, ): - if "SCIE" not in os.environ and "NO_SCIE_WARNING" not in os.environ: + run_via_scie = "SCIE" in os.environ + enable_scie_warning = "NO_SCIE_WARNING" not in os.environ + scie_pants_version = os.environ.get("SCIE_PANTS_VERSION") + + if not run_via_scie and enable_scie_warning: raise RuntimeError( softwrap( f""" @@ -90,6 +101,27 @@ def run(self, start_time: float) -> ExitCode: ), ) + if run_via_scie and ( + # either scie-pants is too old to communicate its version: + scie_pants_version is None + # or the version itself is too old: + or Version(scie_pants_version) < MINIMUM_SCIE_PANTS_VERSION + ): + current_version_text = ( + f"The current version of the `pants` launcher binary is {scie_pants_version}" + if scie_pants_version + else "Run `PANTS_BOOTSTRAP_VERSION=report pants` to see the current version of the `pants` launcher binary" + ) + warn_or_error( + "2.18.0.dev6", + f"using a `pants` launcher binary older than {MINIMUM_SCIE_PANTS_VERSION}", + softwrap( + f""" + {current_version_text}, and see {doc_url("installation")} for how to upgrade. + """ + ), + ) + # N.B. We inline imports to speed up the python thin client run, and avoids importing # engine types until after the runner has had a chance to set __PANTS_BIN_NAME. if self._should_run_with_pantsd(global_bootstrap_options):
detect older versions of scie-pants and emit deprecation warning if too old With the source of truth for Pants releases moving to GitHub from PyPi, `scie-pants` will need to be upgraded to v0.9.x(?) in order to consume GitHub releases. To help inform users, we should consider having Pants detect the scie-pants versions it is running under and emit a deprecation warning to inform the user about the need to upgrade.
I'm going to add this to 2.17.x unless we decide otherwise so that it doesn't slip through the cracks. @thejcannon suggests a good place to start for this would be: https://github.com/pantsbuild/pants/blob/06321e5edf3f648f39f0abc7b11d348181a15a31/src/python/pants/bin/pants_runner.py#L83 I'll see if I have time for this later today.
2023-08-29T22:10:24
pantsbuild/pants
19,718
pantsbuild__pants-19718
[ "19705" ]
23883277dd9e14cafc015f2ba0762e0ec2315bba
diff --git a/build-support/bin/generate_docs.py b/build-support/bin/generate_docs.py --- a/build-support/bin/generate_docs.py +++ b/build-support/bin/generate_docs.py @@ -320,6 +320,59 @@ def _link(scope: str, *, sync: bool) -> str: url_safe_scope = scope.replace(".", "-") return f"reference-{url_safe_scope}" if sync else f"{url_safe_scope}.md" + @staticmethod + def _generate_toml_snippet(option_data, scope) -> str: + """Generate TOML snippet for a single option.""" + + # Generate a toml block for the option to help users fill out their `pants.toml`. For + # scalars and arrays, we put them inline directly in the scope, while for maps we put + # them in a nested table. Since the metadata doesn't contain type info, we'll need to + # parse command line args a bit. + + if not option_data.get("config_key", None): + # This option is not configurable. + return "" + + toml_lines = [] + example_cli = option_data["display_args"][0] + config_key = option_data["config_key"] + + if "[no-]" in example_cli: + val = "<bool>" + else: + _, val = example_cli.split("=", 1) + + is_map = val.startswith('"{') and val.endswith('}"') + is_array = val.startswith('"[') and val.endswith(']"') + if is_map: + toml_lines.append(f"[{scope}.{config_key}]") + val = val[2:-2] # strip the quotes and brackets + + pairs = val.split(", ") + for pair in pairs: + if ":" in pair: + k, v = pair.split(": ", 1) + if k.startswith('"') or k.startswith("'"): + k = k[1:-1] + + toml_lines.append(f"{k} = {v}") + else: + # generally just the trailing ... + toml_lines.append(pair) + + elif is_array: + toml_lines.append(f"[{scope}]") + toml_lines.append(f"{config_key} = [") + val = val[2:-2] + for item in val.split(", "): + toml_lines.append(f" {item},") + toml_lines.append("]") + else: + toml_lines.append(f"[{scope}]") + toml_lines.append(f"{config_key} = {val}") + + return "\n".join(toml_lines) + @classmethod def process_options_input(cls, help_info: dict[str, Any], *, sync: bool) -> dict: scope_to_help_info = help_info["scope_to_help_info"] @@ -342,7 +395,7 @@ def process_options_input(cls, help_info: dict[str, Any], *, sync: bool) -> dict # Process the option data. - def munge_option(option_data): + def munge_option(option_data, scope): # Munge the default so we can display it nicely when it's multiline, while # still displaying it inline if it's not. default_help_repr = option_data.get("default_help_repr") @@ -369,13 +422,15 @@ def munge_option(option_data): else: option_data["marked_up_default"] = f"<code>{escaped_default_str}</code>" - for shi in scope_to_help_info.values(): + option_data["toml"] = cls._generate_toml_snippet(option_data, scope) + + for scope, shi in scope_to_help_info.items(): for opt in shi["basic"]: - munge_option(opt) + munge_option(opt, scope) for opt in shi["advanced"]: - munge_option(opt) + munge_option(opt, scope) for opt in shi["deprecated"]: - munge_option(opt) + munge_option(opt, scope) return help_info
Add `toml` syntax in backend option documentation **Is your feature request related to a problem? Please describe.** Right now all (most?) documentation for backends uses command-line syntax to show to configure options: ``` --python-resolves-to-interpreter-constraints="{'key1': val1, 'key2': val2, ...}" ``` However, most configuration is actually provided in `pants.toml`. Overriding on the command line often causes `pantsd` to restart as well, making it an inefficient pattern for general use. **Describe the solution you'd like** It might make more sense to focus on `toml` syntax for configuration examples in the references like we do in the manuals. **Additional context** From a thread on Slack: > I don't understand how to specify this option. It seems like it's supposed to be provided as an object, but AFAIK that's not possible in TOML directly? Or is this something that must be provided at runtime?
Since this is generated I'd guess it should be fairly easy to change all, but I can't find the script: ```shell ✦ ❯ rg 'generate-docs' docs/NOTES.md 3:Pants currently hosts documentation at Readme.com, and we use a combination of their `rdme` tool to sync handwritten markdown docs, and a custom `generate-docs` script to update Pants' reference documentation. ✦ ❯ fd generate-docs ✦ ❯ ``` Rotten docs? Yeah the docs are overly abbreviated: it's a `.py` file and has an underscore...: https://github.com/pantsbuild/pants/blob/7a292e4bc3b6e5406b7a74398a9963b34d38e909/build-support/bin/generate_docs.py There are two unrelated "docs generation" processes. One for the guides, whose sources are markdown pages, another for the reference docs, whose sources are the code. In this case you want to look at src/python/pants/help for cmd-line help, and build-support/bin/generate_docs.py for the pantsbuild.org reference docs pages.
2023-08-30T18:39:24
pantsbuild/pants
19,796
pantsbuild__pants-19796
[ "17403" ]
9bd3a3019567800692b109563ccd3d65bc921772
diff --git a/src/python/pants/core/goals/fix.py b/src/python/pants/core/goals/fix.py --- a/src/python/pants/core/goals/fix.py +++ b/src/python/pants/core/goals/fix.py @@ -36,6 +36,7 @@ from pants.util.collections import partition_sequentially from pants.util.docutil import bin_name from pants.util.logging import LogLevel +from pants.util.ordered_set import FrozenOrderedSet from pants.util.strutil import softwrap, strip_v2_chroot_path logger = logging.getLogger(__name__) @@ -126,7 +127,7 @@ class Batch(AbstractLintRequest.Batch): @property def files(self) -> tuple[str, ...]: - return self.elements + return tuple(FrozenOrderedSet(self.elements)) @classmethod def _get_rules(cls) -> Iterable[UnionRule]: @@ -294,7 +295,7 @@ def batch_by_size(files: Iterable[str]) -> Iterator[tuple[str, ...]]: yield tuple(batch) def _make_disjoint_batch_requests() -> Iterable[_FixBatchRequest]: - partition_infos: Sequence[Tuple[Type[AbstractFixRequest], Any]] + partition_infos: Iterable[Tuple[Type[AbstractFixRequest], Any]] files: Sequence[str] partition_infos_by_files = defaultdict(list) @@ -306,7 +307,8 @@ def _make_disjoint_batch_requests() -> Iterable[_FixBatchRequest]: files_by_partition_info = defaultdict(list) for file, partition_infos in partition_infos_by_files.items(): - files_by_partition_info[tuple(partition_infos)].append(file) + deduped_partition_infos = FrozenOrderedSet(partition_infos) + files_by_partition_info[deduped_partition_infos].append(file) for partition_infos, files in files_by_partition_info.items(): for batch in batch_by_size(files):
diff --git a/src/python/pants/core/goals/fix_test.py b/src/python/pants/core/goals/fix_test.py --- a/src/python/pants/core/goals/fix_test.py +++ b/src/python/pants/core/goals/fix_test.py @@ -36,10 +36,17 @@ Snapshot, ) from pants.engine.rules import Get, QueryRule, collect_rules, rule -from pants.engine.target import FieldSet, MultipleSourcesField, SingleSourceField, Target +from pants.engine.target import ( + FieldSet, + MultipleSourcesField, + SingleSourceField, + StringField, + Target, +) from pants.option.option_types import SkipOption from pants.option.subsystem import Subsystem from pants.testutil.rule_runner import RuleRunner +from pants.testutil.rule_runner import logging as log_this from pants.util.logging import LogLevel from pants.util.meta import classproperty @@ -128,9 +135,17 @@ class SmalltalkSource(SingleSourceField): pass +# NB: This extra field is required to help us in `test_batches` below. +# With it, each `SmalltalkTarget` we instantiate will produce a different `SmalltalkFieldSet` +# (even with the same `source` field value), which then results in https://github.com/pantsbuild/pants/issues/17403. +# See https://github.com/pantsbuild/pants/pull/19796. +class SmalltalkExtraField(StringField): + alias = "extra" + + class SmalltalkTarget(Target): alias = "smalltalk" - core_fields = (SmalltalkSource,) + core_fields = (SmalltalkSource, SmalltalkExtraField) @dataclass(frozen=True) @@ -253,6 +268,7 @@ def fix_rule_runner( ) +@log_this(level=LogLevel.INFO) def run_fix( rule_runner: RuleRunner, *, @@ -288,6 +304,30 @@ def write_files(rule_runner: RuleRunner) -> None: ) +def test_batches(capfd) -> None: + rule_runner = fix_rule_runner( + target_types=[SmalltalkTarget], + request_types=[SmalltalkNoopRequest], + ) + + rule_runner.write_files( + { + "BUILD": dedent( + """\ + smalltalk(name='s1-1', source="duplicate1.st") + smalltalk(name='s1-2', source="duplicate1.st") + smalltalk(name='s2-1', source="duplicate1.st") + smalltalk(name='s2-2', source="duplicate2.st") + """, + ), + "duplicate1.st": "", + "duplicate2.st": "", + }, + ) + run_fix(rule_runner, target_specs=["::"]) + assert capfd.readouterr().err.count("Smalltalk Did Not Change made no changes.") == 1 + + def test_summary() -> None: rule_runner = fix_rule_runner( target_types=[FortranTarget, SmalltalkTarget], @@ -503,7 +543,7 @@ class FixKitchenRequest(FixTargetsRequest): QueryRule(Partitions, [FixKitchenRequest.PartitionRequest]), ] rule_runner = RuleRunner(rules=rules) - print(rule_runner.write_files({"BUILD": "", "knife.utensil": "", "bowl.utensil": ""})) + rule_runner.write_files({"BUILD": "", "knife.utensil": "", "bowl.utensil": ""}) partitions = rule_runner.request(Partitions, [FixKitchenRequest.PartitionRequest(field_sets)]) assert len(partitions) == 1 assert partitions[0].elements == ("bowl.utensil", "knife.utensil") diff --git a/src/python/pants/core/goals/lint_test.py b/src/python/pants/core/goals/lint_test.py --- a/src/python/pants/core/goals/lint_test.py +++ b/src/python/pants/core/goals/lint_test.py @@ -26,7 +26,7 @@ ) from pants.core.util_rules.distdir import DistDir from pants.core.util_rules.environments import EnvironmentNameRequest -from pants.core.util_rules.partitions import PartitionerType +from pants.core.util_rules.partitions import PartitionerType, _EmptyMetadata from pants.engine.addresses import Address from pants.engine.environment import EnvironmentName from pants.engine.fs import PathGlobs, SpecsPaths, Workspace @@ -403,6 +403,15 @@ def run_lint_rule( return result.exit_code, stdio_reader.get_stderr() +def test_duplicate_files_in_fixer(rule_runner: RuleRunner) -> None: + assert MockFixRequest.Batch( + "tool_name", + ("a", "a"), + _EmptyMetadata(), + rule_runner.make_snapshot({"a": ""}), + ).files == ("a",) + + def test_invalid_target_noops(rule_runner: RuleRunner) -> None: exit_code, stderr = run_lint_rule( rule_runner, lint_request_types=[InvalidRequest], targets=[make_target()]
lint fails after fix & fmt didn't changed anything **Describe the bug** the title says it **Pants version** current main d05c4370b9cae86763f7b9826c5a16ac772ebb99 **OS** Linux pop-os 6.0.2-76060002-generic #202210150739~1666289067~22.04~fe0ce53 SMP PREEMPT_DYNAMIC Thu O x86_64 x86_64 x86_64 GNU/Linux **Additional info** this is the file that didn't pass the lint but it passes the fix & fmt without any changes ``` import tuhls.dashboard.settings as dashboard_settings import utils.config as cfg from django.conf import settings c = cfg.ConfigDict() apps = cfg.ConfigList( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "tuhls.dashboard", "tuhls.dashboard.tests.dashboard_test", "tuhls.icons", ) c = cfg.base_settings(c, "dashboardtest", apps, True) c = cfg.template_settings(c) c = cfg.db_sqlite_test_settings(c) c = dashboard_settings.base(c) c.ROOT_URLCONF = "tuhls.dashboard.urls" c.AUTH_USER_MODEL = "dashboard_test.TestUser" c.LOGIN_URL = "/login/" c.LOGOUT_REDIRECT_URL = "/" settings.configure(**c) ``` as you can see, isort removed the double blank line after the imports (i think that's wrong) but if i add the double blank line and run only lint it fails anyway it could be a isort bug. i have ~1k python source files and it happens only in this file is there an easy way to change the python tool versions?
i think i've found the way to change the isort version: https://www.pantsbuild.org/docs/reference-isort#version so i can narrow it down a little bit further with pants 2.14 this file gets fixed to ``` from django.conf import settings import tuhls.dashboard.settings as dashboard_settings import utils.config as cfg c = cfg.ConfigDict() apps = cfg.ConfigList( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "tuhls.dashboard", "tuhls.dashboard.tests.dashboard_test", "tuhls.icons", ) c = cfg.base_settings(c, "dashboardtest", apps, True) c = cfg.template_settings(c) c = cfg.db_sqlite_test_settings(c) c = dashboard_settings.base(c) c.ROOT_URLCONF = "tuhls.dashboard.urls" c.AUTH_USER_MODEL = "dashboard_test.TestUser" c.LOGIN_URL = "/login/" c.LOGOUT_REDIRECT_URL = "/" settings.configure(**c) ``` and the lint step is happy about it the isort version is the same in main and 2.14. could it be that isort isn't detecting django as an external lib? This might be https://github.com/pantsbuild/pants/issues/15069. Are you running the exact same command with `fmt` vs. `lint`, i.e. the same e.g. file arguments? `./pants fmt path/to/dir` and then `./pants lint path/to/dir`? If those arguments of what to run are are different, then https://github.com/pantsbuild/pants/issues/15069 may be kicking in. Yeah, https://github.com/pantsbuild/pants/issues/15069 was going to be my guess. The workaround is to configure the first-party packages explicitly in isort config. im running `./pants fix lint ::` edit: and its running fine with 2.14 tried every combination of `known_first_party` `known_third_party` `default_section` `resolve_all_configs` and isort version with the exact same outcome :( Are you using both `black` and `isort`, or only `isort`? both, but with this setting in pyproject.toml ``` [tool.isort] profile = "black" ``` and it worked before, in 2.14 and 2.13 ;) Hmm, I can't reproduce this on that file so far. @thelittlebug are you able to create a standalone github repo that reproduces the problem (either at Pants 2.15.0a0, or while running from Pants sources at the SHA you mentioned)? Right now I can't reproduce it. Any solution to this? We are having the same issue migrating from 2.14 to 2.15. On 2.14 running `./pants fmt lint ::` had no issues, on 2.15 the `fmt` command does not change anything but `lint` fails. ``` ./pants --no-pantsd fmt lint :: FTN-1328_update_pants 18:10:21.76 [INFO] Completed: Format with Black - black made no changes. 18:10:23.14 [INFO] Completed: Format with isort - isort made no changes. ✓ black made no changes. ✓ isort made no changes. 18:10:23.37 [INFO] Completed: Format with Black - black made no changes. 18:10:23.42 [INFO] Completed: Lint with Flake8 - flake8 succeeded. Partition: ['CPython>=3.10'] 18:10:23.43 [WARN] Completed: Format with isort - isort made changes. # list of files with changes # some more irrelevant logs ✓ bandit succeeded. ✓ black succeeded. ✓ flake8 succeeded. ✕ isort failed. ``` Huh, this probably isn't https://github.com/pantsbuild/pants/issues/15069 then, since that would kick in if you were not running on the same underlying set of files each time. But you're running on `::`. A small repo that reproduces this issue would be the best way to proceed with debugging this. @gabrielhora are you able to create one based on one of the problematic files? Feel free to obscure the content of the file to avoid exposing proprietary code, we just need some reliable way to reproduce the problem. I'm trying to come up with a test repo but no luck so far. I have no idea what might be causing this in our main repository (which is quite sizeable by now) so it's really hard to come up with a test scenario. There doesn't seem to be anything special with the files that `lint` fails, they have third-party, stdlib and local imports. Not sure if this helpful but in my case it looks like it's not recognising the `lib.redacted` as a local package anymore, so apparently it's trying to move it to a third-party import block for some reason. ``` --- /private/var/folders/5b/1gwwv9v51hb82w76bhcxs5680000gn/T/pants-sandbox-PVkRrO/src/redacted/extractor/tests/samples.py:before 2023-03-21 20:48:37.823102 +++ /private/var/folders/5b/1gwwv9v51hb82w76bhcxs5680000gn/T/pants-sandbox-PVkRrO/src/redacted/extractor/tests/samples.py:after 2023-03-21 20:48:38.111443 @@ -6,10 +6,10 @@ from typing import Any, Dict, List import yaml +from lib.redacted.parser.main import from_bytes as parse +from lib.redacted.parser.schemas import record_to_dict from ruamel.yaml import YAML -from lib.redacted.parser.main import from_bytes as parse -from lib.redacted.parser.schemas import record_to_dict from redacted.extractor.schema import Record ``` So, I've added this to isort settings and that fixed the issue! Now fmt and lint are working well together and the `lib.*` imports are grouped with other local first party imports. ``` [tool.isort] known_first_party = ["lib.*"] ``` It's strange that only packages in `lib/` have this problem, all other first party packages are recognised correctly! Something special with that name? Huh. I guess there must be. But the disturbing part is why this was different between `fix` and `lint`. And it sounds like that doesn't happen if you take `black` out of the mix? There is this 3rdparty library: https://pypi.org/project/lib/ But I think that's a red herring, presumably isort knows about stdlib, and looks for firstparty in your source roots, and assumes everything else is thirdparty. What does `pants roots` show? Is the parent of `lib` a source root? Is it supposed to be? I.e., are you intentionally importing from `lib. redacted` rather than from `redacted`? > And it sounds like that doesn't happen if you take `black` out of the mix? Removing `black` does not change anything. Without the `known_first_party` it still fails. > But I think that's a red herring, presumably isort knows about stdlib, and looks for firstparty in your source roots, and assumes everything else is thirdparty. And the weird part as well is why pants `2.14` works as expected and `2.15` changes this behaviour. > What does `pants roots` show? Is the parent of `lib` a source root? Is it supposed to be? I.e., are you intentionally importing from `lib. redacted` rather than from `redacted`? ```console $ ./pants roots . src ``` `lib` is a normal package like any other inside the `src` source root. Sorry, my previous output might be a bit confusing because of the repeated `redacted` name. The folder structure look something like this: ``` . ├── src │   ├── lib │   │   ├── subpackage_1 │   │   └── subpackage_2 │   ├── package1 │   │   ├── another_subpackage_1 │   │   └── another_subpackage_2 │   ├── package2 │   └── ... ├── pants └── pants.toml ``` Yeah that 2.14->2.15 thing is a good clue. Any kind of reproduction repo you can share would be fantastic. Hey @benjyw I think I finally got a reproducible repository https://github.com/gabrielhora/pants_17403. It looks like it has to do with resolves, if I remove the multiple resolves and the `parametrize` calls in the `BUILD` files then it all works. So maybe I have something mis-configured? This seems to work on `2.14.0` but fails on `2.15.0`. Thanks, this is golden. I can reproduce, so will dive deeper. Looks like `fmt` runs in two partitions, one for the `lib/` files and one for the `project/` files. Not sure why yet, but presumably related to the two resolves. Whereas `lint` runs over all files in one partition. So when `fmt` runs on `src/project/main.py` it doesn't have `lib/` in the sandbox, and so doesn't see it as first-party, whereas when `lint` runs, it does. Note also that in `lint` mode, Pants lists each file under `lib/` *twice* as input to isort, presumably once per resolve those python_sources are parameterized over (although this doesn't seem to be harmful, it indicates that Pants doesn't know what it's doing). So it seems like there is major confusion in Pants on how to handle resolves here. There is partitioning discrepancy between `lint` and `fmt`, and `lint` sees the `lib` files twice. So this is ultimately an `isort` issue (depending on how you're looking at it) since any formatter _shouldnt_ be changing behavior when you run it on M files, or a subset of M files. (Not saying there isn't a Pants bug (or many) but fixing those would paper over the underling issue) Ah OK, this makes sense if you look at the world from Pants' point of view. First let's look at `fmt`: In `fmt`'s eyes, we have a tool to run and we have files. We don't care about pretty much any metadata associated with the file. We don't care about the file's dependencies. We don't care about the file's resolves. Make 1000 resolves for the file, it's still the same file :smile: So when we look at what to format, we look at _files_ (albeit we didn't dedup when we went from addresses -> files, whoops!) Ok, now for `lint`: `lint` operates on targets. You can `lint` things that aren't files (I lint `python_requirements` at $work to check their licenses). So when `lint` needs to divvy things up, it does so by _address_. Well now we've diverged from `fmt`, because 1 file now has multiple _addresses_. ...and :boom: we've run `isort` on different batches and the nasty nasty little bug that persistently plagues us appears. --- So, we definitely should de-dup in `fmt`. I'll open a new ticket for that. As for de-duping in `lint`.... yeah maybe? I'll keep this open as I think about it. Either way, thanks for the report and reproduction. This was very helpful! FWIW I'm going to close as duplicate of https://github.com/pantsbuild/pants/issues/15069 Be sure to track that one!
2023-09-07T20:59:15
pantsbuild/pants
19,858
pantsbuild__pants-19858
[ "3423" ]
7c60c17431aaba180df169a40a63ed6df527beb0
diff --git a/src/python/pants/backend/python/goals/repl.py b/src/python/pants/backend/python/goals/repl.py --- a/src/python/pants/backend/python/goals/repl.py +++ b/src/python/pants/backend/python/goals/repl.py @@ -71,6 +71,7 @@ def maybe_get_resolve(t: Target) -> str | None: class PythonRepl(ReplImplementation): name = "python" + supports_args = False @rule(level=LogLevel.DEBUG) @@ -124,6 +125,7 @@ async def create_python_repl_request( class IPythonRepl(ReplImplementation): name = "ipython" + supports_args = True @rule(level=LogLevel.DEBUG) diff --git a/src/python/pants/backend/scala/goals/repl.py b/src/python/pants/backend/scala/goals/repl.py --- a/src/python/pants/backend/scala/goals/repl.py +++ b/src/python/pants/backend/scala/goals/repl.py @@ -25,6 +25,7 @@ class ScalaRepl(ReplImplementation): name = "scala" + supports_args = False @rule(level=LogLevel.DEBUG) diff --git a/src/python/pants/core/goals/repl.py b/src/python/pants/core/goals/repl.py --- a/src/python/pants/core/goals/repl.py +++ b/src/python/pants/core/goals/repl.py @@ -5,7 +5,7 @@ import os from abc import ABC from dataclasses import dataclass -from typing import ClassVar, Iterable, Mapping, Optional, Sequence, Tuple +from typing import ClassVar, Iterable, Mapping, Optional, Sequence, Tuple, Type, cast from pants.core.util_rules.environments import _warn_on_non_local_environments from pants.engine.addresses import Addresses @@ -18,7 +18,7 @@ from pants.engine.rules import Effect, Get, collect_rules, goal_rule from pants.engine.target import FilteredTargets, Target from pants.engine.unions import UnionMembership, union -from pants.option.option_types import BoolOption, StrOption +from pants.option.option_types import ArgsListOption, BoolOption, StrOption from pants.util.frozendict import FrozenDict from pants.util.memo import memoized_property from pants.util.strutil import softwrap @@ -33,6 +33,7 @@ class ReplImplementation(ABC): """ name: ClassVar[str] + supports_args: ClassVar[bool] targets: Sequence[Target] @@ -56,6 +57,12 @@ def activated(cls, union_membership: UnionMembership) -> bool: default=None, help="Override the automatically-detected REPL program for the target(s) specified.", ) + args = ArgsListOption( + example="-i helloworld/main.py", + tool_name="the repl program", + passthrough=True, + extra_help="Currently supported only for the ipython shell.", + ) restartable = BoolOption( default=False, help="True if the REPL should be restarted if its inputs have changed.", @@ -110,7 +117,9 @@ async def run_repl( # on the targets. For now we default to the python repl. repl_shell_name = repl_subsystem.shell or "python" implementations = {impl.name: impl for impl in union_membership[ReplImplementation]} - repl_implementation_cls = implementations.get(repl_shell_name) + repl_implementation_cls = cast( + Optional[Type[ReplImplementation]], implementations.get(repl_shell_name) + ) if repl_implementation_cls is None: available = sorted(implementations.keys()) console.print_stderr( @@ -123,14 +132,25 @@ async def run_repl( ) return Repl(-1) + if repl_subsystem.args and not repl_implementation_cls.supports_args: + console.print_stderr( + softwrap( + f""" + REPL goal does not support passing args to a {repr(repl_shell_name)} shell. + """ + ) + ) + return Repl(-1) + repl_impl = repl_implementation_cls(targets=specified_targets) request = await Get(ReplRequest, ReplImplementation, repl_impl) env = {**complete_env, **request.extra_env} + result = await Effect( InteractiveProcessResult, InteractiveProcess( - argv=request.args, + argv=(*request.args, *repl_subsystem.args), env=env, input_digest=request.digest, run_in_workspace=request.run_in_workspace,
diff --git a/src/python/pants/core/goals/repl_test.py b/src/python/pants/core/goals/repl_test.py --- a/src/python/pants/core/goals/repl_test.py +++ b/src/python/pants/core/goals/repl_test.py @@ -13,6 +13,7 @@ class MockRepl(ReplImplementation): name = "mock" + supports_args = False @rule
Add support for passthrough args to the python repl In particular, the `ipython` repl supports CLI arguments like: ``` ipython notebook ``` which launches a visual repl. Supporting passthrough args would mean that: ``` ./pants repl.py --ipython $target -- notebook $file ``` would work (assuming you added the relevant 'notebook' deps to `--ipython-requirements`) --- To do this, you would enable passthru args on the `PythonRepl` task by overriding the `supports_passthru_args` property to True ([example](https://github.com/pantsbuild/pants/blob/9f2bd17640a29ee7ad34d353efdd979222a75f70/src/python/pants//backend/jvm/tasks/jvm_run.py#L49-L51)), and then pass any additional `self.get_passthru_args()` as args [while launching the repl](https://github.com/pantsbuild/pants/blob/9f2bd17640a29ee7ad34d353efdd979222a75f70/src/python/pants/backend/python/tasks/python_repl.py#L32). You could then add either a [unit](https://github.com/pantsbuild/pants/blob/7ae9a31508e61a237a1dcf650d0626b1f1b07af6/tests/python/pants_test/backend/python/tasks/test_python_repl.py#L25) or [integration](https://github.com/pantsbuild/pants/blob/7ae9a31508e61a237a1dcf650d0626b1f1b07af6/tests/python/pants_test/backend/python/tasks/test_python_repl_integration.py#L11) test for the passthru.
Thanks @stuhood I believe this works with both the v1 and v2 implementations. See https://pants.readme.io/docs/python-repl-goal. Oh, nevermind. Confused with `run`. Reopening.
2023-09-18T14:11:19
pantsbuild/pants
19,899
pantsbuild__pants-19899
[ "19820" ]
1bb84ed4720525b79fcdf3fd3664b8c087043982
diff --git a/src/python/pants/backend/experimental/tools/yamllint/__init__.py b/src/python/pants/backend/experimental/tools/yamllint/__init__.py new file mode 100644
Missing `pants/backend/experimental/tools/yamllint/__init__.py` file ``` Can not check requirements for backend: 'pants.backend.experimental.tools.yamllint'. A __init__.py file is probably missing. ``` Tagging as internal as I don't believe it has a practical impact.
2023-09-21T21:00:45
pantsbuild/pants
19,906
pantsbuild__pants-19906
[ "19820" ]
65c5b49a59ecdd14e8b7cd98e27fe217466947d8
diff --git a/src/python/pants/backend/experimental/tools/yamllint/__init__.py b/src/python/pants/backend/experimental/tools/yamllint/__init__.py new file mode 100644
Missing `pants/backend/experimental/tools/yamllint/__init__.py` file ``` Can not check requirements for backend: 'pants.backend.experimental.tools.yamllint'. A __init__.py file is probably missing. ``` Tagging as internal as I don't believe it has a practical impact.
2023-09-22T01:49:59
pantsbuild/pants
19,907
pantsbuild__pants-19907
[ "19820" ]
8aaac91049990e180296057a3d887e45b2b99258
diff --git a/src/python/pants/backend/experimental/tools/yamllint/__init__.py b/src/python/pants/backend/experimental/tools/yamllint/__init__.py new file mode 100644
Missing `pants/backend/experimental/tools/yamllint/__init__.py` file ``` Can not check requirements for backend: 'pants.backend.experimental.tools.yamllint'. A __init__.py file is probably missing. ``` Tagging as internal as I don't believe it has a practical impact.
2023-09-22T01:50:00
pantsbuild/pants
19,908
pantsbuild__pants-19908
[ "19820" ]
df2f1aebba35a9d8a3a3a59d76b799c58a20159a
diff --git a/src/python/pants/backend/experimental/tools/yamllint/__init__.py b/src/python/pants/backend/experimental/tools/yamllint/__init__.py new file mode 100644
Missing `pants/backend/experimental/tools/yamllint/__init__.py` file ``` Can not check requirements for backend: 'pants.backend.experimental.tools.yamllint'. A __init__.py file is probably missing. ``` Tagging as internal as I don't believe it has a practical impact.
2023-09-22T01:50:03
pantsbuild/pants
19,920
pantsbuild__pants-19920
[ "16978" ]
2b91b8a5d6a43c6b62e577a4ca8c85ec0666a0fe
diff --git a/src/python/pants/engine/internals/graph.py b/src/python/pants/engine/internals/graph.py --- a/src/python/pants/engine/internals/graph.py +++ b/src/python/pants/engine/internals/graph.py @@ -366,8 +366,9 @@ def _target_parametrizations( target_type: type[Target], union_membership: UnionMembership, ) -> _TargetParametrization: - first, *rest = Parametrize.expand(address, target_adaptor.kwargs) - if rest: + expanded_parametrizations = tuple(Parametrize.expand(address, target_adaptor.kwargs)) + first_address, first_kwargs = expanded_parametrizations[0] + if first_address is not address: # The target was parametrized, and so the original Target does not exist. generated = FrozenDict( ( @@ -380,7 +381,7 @@ def _target_parametrizations( description_of_origin=target_adaptor.description_of_origin, ), ) - for parameterized_address, parameterized_fields in (first, *rest) + for parameterized_address, parameterized_fields in expanded_parametrizations ) return _TargetParametrization(None, generated) else:
diff --git a/src/python/pants/engine/internals/graph_test.py b/src/python/pants/engine/internals/graph_test.py --- a/src/python/pants/engine/internals/graph_test.py +++ b/src/python/pants/engine/internals/graph_test.py @@ -1464,6 +1464,25 @@ def test_parametrize_16910(generated_targets_rule_runner: RuleRunner, field_cont ) +def test_parametrize_single_value_16978(generated_targets_rule_runner: RuleRunner) -> None: + assert_generated( + generated_targets_rule_runner, + Address("demo"), + "generated(resolve=parametrize('demo'), source='f1.ext')", + ["f1.ext"], + { + MockGeneratedTarget( + {SingleSourceField.alias: "f1.ext", ResolveField.alias: "demo"}, + Address("demo", parameters={"resolve": "demo"}), + residence_dir="demo", + ), + }, + expected_dependencies={ + "demo@resolve=demo": set(), + }, + ) + + # ----------------------------------------------------------------------------------------------- # Test `SourcesField`. Also see `engine/target_test.py`. # -----------------------------------------------------------------------------------------------
Parametrize with only one arg broken **Describe the bug** You can not parametrize a regular (non-generator) target with a single value (i.e. it is not parametrized at all) **Pants version** `main` **Additional info** The parametrization correctly deduces that there is no parametrization going on, but fails to unwrap the parametrization object on the field value. The log lines added below are from: https://github.com/pantsbuild/pants/blob/f5de7c4e2538376bede255be27ef32afae56ccf0/src/python/pants/engine/internals/graph.py#L306-L309 as: ```python else: logger.info(f"ADAPTOR: {target_adaptor}, kwargs: {target_adaptor.kwargs}") first, *rest = Parametrize.expand(address, target_adaptor.kwargs) logger.info(f"first, rest: {first} : {rest}") if rest: # The target was parametrized, and so the original Target does not exist. ``` ``` 10:52:54.40 [INFO] ADAPTOR: TargetAdaptor(type_alias=python_requirement, name=pydevd-pycharm), kwargs: {'resolve': parametrize(python-default), 'requirements': ['pydevd-pycharm==203.5419.8']} 10:52:54.40 [INFO] first, rest: (Address(3rdparty/python:pydevd-pycharm@resolve=python-default), {'requirements': ['pydevd-pycharm==203.5419.8'], 'resolve': 'python-default'}) : [] 10:52:54.40 [ERROR] 1 Exception encountered: Engine traceback: in select in pants.backend.project_info.peek.peek (default_env) in pants.engine.internals.graph.resolve_unexpanded_targets (default_env) in pants.engine.internals.specs_rules.resolve_addresses_from_specs (default_env) in pants.engine.internals.specs_rules.resolve_addresses_from_raw_specs (default_env) in pants.engine.internals.specs_rules.addresses_from_raw_specs_without_file_owners (default_env) in pants.engine.internals.graph.resolve_target_parametrizations (3rdparty/python:pydevd-pycharm, default_env) Traceback (most recent call last): File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/engine/internals/selectors.py", line 593, in native_engine_generator_send res = func.send(arg) File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/engine/internals/graph.py", line 327, in resolve_target_parametrizations target = target_type( File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/util/meta.py", line 164, in new_init prev_init(self, *args, **kwargs) File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/engine/target.py", line 414, in __init__ self.field_values = self._calculate_field_values( File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/engine/target.py", line 449, in _calculate_field_values field_values[field_type] = field_type(value, address) File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/engine/target.py", line 239, in __init__ super().__init__(raw_value, address) File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/util/meta.py", line 164, in new_init prev_init(self, *args, **kwargs) File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/engine/target.py", line 139, in __init__ self.value: Optional[ImmutableValue] = self.compute_value(raw_value, address) File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/engine/target.py", line 1740, in compute_value value_or_default = super().compute_value(raw_value, address) File "/Users/andreas.stenius/src/github/kaos/pants/src/python/pants/engine/target.py", line 1639, in compute_value raise InvalidFieldTypeException( pants.engine.target.InvalidFieldTypeException: The 'resolve' field in target 3rdparty/python:pydevd-pycharm must be a string, but was `parametrize(python-default)` with type `Parametrize`. ```
2023-09-22T17:47:24
pantsbuild/pants
19,935
pantsbuild__pants-19935
[ "19932" ]
485b2bc7191057b92f7466d3aff544b7f8496588
diff --git a/src/python/pants/backend/visibility/glob.py b/src/python/pants/backend/visibility/glob.py --- a/src/python/pants/backend/visibility/glob.py +++ b/src/python/pants/backend/visibility/glob.py @@ -129,7 +129,7 @@ def parse(cls, pattern: str, base: str) -> PathGlob: def _match_path(self, path: str, base: str) -> str | None: if self.anchor_mode is PathGlobAnchorMode.INVOKED_PATH: - path = os.path.relpath(path, base + "/.." * self.uplvl) + path = os.path.relpath(path or ".", base + "/.." * self.uplvl) if path.startswith(".."): # The `path` is not in the sub tree of `base`. return None
diff --git a/src/python/pants/backend/visibility/glob_test.py b/src/python/pants/backend/visibility/glob_test.py --- a/src/python/pants/backend/visibility/glob_test.py +++ b/src/python/pants/backend/visibility/glob_test.py @@ -184,6 +184,8 @@ def test_pathglob_parse(base: str, pattern_text: str | tuple[str, str], expected ( # path, base, expected ("src/foo/bar", "src/qux", "foo/bar"), + ("", "snout", ""), + ("", "snout/deep", None), ), ), ],
Target visibility rules fail to handle dependency on a target in the root of the repo **Describe the bug** With this patch in the https://github.com/pantsbuild/example-python ```diff diff --git a/BUILD b/BUILD index fca77e4..f25009f 100644 --- a/BUILD +++ b/BUILD @@ -5,3 +5,5 @@ # `python_requirement_library` target. Refer to # https://www.pantsbuild.org/docs/python-third-party-dependencies. python_requirements(name="reqs") + +file(name="license-file", source="LICENSE") diff --git a/helloworld/greet/BUILD b/helloworld/greet/BUILD index 6dcc65e..3376617 100644 --- a/helloworld/greet/BUILD +++ b/helloworld/greet/BUILD @@ -13,6 +13,7 @@ python_sources( # This target sets the metadata for all the Python test files in this directory. python_tests( name="tests", + dependencies=["//:license-file"], ) # This target teaches Pants about our JSON file, which allows other targets to depend on it. @@ -20,3 +21,12 @@ resource( name="translations", source="translations.json", ) + +__dependencies_rules__( + ( + (python_tests, python_test), + "?../*/**", + ), + # Catch all, allow all. + ("*", "*"), +) diff --git a/pants.toml b/pants.toml index 59bdbc4..a357db2 100644 --- a/pants.toml +++ b/pants.toml @@ -11,6 +11,7 @@ backend_packages.add = [ "pants.backend.python.lint.flake8", "pants.backend.python.lint.isort", "pants.backend.python.typecheck.mypy", + "pants.backend.experimental.visibility", ] [anonymous-telemetry] ``` running ``` $ pants --print-stacktrace dependencies helloworld/greet/greeting_test.py ``` fails with ``` 20:51:19.46 [ERROR] 1 Exception encountered: Engine traceback: in select .. in pants.backend.project_info.dependencies.dependencies `dependencies` goal (truncated) path = os.path.relpath(path, base + "/.." * self.uplvl) File "/home/alexey.tereshenkov/.cache/nce/2b6e146234a4ef2a8946081fc3fbfffe0765b80b690425a49ebe40b47c33445b/cpython-3.9.16+20230507-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/posixpath.py", line 454, in relpath raise ValueError("no path specified") ValueError: no path specified ``` I have been able to pinpoint this to the usage of `"?../*/**"` in the visibility ruleset; the parser doesn't seem to handle the double dots `..`. Validating dependencies on targets anywhere else in the repo (except the root) or without using double dot in the pattern doesn't cause the error to be thrown. **Pants version** 2.16 / 2.17 / 2.18 **OS** Not OS specific **Additional info** If it's an implementation constraint, it would be helpful to know how to work around this.
2023-09-24T22:29:28
pantsbuild/pants
19,937
pantsbuild__pants-19937
[ "19932" ]
729275ebdc52ccf7b59d7ba89db079bd9c6674a8
diff --git a/src/python/pants/backend/visibility/glob.py b/src/python/pants/backend/visibility/glob.py --- a/src/python/pants/backend/visibility/glob.py +++ b/src/python/pants/backend/visibility/glob.py @@ -129,7 +129,7 @@ def parse(cls, pattern: str, base: str) -> PathGlob: def _match_path(self, path: str, base: str) -> str | None: if self.anchor_mode is PathGlobAnchorMode.INVOKED_PATH: - path = os.path.relpath(path, base + "/.." * self.uplvl) + path = os.path.relpath(path or ".", base + "/.." * self.uplvl) if path.startswith(".."): # The `path` is not in the sub tree of `base`. return None
diff --git a/src/python/pants/backend/visibility/glob_test.py b/src/python/pants/backend/visibility/glob_test.py --- a/src/python/pants/backend/visibility/glob_test.py +++ b/src/python/pants/backend/visibility/glob_test.py @@ -184,6 +184,8 @@ def test_pathglob_parse(base: str, pattern_text: str | tuple[str, str], expected ( # path, base, expected ("src/foo/bar", "src/qux", "foo/bar"), + ("", "snout", ""), + ("", "snout/deep", None), ), ), ],
Target visibility rules fail to handle dependency on a target in the root of the repo **Describe the bug** With this patch in the https://github.com/pantsbuild/example-python ```diff diff --git a/BUILD b/BUILD index fca77e4..f25009f 100644 --- a/BUILD +++ b/BUILD @@ -5,3 +5,5 @@ # `python_requirement_library` target. Refer to # https://www.pantsbuild.org/docs/python-third-party-dependencies. python_requirements(name="reqs") + +file(name="license-file", source="LICENSE") diff --git a/helloworld/greet/BUILD b/helloworld/greet/BUILD index 6dcc65e..3376617 100644 --- a/helloworld/greet/BUILD +++ b/helloworld/greet/BUILD @@ -13,6 +13,7 @@ python_sources( # This target sets the metadata for all the Python test files in this directory. python_tests( name="tests", + dependencies=["//:license-file"], ) # This target teaches Pants about our JSON file, which allows other targets to depend on it. @@ -20,3 +21,12 @@ resource( name="translations", source="translations.json", ) + +__dependencies_rules__( + ( + (python_tests, python_test), + "?../*/**", + ), + # Catch all, allow all. + ("*", "*"), +) diff --git a/pants.toml b/pants.toml index 59bdbc4..a357db2 100644 --- a/pants.toml +++ b/pants.toml @@ -11,6 +11,7 @@ backend_packages.add = [ "pants.backend.python.lint.flake8", "pants.backend.python.lint.isort", "pants.backend.python.typecheck.mypy", + "pants.backend.experimental.visibility", ] [anonymous-telemetry] ``` running ``` $ pants --print-stacktrace dependencies helloworld/greet/greeting_test.py ``` fails with ``` 20:51:19.46 [ERROR] 1 Exception encountered: Engine traceback: in select .. in pants.backend.project_info.dependencies.dependencies `dependencies` goal (truncated) path = os.path.relpath(path, base + "/.." * self.uplvl) File "/home/alexey.tereshenkov/.cache/nce/2b6e146234a4ef2a8946081fc3fbfffe0765b80b690425a49ebe40b47c33445b/cpython-3.9.16+20230507-x86_64-unknown-linux-gnu-install_only.tar.gz/python/lib/python3.9/posixpath.py", line 454, in relpath raise ValueError("no path specified") ValueError: no path specified ``` I have been able to pinpoint this to the usage of `"?../*/**"` in the visibility ruleset; the parser doesn't seem to handle the double dots `..`. Validating dependencies on targets anywhere else in the repo (except the root) or without using double dot in the pattern doesn't cause the error to be thrown. **Pants version** 2.16 / 2.17 / 2.18 **OS** Not OS specific **Additional info** If it's an implementation constraint, it would be helpful to know how to work around this.
2023-09-25T15:07:06
pantsbuild/pants
19,945
pantsbuild__pants-19945
[ "18589" ]
9382fe26666915be5b9a7cc9d04f222e3a1be2ec
diff --git a/src/python/pants/backend/shell/lint/shellcheck/subsystem.py b/src/python/pants/backend/shell/lint/shellcheck/subsystem.py --- a/src/python/pants/backend/shell/lint/shellcheck/subsystem.py +++ b/src/python/pants/backend/shell/lint/shellcheck/subsystem.py @@ -20,18 +20,21 @@ class Shellcheck(TemplatedExternalTool): default_version = "v0.8.0" default_known_versions = [ - "v0.8.0|macos_arm64 |e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", - "v0.8.0|macos_x86_64|e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", - "v0.8.0|linux_arm64 |9f47bbff5624babfa712eb9d64ece14c6c46327122d0c54983f627ae3a30a4ac|2996468", - "v0.8.0|linux_x86_64|ab6ee1b178f014d1b86d1e24da20d1139656c8b0ed34d2867fbb834dad02bf0a|1403852", + "v0.8.0|macos_arm64 |36dffd536b801c8bab2e9fa468163037e0c7f7e0a05298e5ad6299b4dde67e31|14525367", + "v0.8.0|macos_x86_64|4e93a76ee116b2f08c88e25011830280ad0d61615d8346364a4ea564b29be3f0|6310442", + "v0.8.0|linux_arm64 |8f4810485425636eadce2ec23441fd29d5b1b58d239ffda0a5faf8dd499026f5|4884430", + "v0.8.0|linux_x86_64|01d181787ffe63ebb0a2293f63bdc8455c5c30d3a6636320664bfa278424638f|2082242", ] + # We use this third party source since it has pre-compiled binaries for both x86 and aarch. + # It is recommended by shellcheck + # https://github.com/koalaman/shellcheck/blob/90d3172dfec30a7569f95b32479ae97af73b8b2e/README.md?plain=1#L236-L237 default_url_template = ( - "https://github.com/koalaman/shellcheck/releases/download/{version}/shellcheck-" - "{version}.{platform}.tar.xz" + "https://github.com/vscode-shellcheck/shellcheck-binaries/releases/download/{version}/shellcheck-" + "{version}.{platform}.tar.gz" ) default_url_platform_mapping = { - "macos_arm64": "darwin.x86_64", + "macos_arm64": "darwin.aarch64", "macos_x86_64": "darwin.x86_64", "linux_arm64": "linux.aarch64", "linux_x86_64": "linux.x86_64", @@ -52,7 +55,7 @@ class Shellcheck(TemplatedExternalTool): ) def generate_exe(self, _: Platform) -> str: - return f"./shellcheck-{self.version}/shellcheck" + return "./shellcheck" def config_request(self, dirs: Iterable[str]) -> ConfigFilesRequest: # Refer to https://www.mankier.com/1/shellcheck#RC_Files for how config files are
Shellcheck fails on M2 (without Rosetta installed) After running `pants peek ::` in the Pants main repo, I get the following error: ```bash Error launching process: Os { code: 86, kind: Uncategorized, message: "Bad CPU type in executable" } ``` From the ShellCheck subsystem, I see that the Mac ARM version points to the x86 binaries (there are no Mac ARM binaries in the GH releases): ```python class Shellcheck(TemplatedExternalTool): options_scope = "shellcheck" name = "Shellcheck" help = "A linter for shell scripts." default_version = "v0.8.0" default_known_versions = [ "v0.8.0|macos_arm64 |e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", "v0.8.0|macos_x86_64|e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", "v0.8.0|linux_arm64 |9f47bbff5624babfa712eb9d64ece14c6c46327122d0c54983f627ae3a30a4ac|2996468", "v0.8.0|linux_x86_64|ab6ee1b178f014d1b86d1e24da20d1139656c8b0ed34d2867fbb834dad02bf0a|1403852", ] default_url_template = ( "https://github.com/koalaman/shellcheck/releases/download/{version}/shellcheck-" "{version}.{platform}.tar.xz" ) default_url_platform_mapping = { "macos_arm64": "darwin.x86_64", "macos_x86_64": "darwin.x86_64", "linux_arm64": "linux.aarch64", "linux_x86_64": "linux.x86_64", } ``` ## Mitigation I think that installing Rosetta might fix this... ## Context - https://github.com/pantsbuild/pants/issues/14416 - https://github.com/koalaman/shellcheck/issues/2680 - https://github.com/koalaman/shellcheck/issues/2714 ## Detailed Error ```bash native_engine.IntrinsicError: Failed to execute: Process { argv: [ "./shellcheck-v0.8.0/shellcheck", "--format=json", "cargo", ], env: {}, working_directory: None, input_digests: InputDigests { complete: DirectoryDigest { digest: Digest { hash: Fingerprint<74712eda6b804fa6f81dea6d4b7008be9e369f40d2c7c2fce92bb59ca25a9ba3>, size_bytes: 174, }, tree: "Some(..)", }, nailgun: DirectoryDigest { digest: Digest { hash: Fingerprint<e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855>, size_bytes: 0, }, tree: "Some(..)", }, inputs: DirectoryDigest { digest: Digest { hash: Fingerprint<74712eda6b804fa6f81dea6d4b7008be9e369f40d2c7c2fce92bb59ca25a9ba3>, size_bytes: 174, }, tree: "Some(..)", }, immutable_inputs: {}, use_nailgun: {}, }, output_files: {}, output_directories: {}, timeout: None, execution_slot_variable: None, concurrency_available: 0, description: "Detect Shell imports for cargo", level: Debug, append_only_caches: {}, jdk_home: None, cache_scope: Always, execution_environment: ProcessExecutionEnvironment { name: None, platform: Macos_arm64, strategy: Local, }, remote_cache_speculation_delay: 0ns, } Error launching process: Os { code: 86, kind: Uncategorized, message: "Bad CPU type in executable" } ```
I still think one big question is why this was run in the first place... I was `peek`ing, so not sure why a lint rule suddenly ran. Ok, I see it is because we use ShellCheck for dependency inference. That is why the failure to run shellcheck is getting in the way even when we are not linting. https://github.com/pantsbuild/pants/blob/9382fe26666915be5b9a7cc9d04f222e3a1be2ec/src/python/pants/backend/shell/dependency_inference.py#L96-L111 Shellcheck is available from VSCode: https://github.com/vscode-shellcheck/shellcheck-binaries/releases and this is the recommendation of shellcheck itself: https://github.com/koalaman/shellcheck/blob/90d3172dfec30a7569f95b32479ae97af73b8b2e/README.md?plain=1#L236-L237 > There are currently no official binaries for Apple Silicon, but third party builds are available via [ShellCheck for Visual Studio Code](https://github.com/vscode-shellcheck/shellcheck-binaries/releases). I'll make a PR to add references to this source of binaries.
2023-09-27T16:32:54
pantsbuild/pants
19,951
pantsbuild__pants-19951
[ "18589" ]
054919d0a7fc9bf895c6d81a52cb26823b91bf1c
diff --git a/src/python/pants/backend/shell/lint/shellcheck/subsystem.py b/src/python/pants/backend/shell/lint/shellcheck/subsystem.py --- a/src/python/pants/backend/shell/lint/shellcheck/subsystem.py +++ b/src/python/pants/backend/shell/lint/shellcheck/subsystem.py @@ -20,18 +20,21 @@ class Shellcheck(TemplatedExternalTool): default_version = "v0.8.0" default_known_versions = [ - "v0.8.0|macos_arm64 |e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", - "v0.8.0|macos_x86_64|e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", - "v0.8.0|linux_arm64 |9f47bbff5624babfa712eb9d64ece14c6c46327122d0c54983f627ae3a30a4ac|2996468", - "v0.8.0|linux_x86_64|ab6ee1b178f014d1b86d1e24da20d1139656c8b0ed34d2867fbb834dad02bf0a|1403852", + "v0.8.0|macos_arm64 |36dffd536b801c8bab2e9fa468163037e0c7f7e0a05298e5ad6299b4dde67e31|14525367", + "v0.8.0|macos_x86_64|4e93a76ee116b2f08c88e25011830280ad0d61615d8346364a4ea564b29be3f0|6310442", + "v0.8.0|linux_arm64 |8f4810485425636eadce2ec23441fd29d5b1b58d239ffda0a5faf8dd499026f5|4884430", + "v0.8.0|linux_x86_64|01d181787ffe63ebb0a2293f63bdc8455c5c30d3a6636320664bfa278424638f|2082242", ] + # We use this third party source since it has pre-compiled binaries for both x86 and aarch. + # It is recommended by shellcheck + # https://github.com/koalaman/shellcheck/blob/90d3172dfec30a7569f95b32479ae97af73b8b2e/README.md?plain=1#L236-L237 default_url_template = ( - "https://github.com/koalaman/shellcheck/releases/download/{version}/shellcheck-" - "{version}.{platform}.tar.xz" + "https://github.com/vscode-shellcheck/shellcheck-binaries/releases/download/{version}/shellcheck-" + "{version}.{platform}.tar.gz" ) default_url_platform_mapping = { - "macos_arm64": "darwin.x86_64", + "macos_arm64": "darwin.aarch64", "macos_x86_64": "darwin.x86_64", "linux_arm64": "linux.aarch64", "linux_x86_64": "linux.x86_64", @@ -52,7 +55,7 @@ class Shellcheck(TemplatedExternalTool): ) def generate_exe(self, _: Platform) -> str: - return f"./shellcheck-{self.version}/shellcheck" + return "./shellcheck" def config_request(self, dirs: Iterable[str]) -> ConfigFilesRequest: # Refer to https://www.mankier.com/1/shellcheck#RC_Files for how config files are
Shellcheck fails on M2 (without Rosetta installed) After running `pants peek ::` in the Pants main repo, I get the following error: ```bash Error launching process: Os { code: 86, kind: Uncategorized, message: "Bad CPU type in executable" } ``` From the ShellCheck subsystem, I see that the Mac ARM version points to the x86 binaries (there are no Mac ARM binaries in the GH releases): ```python class Shellcheck(TemplatedExternalTool): options_scope = "shellcheck" name = "Shellcheck" help = "A linter for shell scripts." default_version = "v0.8.0" default_known_versions = [ "v0.8.0|macos_arm64 |e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", "v0.8.0|macos_x86_64|e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", "v0.8.0|linux_arm64 |9f47bbff5624babfa712eb9d64ece14c6c46327122d0c54983f627ae3a30a4ac|2996468", "v0.8.0|linux_x86_64|ab6ee1b178f014d1b86d1e24da20d1139656c8b0ed34d2867fbb834dad02bf0a|1403852", ] default_url_template = ( "https://github.com/koalaman/shellcheck/releases/download/{version}/shellcheck-" "{version}.{platform}.tar.xz" ) default_url_platform_mapping = { "macos_arm64": "darwin.x86_64", "macos_x86_64": "darwin.x86_64", "linux_arm64": "linux.aarch64", "linux_x86_64": "linux.x86_64", } ``` ## Mitigation I think that installing Rosetta might fix this... ## Context - https://github.com/pantsbuild/pants/issues/14416 - https://github.com/koalaman/shellcheck/issues/2680 - https://github.com/koalaman/shellcheck/issues/2714 ## Detailed Error ```bash native_engine.IntrinsicError: Failed to execute: Process { argv: [ "./shellcheck-v0.8.0/shellcheck", "--format=json", "cargo", ], env: {}, working_directory: None, input_digests: InputDigests { complete: DirectoryDigest { digest: Digest { hash: Fingerprint<74712eda6b804fa6f81dea6d4b7008be9e369f40d2c7c2fce92bb59ca25a9ba3>, size_bytes: 174, }, tree: "Some(..)", }, nailgun: DirectoryDigest { digest: Digest { hash: Fingerprint<e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855>, size_bytes: 0, }, tree: "Some(..)", }, inputs: DirectoryDigest { digest: Digest { hash: Fingerprint<74712eda6b804fa6f81dea6d4b7008be9e369f40d2c7c2fce92bb59ca25a9ba3>, size_bytes: 174, }, tree: "Some(..)", }, immutable_inputs: {}, use_nailgun: {}, }, output_files: {}, output_directories: {}, timeout: None, execution_slot_variable: None, concurrency_available: 0, description: "Detect Shell imports for cargo", level: Debug, append_only_caches: {}, jdk_home: None, cache_scope: Always, execution_environment: ProcessExecutionEnvironment { name: None, platform: Macos_arm64, strategy: Local, }, remote_cache_speculation_delay: 0ns, } Error launching process: Os { code: 86, kind: Uncategorized, message: "Bad CPU type in executable" } ```
I still think one big question is why this was run in the first place... I was `peek`ing, so not sure why a lint rule suddenly ran. Ok, I see it is because we use ShellCheck for dependency inference. That is why the failure to run shellcheck is getting in the way even when we are not linting. https://github.com/pantsbuild/pants/blob/9382fe26666915be5b9a7cc9d04f222e3a1be2ec/src/python/pants/backend/shell/dependency_inference.py#L96-L111 Shellcheck is available from VSCode: https://github.com/vscode-shellcheck/shellcheck-binaries/releases and this is the recommendation of shellcheck itself: https://github.com/koalaman/shellcheck/blob/90d3172dfec30a7569f95b32479ae97af73b8b2e/README.md?plain=1#L236-L237 > There are currently no official binaries for Apple Silicon, but third party builds are available via [ShellCheck for Visual Studio Code](https://github.com/vscode-shellcheck/shellcheck-binaries/releases). I'll make a PR to add references to this source of binaries.
2023-09-28T23:42:04
pantsbuild/pants
19,952
pantsbuild__pants-19952
[ "18589" ]
61f74059cafca9140683268bd66c5a097b4210bd
diff --git a/src/python/pants/backend/shell/lint/shellcheck/subsystem.py b/src/python/pants/backend/shell/lint/shellcheck/subsystem.py --- a/src/python/pants/backend/shell/lint/shellcheck/subsystem.py +++ b/src/python/pants/backend/shell/lint/shellcheck/subsystem.py @@ -20,18 +20,21 @@ class Shellcheck(TemplatedExternalTool): default_version = "v0.8.0" default_known_versions = [ - "v0.8.0|macos_arm64 |e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", - "v0.8.0|macos_x86_64|e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", - "v0.8.0|linux_arm64 |9f47bbff5624babfa712eb9d64ece14c6c46327122d0c54983f627ae3a30a4ac|2996468", - "v0.8.0|linux_x86_64|ab6ee1b178f014d1b86d1e24da20d1139656c8b0ed34d2867fbb834dad02bf0a|1403852", + "v0.8.0|macos_arm64 |36dffd536b801c8bab2e9fa468163037e0c7f7e0a05298e5ad6299b4dde67e31|14525367", + "v0.8.0|macos_x86_64|4e93a76ee116b2f08c88e25011830280ad0d61615d8346364a4ea564b29be3f0|6310442", + "v0.8.0|linux_arm64 |8f4810485425636eadce2ec23441fd29d5b1b58d239ffda0a5faf8dd499026f5|4884430", + "v0.8.0|linux_x86_64|01d181787ffe63ebb0a2293f63bdc8455c5c30d3a6636320664bfa278424638f|2082242", ] + # We use this third party source since it has pre-compiled binaries for both x86 and aarch. + # It is recommended by shellcheck + # https://github.com/koalaman/shellcheck/blob/90d3172dfec30a7569f95b32479ae97af73b8b2e/README.md?plain=1#L236-L237 default_url_template = ( - "https://github.com/koalaman/shellcheck/releases/download/{version}/shellcheck-" - "{version}.{platform}.tar.xz" + "https://github.com/vscode-shellcheck/shellcheck-binaries/releases/download/{version}/shellcheck-" + "{version}.{platform}.tar.gz" ) default_url_platform_mapping = { - "macos_arm64": "darwin.x86_64", + "macos_arm64": "darwin.aarch64", "macos_x86_64": "darwin.x86_64", "linux_arm64": "linux.aarch64", "linux_x86_64": "linux.x86_64", @@ -52,7 +55,7 @@ class Shellcheck(TemplatedExternalTool): ) def generate_exe(self, _: Platform) -> str: - return f"./shellcheck-{self.version}/shellcheck" + return "./shellcheck" def config_request(self, dirs: Iterable[str]) -> ConfigFilesRequest: # Refer to https://www.mankier.com/1/shellcheck#RC_Files for how config files are
Shellcheck fails on M2 (without Rosetta installed) After running `pants peek ::` in the Pants main repo, I get the following error: ```bash Error launching process: Os { code: 86, kind: Uncategorized, message: "Bad CPU type in executable" } ``` From the ShellCheck subsystem, I see that the Mac ARM version points to the x86 binaries (there are no Mac ARM binaries in the GH releases): ```python class Shellcheck(TemplatedExternalTool): options_scope = "shellcheck" name = "Shellcheck" help = "A linter for shell scripts." default_version = "v0.8.0" default_known_versions = [ "v0.8.0|macos_arm64 |e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", "v0.8.0|macos_x86_64|e065d4afb2620cc8c1d420a9b3e6243c84ff1a693c1ff0e38f279c8f31e86634|4049756", "v0.8.0|linux_arm64 |9f47bbff5624babfa712eb9d64ece14c6c46327122d0c54983f627ae3a30a4ac|2996468", "v0.8.0|linux_x86_64|ab6ee1b178f014d1b86d1e24da20d1139656c8b0ed34d2867fbb834dad02bf0a|1403852", ] default_url_template = ( "https://github.com/koalaman/shellcheck/releases/download/{version}/shellcheck-" "{version}.{platform}.tar.xz" ) default_url_platform_mapping = { "macos_arm64": "darwin.x86_64", "macos_x86_64": "darwin.x86_64", "linux_arm64": "linux.aarch64", "linux_x86_64": "linux.x86_64", } ``` ## Mitigation I think that installing Rosetta might fix this... ## Context - https://github.com/pantsbuild/pants/issues/14416 - https://github.com/koalaman/shellcheck/issues/2680 - https://github.com/koalaman/shellcheck/issues/2714 ## Detailed Error ```bash native_engine.IntrinsicError: Failed to execute: Process { argv: [ "./shellcheck-v0.8.0/shellcheck", "--format=json", "cargo", ], env: {}, working_directory: None, input_digests: InputDigests { complete: DirectoryDigest { digest: Digest { hash: Fingerprint<74712eda6b804fa6f81dea6d4b7008be9e369f40d2c7c2fce92bb59ca25a9ba3>, size_bytes: 174, }, tree: "Some(..)", }, nailgun: DirectoryDigest { digest: Digest { hash: Fingerprint<e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855>, size_bytes: 0, }, tree: "Some(..)", }, inputs: DirectoryDigest { digest: Digest { hash: Fingerprint<74712eda6b804fa6f81dea6d4b7008be9e369f40d2c7c2fce92bb59ca25a9ba3>, size_bytes: 174, }, tree: "Some(..)", }, immutable_inputs: {}, use_nailgun: {}, }, output_files: {}, output_directories: {}, timeout: None, execution_slot_variable: None, concurrency_available: 0, description: "Detect Shell imports for cargo", level: Debug, append_only_caches: {}, jdk_home: None, cache_scope: Always, execution_environment: ProcessExecutionEnvironment { name: None, platform: Macos_arm64, strategy: Local, }, remote_cache_speculation_delay: 0ns, } Error launching process: Os { code: 86, kind: Uncategorized, message: "Bad CPU type in executable" } ```
I still think one big question is why this was run in the first place... I was `peek`ing, so not sure why a lint rule suddenly ran. Ok, I see it is because we use ShellCheck for dependency inference. That is why the failure to run shellcheck is getting in the way even when we are not linting. https://github.com/pantsbuild/pants/blob/9382fe26666915be5b9a7cc9d04f222e3a1be2ec/src/python/pants/backend/shell/dependency_inference.py#L96-L111 Shellcheck is available from VSCode: https://github.com/vscode-shellcheck/shellcheck-binaries/releases and this is the recommendation of shellcheck itself: https://github.com/koalaman/shellcheck/blob/90d3172dfec30a7569f95b32479ae97af73b8b2e/README.md?plain=1#L236-L237 > There are currently no official binaries for Apple Silicon, but third party builds are available via [ShellCheck for Visual Studio Code](https://github.com/vscode-shellcheck/shellcheck-binaries/releases). I'll make a PR to add references to this source of binaries.
2023-09-28T23:42:06
pantsbuild/pants
19,968
pantsbuild__pants-19968
[ "19158" ]
fc99fb947013f68f2fa91501f9a4eaa9da904d93
diff --git a/src/python/pants/engine/internals/defaults.py b/src/python/pants/engine/internals/defaults.py --- a/src/python/pants/engine/internals/defaults.py +++ b/src/python/pants/engine/internals/defaults.py @@ -114,7 +114,7 @@ def set_defaults( all: SetDefaultsValueT | None = None, extend: bool = False, ignore_unknown_fields: bool = False, - **kwargs, + ignore_unknown_targets: bool = False, ) -> None: defaults: dict[str, dict[str, Any]] = ( {} if not extend else {k: dict(v) for k, v in self.defaults.items()} @@ -125,10 +125,16 @@ def set_defaults( defaults, {tuple(self.registered_target_types.aliases): all}, ignore_unknown_fields=True, + ignore_unknown_targets=ignore_unknown_targets, ) for arg in args: - self._process_defaults(defaults, arg, ignore_unknown_fields=ignore_unknown_fields) + self._process_defaults( + defaults, + arg, + ignore_unknown_fields=ignore_unknown_fields, + ignore_unknown_targets=ignore_unknown_targets, + ) # Update with new defaults, dropping targets without any default values. for tgt, default in defaults.items(): @@ -148,6 +154,7 @@ def _process_defaults( defaults: dict[str, dict[str, Any]], targets_defaults: SetDefaultsT, ignore_unknown_fields: bool = False, + ignore_unknown_targets: bool = False, ): if not isinstance(targets_defaults, dict): raise ValueError( @@ -168,6 +175,8 @@ def _process_defaults( for target_alias in map(str, targets): if target_alias in types: target_type = types[target_alias] + elif ignore_unknown_targets: + continue else: raise ValueError(f"Unrecognized target type {target_alias} in {self.address}.") diff --git a/src/python/pants/engine/internals/parser.py b/src/python/pants/engine/internals/parser.py --- a/src/python/pants/engine/internals/parser.py +++ b/src/python/pants/engine/internals/parser.py @@ -198,10 +198,17 @@ def get_env(self, name: str, *args, **kwargs) -> Any: """ ) def set_defaults( - self, *args: SetDefaultsT, ignore_unknown_fields: bool = False, **kwargs + self, + *args: SetDefaultsT, + ignore_unknown_fields: bool = False, + ignore_unknown_targets: bool = False, + **kwargs, ) -> None: self.defaults.set_defaults( - *args, ignore_unknown_fields=self.is_bootstrap or ignore_unknown_fields, **kwargs + *args, + ignore_unknown_fields=self.is_bootstrap or ignore_unknown_fields, + ignore_unknown_targets=self.is_bootstrap or ignore_unknown_targets, + **kwargs, ) def set_dependents_rules(self, *args, **kwargs) -> None:
diff --git a/src/python/pants/engine/internals/parser_test.py b/src/python/pants/engine/internals/parser_test.py --- a/src/python/pants/engine/internals/parser_test.py +++ b/src/python/pants/engine/internals/parser_test.py @@ -122,6 +122,28 @@ def perform_test(extra_targets: list[str], dym: str) -> None: perform_test(test_targs, dym_many) +def test_unknown_target_for_defaults_during_bootstrap_issue_19445( + defaults_parser_state: BuildFileDefaultsParserState, +) -> None: + parser = Parser( + build_root="", + registered_target_types=RegisteredTargetTypes({}), + union_membership=UnionMembership({}), + object_aliases=BuildFileAliases(), + ignore_unrecognized_symbols=True, + ) + parser.parse( + "BUILD", + "__defaults__({'type_1': dict(), type_2: dict()})", + BuildFilePreludeSymbols.create({}, ()), + EnvironmentVars({}), + True, + defaults_parser_state, + dependents_rules=None, + dependencies_rules=None, + ) + + @pytest.mark.parametrize("symbol", ["a", "bad", "BAD", "a___b_c", "a231", "áç"]) def test_extract_symbol_from_name_error(symbol: str) -> None: assert _extract_symbol_from_name_error(NameError(f"name '{symbol}' is not defined")) == symbol
`__defaults__` silently allows-and-ignores fallthrough kwargs **Describe the bug** I was trying to do: ```python __defaults__(python_test=dict(environment="focal-docker")) ``` and getting frustrated it wasn't working. Turns out it just gets collected and ignored: https://github.com/pantsbuild/pants/blob/3ce90948d2dc49dd525ca4a10daeaba98068a8e0/src/python/pants/engine/internals/defaults.py#L117 **Pants version** `2.16.0rc2` **OS** N/A **Additional info** N/A
2023-10-04T10:01:26
pantsbuild/pants
19,969
pantsbuild__pants-19969
[ "19158" ]
ddeaa627d1600b4f1813beb5f38d209dcafb112d
diff --git a/src/python/pants/engine/internals/defaults.py b/src/python/pants/engine/internals/defaults.py --- a/src/python/pants/engine/internals/defaults.py +++ b/src/python/pants/engine/internals/defaults.py @@ -114,7 +114,7 @@ def set_defaults( all: SetDefaultsValueT | None = None, extend: bool = False, ignore_unknown_fields: bool = False, - **kwargs, + ignore_unknown_targets: bool = False, ) -> None: defaults: dict[str, dict[str, Any]] = ( {} if not extend else {k: dict(v) for k, v in self.defaults.items()} @@ -125,10 +125,16 @@ def set_defaults( defaults, {tuple(self.registered_target_types.aliases): all}, ignore_unknown_fields=True, + ignore_unknown_targets=ignore_unknown_targets, ) for arg in args: - self._process_defaults(defaults, arg, ignore_unknown_fields=ignore_unknown_fields) + self._process_defaults( + defaults, + arg, + ignore_unknown_fields=ignore_unknown_fields, + ignore_unknown_targets=ignore_unknown_targets, + ) # Update with new defaults, dropping targets without any default values. for tgt, default in defaults.items(): @@ -148,6 +154,7 @@ def _process_defaults( defaults: dict[str, dict[str, Any]], targets_defaults: SetDefaultsT, ignore_unknown_fields: bool = False, + ignore_unknown_targets: bool = False, ): if not isinstance(targets_defaults, dict): raise ValueError( @@ -168,6 +175,8 @@ def _process_defaults( for target_alias in map(str, targets): if target_alias in types: target_type = types[target_alias] + elif ignore_unknown_targets: + continue else: raise ValueError(f"Unrecognized target type {target_alias} in {self.address}.") diff --git a/src/python/pants/engine/internals/parser.py b/src/python/pants/engine/internals/parser.py --- a/src/python/pants/engine/internals/parser.py +++ b/src/python/pants/engine/internals/parser.py @@ -198,10 +198,17 @@ def get_env(self, name: str, *args, **kwargs) -> Any: """ ) def set_defaults( - self, *args: SetDefaultsT, ignore_unknown_fields: bool = False, **kwargs + self, + *args: SetDefaultsT, + ignore_unknown_fields: bool = False, + ignore_unknown_targets: bool = False, + **kwargs, ) -> None: self.defaults.set_defaults( - *args, ignore_unknown_fields=self.is_bootstrap or ignore_unknown_fields, **kwargs + *args, + ignore_unknown_fields=self.is_bootstrap or ignore_unknown_fields, + ignore_unknown_targets=self.is_bootstrap or ignore_unknown_targets, + **kwargs, ) def set_dependents_rules(self, *args, **kwargs) -> None:
diff --git a/src/python/pants/engine/internals/parser_test.py b/src/python/pants/engine/internals/parser_test.py --- a/src/python/pants/engine/internals/parser_test.py +++ b/src/python/pants/engine/internals/parser_test.py @@ -122,6 +122,28 @@ def perform_test(extra_targets: list[str], dym: str) -> None: perform_test(test_targs, dym_many) +def test_unknown_target_for_defaults_during_bootstrap_issue_19445( + defaults_parser_state: BuildFileDefaultsParserState, +) -> None: + parser = Parser( + build_root="", + registered_target_types=RegisteredTargetTypes({}), + union_membership=UnionMembership({}), + object_aliases=BuildFileAliases(), + ignore_unrecognized_symbols=True, + ) + parser.parse( + "BUILD", + "__defaults__({'type_1': dict(), type_2: dict()})", + BuildFilePreludeSymbols.create({}, ()), + EnvironmentVars({}), + True, + defaults_parser_state, + dependents_rules=None, + dependencies_rules=None, + ) + + @pytest.mark.parametrize("symbol", ["a", "bad", "BAD", "a___b_c", "a231", "áç"]) def test_extract_symbol_from_name_error(symbol: str) -> None: assert _extract_symbol_from_name_error(NameError(f"name '{symbol}' is not defined")) == symbol
`__defaults__` silently allows-and-ignores fallthrough kwargs **Describe the bug** I was trying to do: ```python __defaults__(python_test=dict(environment="focal-docker")) ``` and getting frustrated it wasn't working. Turns out it just gets collected and ignored: https://github.com/pantsbuild/pants/blob/3ce90948d2dc49dd525ca4a10daeaba98068a8e0/src/python/pants/engine/internals/defaults.py#L117 **Pants version** `2.16.0rc2` **OS** N/A **Additional info** N/A
2023-10-04T10:02:23
pantsbuild/pants
19,980
pantsbuild__pants-19980
[ "19979" ]
9bc10447592724a137232105bbe6ddfa64a5d371
diff --git a/src/python/pants/backend/docker/goals/package_image.py b/src/python/pants/backend/docker/goals/package_image.py --- a/src/python/pants/backend/docker/goals/package_image.py +++ b/src/python/pants/backend/docker/goals/package_image.py @@ -45,10 +45,10 @@ from pants.engine.fs import CreateDigest, Digest, FileContent from pants.engine.process import FallibleProcessResult, Process, ProcessExecutionFailure from pants.engine.rules import Get, MultiGet, collect_rules, rule -from pants.engine.target import Target, WrappedTarget, WrappedTargetRequest +from pants.engine.target import InvalidFieldException, Target, WrappedTarget, WrappedTargetRequest from pants.engine.unions import UnionMembership, UnionRule from pants.option.global_options import GlobalOptions, KeepSandboxes -from pants.util.strutil import bullet_list +from pants.util.strutil import bullet_list, softwrap from pants.util.value_interpolation import InterpolationContext, InterpolationError logger = logging.getLogger(__name__) @@ -414,6 +414,16 @@ async def build_docker_image( ) ) tags = tuple(tag.full_name for registry in image_refs for tag in registry.tags) + if not tags: + raise InvalidFieldException( + softwrap( + f""" + The `{DockerImageTagsField.alias}` field in target {field_set.address} must not be + empty, unless there is a custom plugin providing additional tags using the + `DockerImageTagsRequest` union type. + """ + ) + ) # Mix the upstream image ids into the env to ensure that Pants invalidates this # image-building process correctly when an upstream image changes, even though the
diff --git a/src/python/pants/backend/docker/goals/package_image_test.py b/src/python/pants/backend/docker/goals/package_image_test.py --- a/src/python/pants/backend/docker/goals/package_image_test.py +++ b/src/python/pants/backend/docker/goals/package_image_test.py @@ -1846,18 +1846,40 @@ def test_image_ref_formatting(test: ImageRefTest) -> None: assert tuple(image_refs) == test.expect_refs -def test_docker_image_tags_from_plugin_hook(rule_runner: RuleRunner) -> None: - rule_runner.write_files({"docker/test/BUILD": 'docker_image(name="plugin")'}) [email protected]( + "BUILD, plugin_tags, tag_flags", + [ + ( + 'docker_image(name="plugin")', + ("1.2.3",), + ( + "--tag", + "plugin:latest", + "--tag", + "plugin:1.2.3", + ), + ), + ( + 'docker_image(name="plugin", image_tags=[])', + ("1.2.3",), + ( + "--tag", + "plugin:1.2.3", + ), + ), + ], +) +def test_docker_image_tags_from_plugin_hook( + rule_runner: RuleRunner, BUILD: str, plugin_tags: tuple[str, ...], tag_flags: tuple[str, ...] +) -> None: + rule_runner.write_files({"docker/test/BUILD": BUILD}) def check_docker_proc(process: Process): assert process.argv == ( "/dummy/docker", "build", "--pull=False", - "--tag", - "plugin:latest", - "--tag", - "plugin:1.2.3", + *tag_flags, "--file", "docker/test/Dockerfile", ".", @@ -1867,10 +1889,21 @@ def check_docker_proc(process: Process): rule_runner, Address("docker/test", target_name="plugin"), process_assertions=check_docker_proc, - plugin_tags=("1.2.3",), + plugin_tags=plugin_tags, ) +def test_docker_image_tags_defined(rule_runner: RuleRunner) -> None: + rule_runner.write_files({"docker/test/BUILD": 'docker_image(name="no-tags", image_tags=[])'}) + + err = "The `image_tags` field in target docker/test:no-tags must not be empty, unless" + with pytest.raises(InvalidFieldException, match=err): + assert_build( + rule_runner, + Address("docker/test", target_name="no-tags"), + ) + + def test_docker_info_serialize() -> None: image_id = "abc123" # image refs with unique strings (i.e. not actual templates/names etc.), to make sure they're
mysteriously terse engine error message when docker image_tags=[] **Describe the bug** Starting with https://github.com/pantsbuild/example-docker ``` $ git diff | cat diff --git a/src/docker/hello_world/BUILD b/src/docker/hello_world/BUILD index 4b6c1c4..83e04a9 100644 --- a/src/docker/hello_world/BUILD +++ b/src/docker/hello_world/BUILD @@ -4,6 +4,7 @@ docker_image( name="python", source="Dockerfile.python", + image_tags = [] ) docker_image( $ pants package src/docker/hello_world:python 15:32:12.80 [ERROR] 1 Exception encountered: Engine traceback: in `package` goal IndexError: tuple index out of range $ ls -lsthra .pants.d/ total 16K 512 -rw-r----- 1 ecsb ecsb 0 Oct 4 15:30 exceptions.log 512 -rw-r----- 1 ecsb ecsb 0 Oct 4 15:30 exceptions.4637.log 1.5K drwxr-x--- 3 ecsb ecsb 6 Oct 4 15:30 . 1.5K drwxr-x--- 8 ecsb ecsb 15 Oct 4 15:30 .. 11K drwxr-x--- 6 ecsb ecsb 6 Oct 4 15:32 run-tracker 1.5K -rw-r----- 1 ecsb ecsb 2.7K Oct 4 15:32 pants.log $ pants package -ltrace src/docker/hello_world:python 15:32:41.40 [INFO] Initialization options changed: reinitializing scheduler... 15:32:47.64 [INFO] Scheduler initialized. 15:32:49.55 [ERROR] 1 Exception encountered: Engine traceback: in `package` goal IndexError: tuple index out of range ``` Note that the exception log files are empty and logging doesn't give any additional clues. **Pants version** 2.17.0 **OS** Linux **Additional info** I ran into this with a macro that generated image tags and left them blank in some not-in-CI cases. python tests would then throw the above error locally due to a `runtime_package_dependencies` on said image. Which is all to say that the cause was not obvious.
2023-10-04T19:53:59
pantsbuild/pants
19,990
pantsbuild__pants-19990
[ "19979" ]
62c2af211c70d988d55e3a2749ffcbcee3391a8c
diff --git a/src/python/pants/backend/docker/goals/package_image.py b/src/python/pants/backend/docker/goals/package_image.py --- a/src/python/pants/backend/docker/goals/package_image.py +++ b/src/python/pants/backend/docker/goals/package_image.py @@ -43,10 +43,10 @@ from pants.engine.fs import CreateDigest, Digest, FileContent from pants.engine.process import FallibleProcessResult, Process, ProcessExecutionFailure from pants.engine.rules import Get, MultiGet, collect_rules, rule -from pants.engine.target import Target, WrappedTarget, WrappedTargetRequest +from pants.engine.target import InvalidFieldException, Target, WrappedTarget, WrappedTargetRequest from pants.engine.unions import UnionMembership, UnionRule from pants.option.global_options import GlobalOptions, KeepSandboxes -from pants.util.strutil import bullet_list +from pants.util.strutil import bullet_list, softwrap from pants.util.value_interpolation import InterpolationContext, InterpolationError logger = logging.getLogger(__name__) @@ -400,6 +400,16 @@ async def build_docker_image( ) ) tags = tuple(tag.full_name for registry in image_refs for tag in registry.tags) + if not tags: + raise InvalidFieldException( + softwrap( + f""" + The `{DockerImageTagsField.alias}` field in target {field_set.address} must not be + empty, unless there is a custom plugin providing additional tags using the + `DockerImageTagsRequest` union type. + """ + ) + ) # Mix the upstream image ids into the env to ensure that Pants invalidates this # image-building process correctly when an upstream image changes, even though the
diff --git a/src/python/pants/backend/docker/goals/package_image_test.py b/src/python/pants/backend/docker/goals/package_image_test.py --- a/src/python/pants/backend/docker/goals/package_image_test.py +++ b/src/python/pants/backend/docker/goals/package_image_test.py @@ -1778,18 +1778,40 @@ def test_image_ref_formatting(test: ImageRefTest) -> None: assert tuple(image_refs) == test.expect_refs -def test_docker_image_tags_from_plugin_hook(rule_runner: RuleRunner) -> None: - rule_runner.write_files({"docker/test/BUILD": 'docker_image(name="plugin")'}) [email protected]( + "BUILD, plugin_tags, tag_flags", + [ + ( + 'docker_image(name="plugin")', + ("1.2.3",), + ( + "--tag", + "plugin:latest", + "--tag", + "plugin:1.2.3", + ), + ), + ( + 'docker_image(name="plugin", image_tags=[])', + ("1.2.3",), + ( + "--tag", + "plugin:1.2.3", + ), + ), + ], +) +def test_docker_image_tags_from_plugin_hook( + rule_runner: RuleRunner, BUILD: str, plugin_tags: tuple[str, ...], tag_flags: tuple[str, ...] +) -> None: + rule_runner.write_files({"docker/test/BUILD": BUILD}) def check_docker_proc(process: Process): assert process.argv == ( "/dummy/docker", "build", "--pull=False", - "--tag", - "plugin:latest", - "--tag", - "plugin:1.2.3", + *tag_flags, "--file", "docker/test/Dockerfile", ".", @@ -1799,10 +1821,21 @@ def check_docker_proc(process: Process): rule_runner, Address("docker/test", target_name="plugin"), process_assertions=check_docker_proc, - plugin_tags=("1.2.3",), + plugin_tags=plugin_tags, ) +def test_docker_image_tags_defined(rule_runner: RuleRunner) -> None: + rule_runner.write_files({"docker/test/BUILD": 'docker_image(name="no-tags", image_tags=[])'}) + + err = "The `image_tags` field in target docker/test:no-tags must not be empty, unless" + with pytest.raises(InvalidFieldException, match=err): + assert_build( + rule_runner, + Address("docker/test", target_name="no-tags"), + ) + + def test_docker_info_serialize() -> None: image_id = "abc123" # image refs with unique strings (i.e. not actual templates/names etc.), to make sure they're
mysteriously terse engine error message when docker image_tags=[] **Describe the bug** Starting with https://github.com/pantsbuild/example-docker ``` $ git diff | cat diff --git a/src/docker/hello_world/BUILD b/src/docker/hello_world/BUILD index 4b6c1c4..83e04a9 100644 --- a/src/docker/hello_world/BUILD +++ b/src/docker/hello_world/BUILD @@ -4,6 +4,7 @@ docker_image( name="python", source="Dockerfile.python", + image_tags = [] ) docker_image( $ pants package src/docker/hello_world:python 15:32:12.80 [ERROR] 1 Exception encountered: Engine traceback: in `package` goal IndexError: tuple index out of range $ ls -lsthra .pants.d/ total 16K 512 -rw-r----- 1 ecsb ecsb 0 Oct 4 15:30 exceptions.log 512 -rw-r----- 1 ecsb ecsb 0 Oct 4 15:30 exceptions.4637.log 1.5K drwxr-x--- 3 ecsb ecsb 6 Oct 4 15:30 . 1.5K drwxr-x--- 8 ecsb ecsb 15 Oct 4 15:30 .. 11K drwxr-x--- 6 ecsb ecsb 6 Oct 4 15:32 run-tracker 1.5K -rw-r----- 1 ecsb ecsb 2.7K Oct 4 15:32 pants.log $ pants package -ltrace src/docker/hello_world:python 15:32:41.40 [INFO] Initialization options changed: reinitializing scheduler... 15:32:47.64 [INFO] Scheduler initialized. 15:32:49.55 [ERROR] 1 Exception encountered: Engine traceback: in `package` goal IndexError: tuple index out of range ``` Note that the exception log files are empty and logging doesn't give any additional clues. **Pants version** 2.17.0 **OS** Linux **Additional info** I ran into this with a macro that generated image tags and left them blank in some not-in-CI cases. python tests would then throw the above error locally due to a `runtime_package_dependencies` on said image. Which is all to say that the cause was not obvious.
Sorry for the trouble, and thanks for the report. I guess an additional venue to address this is to ensure a better error message for a case like this. My fix merely patches the bug at hand, but if we hit another code path that is flawed in a similar way we'd still be throwing a terrible error message. As a tip for future, the `--print-stacktrace` flag is handy for getting more info about problems like this (https://www.pantsbuild.org/docs/troubleshooting has a few more tips too, if you haven't seen it), and provides a few more hints about where the problem originated (docker): ``` Traceback (most recent call last): File ".../site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File ".../site-packages/pants/core/goals/package.py", line 157, in package_asset packages = await MultiGet( File ".../site-packages/pants/engine/internals/selectors.py", line 358, in MultiGet return await _MultiGet(tuple(__arg0)) File ".../site-packages/pants/engine/internals/selectors.py", line 165, in __await__ result = yield self.gets File ".../site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File ".../site-packages/pants/core/goals/package.py", line 108, in environment_aware_package package = await Get( File ".../site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File ".../site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File ".../site-packages/pants/backend/docker/goals/package_image.py", line 404, in build_docker_image process = docker.build_image( File ".../site-packages/pants/backend/docker/util_rules/docker_binary.py", line 84, in build_image f"Building docker image {tags[0]}" IndexError: tuple index out of range ``` (Of course, not minimising that it would be nice for the diagnostics to be better by default, without requiring extra flags. Plus the `-l` vs. `--print-stacktrace` flag difference is a bit annoying!)
2023-10-06T02:37:58
pantsbuild/pants
19,991
pantsbuild__pants-19991
[ "19979" ]
e4664a97d5a3eba337d676e286401e7dee33e02a
diff --git a/src/python/pants/backend/docker/goals/package_image.py b/src/python/pants/backend/docker/goals/package_image.py --- a/src/python/pants/backend/docker/goals/package_image.py +++ b/src/python/pants/backend/docker/goals/package_image.py @@ -42,10 +42,10 @@ from pants.engine.fs import CreateDigest, Digest, FileContent from pants.engine.process import FallibleProcessResult, Process, ProcessExecutionFailure from pants.engine.rules import Get, MultiGet, collect_rules, rule -from pants.engine.target import Target, WrappedTarget, WrappedTargetRequest +from pants.engine.target import InvalidFieldException, Target, WrappedTarget, WrappedTargetRequest from pants.engine.unions import UnionMembership, UnionRule from pants.option.global_options import GlobalOptions, KeepSandboxes -from pants.util.strutil import bullet_list +from pants.util.strutil import bullet_list, softwrap from pants.util.value_interpolation import InterpolationContext, InterpolationError logger = logging.getLogger(__name__) @@ -392,6 +392,16 @@ async def build_docker_image( ) ) tags = tuple(tag.full_name for registry in image_refs for tag in registry.tags) + if not tags: + raise InvalidFieldException( + softwrap( + f""" + The `{DockerImageTagsField.alias}` field in target {field_set.address} must not be + empty, unless there is a custom plugin providing additional tags using the + `DockerImageTagsRequest` union type. + """ + ) + ) # Mix the upstream image ids into the env to ensure that Pants invalidates this # image-building process correctly when an upstream image changes, even though the
diff --git a/src/python/pants/backend/docker/goals/package_image_test.py b/src/python/pants/backend/docker/goals/package_image_test.py --- a/src/python/pants/backend/docker/goals/package_image_test.py +++ b/src/python/pants/backend/docker/goals/package_image_test.py @@ -1624,18 +1624,40 @@ def test_image_ref_formatting(test: ImageRefTest) -> None: assert tuple(image_refs) == test.expect_refs -def test_docker_image_tags_from_plugin_hook(rule_runner: RuleRunner) -> None: - rule_runner.write_files({"docker/test/BUILD": 'docker_image(name="plugin")'}) [email protected]( + "BUILD, plugin_tags, tag_flags", + [ + ( + 'docker_image(name="plugin")', + ("1.2.3",), + ( + "--tag", + "plugin:latest", + "--tag", + "plugin:1.2.3", + ), + ), + ( + 'docker_image(name="plugin", image_tags=[])', + ("1.2.3",), + ( + "--tag", + "plugin:1.2.3", + ), + ), + ], +) +def test_docker_image_tags_from_plugin_hook( + rule_runner: RuleRunner, BUILD: str, plugin_tags: tuple[str, ...], tag_flags: tuple[str, ...] +) -> None: + rule_runner.write_files({"docker/test/BUILD": BUILD}) def check_docker_proc(process: Process): assert process.argv == ( "/dummy/docker", "build", "--pull=False", - "--tag", - "plugin:latest", - "--tag", - "plugin:1.2.3", + *tag_flags, "--file", "docker/test/Dockerfile", ".", @@ -1645,10 +1667,21 @@ def check_docker_proc(process: Process): rule_runner, Address("docker/test", target_name="plugin"), process_assertions=check_docker_proc, - plugin_tags=("1.2.3",), + plugin_tags=plugin_tags, ) +def test_docker_image_tags_defined(rule_runner: RuleRunner) -> None: + rule_runner.write_files({"docker/test/BUILD": 'docker_image(name="no-tags", image_tags=[])'}) + + err = "The `image_tags` field in target docker/test:no-tags must not be empty, unless" + with pytest.raises(InvalidFieldException, match=err): + assert_build( + rule_runner, + Address("docker/test", target_name="no-tags"), + ) + + def test_docker_info_serialize() -> None: image_id = "abc123" # image refs with unique strings (i.e. not actual templates/names etc.), to make sure they're
mysteriously terse engine error message when docker image_tags=[] **Describe the bug** Starting with https://github.com/pantsbuild/example-docker ``` $ git diff | cat diff --git a/src/docker/hello_world/BUILD b/src/docker/hello_world/BUILD index 4b6c1c4..83e04a9 100644 --- a/src/docker/hello_world/BUILD +++ b/src/docker/hello_world/BUILD @@ -4,6 +4,7 @@ docker_image( name="python", source="Dockerfile.python", + image_tags = [] ) docker_image( $ pants package src/docker/hello_world:python 15:32:12.80 [ERROR] 1 Exception encountered: Engine traceback: in `package` goal IndexError: tuple index out of range $ ls -lsthra .pants.d/ total 16K 512 -rw-r----- 1 ecsb ecsb 0 Oct 4 15:30 exceptions.log 512 -rw-r----- 1 ecsb ecsb 0 Oct 4 15:30 exceptions.4637.log 1.5K drwxr-x--- 3 ecsb ecsb 6 Oct 4 15:30 . 1.5K drwxr-x--- 8 ecsb ecsb 15 Oct 4 15:30 .. 11K drwxr-x--- 6 ecsb ecsb 6 Oct 4 15:32 run-tracker 1.5K -rw-r----- 1 ecsb ecsb 2.7K Oct 4 15:32 pants.log $ pants package -ltrace src/docker/hello_world:python 15:32:41.40 [INFO] Initialization options changed: reinitializing scheduler... 15:32:47.64 [INFO] Scheduler initialized. 15:32:49.55 [ERROR] 1 Exception encountered: Engine traceback: in `package` goal IndexError: tuple index out of range ``` Note that the exception log files are empty and logging doesn't give any additional clues. **Pants version** 2.17.0 **OS** Linux **Additional info** I ran into this with a macro that generated image tags and left them blank in some not-in-CI cases. python tests would then throw the above error locally due to a `runtime_package_dependencies` on said image. Which is all to say that the cause was not obvious.
Sorry for the trouble, and thanks for the report. I guess an additional venue to address this is to ensure a better error message for a case like this. My fix merely patches the bug at hand, but if we hit another code path that is flawed in a similar way we'd still be throwing a terrible error message. As a tip for future, the `--print-stacktrace` flag is handy for getting more info about problems like this (https://www.pantsbuild.org/docs/troubleshooting has a few more tips too, if you haven't seen it), and provides a few more hints about where the problem originated (docker): ``` Traceback (most recent call last): File ".../site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File ".../site-packages/pants/core/goals/package.py", line 157, in package_asset packages = await MultiGet( File ".../site-packages/pants/engine/internals/selectors.py", line 358, in MultiGet return await _MultiGet(tuple(__arg0)) File ".../site-packages/pants/engine/internals/selectors.py", line 165, in __await__ result = yield self.gets File ".../site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File ".../site-packages/pants/core/goals/package.py", line 108, in environment_aware_package package = await Get( File ".../site-packages/pants/engine/internals/selectors.py", line 118, in __await__ result = yield self File ".../site-packages/pants/engine/internals/selectors.py", line 623, in native_engine_generator_send res = rule.send(arg) if err is None else rule.throw(throw or err) File ".../site-packages/pants/backend/docker/goals/package_image.py", line 404, in build_docker_image process = docker.build_image( File ".../site-packages/pants/backend/docker/util_rules/docker_binary.py", line 84, in build_image f"Building docker image {tags[0]}" IndexError: tuple index out of range ``` (Of course, not minimising that it would be nice for the diagnostics to be better by default, without requiring extra flags. Plus the `-l` vs. `--print-stacktrace` flag difference is a bit annoying!)
2023-10-06T02:38:00
pantsbuild/pants
20,011
pantsbuild__pants-20011
[ "18364" ]
225f1101ca49083045c565a8f3c861faab3f6ada
diff --git a/src/python/pants/engine/internals/selectors.py b/src/python/pants/engine/internals/selectors.py --- a/src/python/pants/engine/internals/selectors.py +++ b/src/python/pants/engine/internals/selectors.py @@ -16,18 +16,11 @@ Sequence, Tuple, TypeVar, - Union, cast, overload, ) -from pants.base.exceptions import NativeEngineFailure -from pants.engine.internals.native_engine import ( - PyGeneratorResponseBreak, - PyGeneratorResponseCall, - PyGeneratorResponseGet, - PyGeneratorResponseGetMulti, -) +from pants.engine.internals.native_engine import PyGeneratorResponseCall, PyGeneratorResponseGet from pants.util.strutil import softwrap _Output = TypeVar("_Output") @@ -111,7 +104,7 @@ def __await__( """Allow a Get to be `await`ed within an `async` method, returning a strongly-typed result. The `yield`ed value `self` is interpreted by the engine within - `native_engine_generator_send()`. This class will yield a single Get instance, which is + `generator_send()`. This class will yield a single Get instance, which is a subclass of `PyGeneratorResponseGet`. This is how this method is eventually called: @@ -173,9 +166,9 @@ class Get(Generic[_Output], Awaitable[_Output]): @dataclass(frozen=True) class _MultiGet: - gets: tuple[Get, ...] + gets: tuple[Get | Coroutine, ...] - def __await__(self) -> Generator[tuple[Get, ...], None, tuple]: + def __await__(self) -> Generator[tuple[Get | Coroutine, ...], None, tuple]: result = yield self.gets return cast(Tuple, result) @@ -196,143 +189,152 @@ def __await__(self) -> Generator[tuple[Get, ...], None, tuple]: @overload -async def MultiGet(__gets: Iterable[Get[_Output]]) -> tuple[_Output, ...]: # noqa: F811 +async def MultiGet( + __gets: Iterable[Get[_Output] | Coroutine[Any, Any, _Output]] +) -> tuple[_Output, ...]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Output], - __get1: Get[_Output], - __get2: Get[_Output], - __get3: Get[_Output], - __get4: Get[_Output], - __get5: Get[_Output], - __get6: Get[_Output], - __get7: Get[_Output], - __get8: Get[_Output], - __get9: Get[_Output], - __get10: Get[_Output], - *__gets: Get[_Output], +async def MultiGet( + __get0: Get[_Output] | Coroutine[Any, Any, _Output], + __get1: Get[_Output] | Coroutine[Any, Any, _Output], + __get2: Get[_Output] | Coroutine[Any, Any, _Output], + __get3: Get[_Output] | Coroutine[Any, Any, _Output], + __get4: Get[_Output] | Coroutine[Any, Any, _Output], + __get5: Get[_Output] | Coroutine[Any, Any, _Output], + __get6: Get[_Output] | Coroutine[Any, Any, _Output], + __get7: Get[_Output] | Coroutine[Any, Any, _Output], + __get8: Get[_Output] | Coroutine[Any, Any, _Output], + __get9: Get[_Output] | Coroutine[Any, Any, _Output], + __get10: Get[_Output] | Coroutine[Any, Any, _Output], + *__gets: Get[_Output] | Coroutine[Any, Any, _Output], ) -> tuple[_Output, ...]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Out0], - __get1: Get[_Out1], - __get2: Get[_Out2], - __get3: Get[_Out3], - __get4: Get[_Out4], - __get5: Get[_Out5], - __get6: Get[_Out6], - __get7: Get[_Out7], - __get8: Get[_Out8], - __get9: Get[_Out9], +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], + __get2: Get[_Out2] | Coroutine[Any, Any, _Out2], + __get3: Get[_Out3] | Coroutine[Any, Any, _Out3], + __get4: Get[_Out4] | Coroutine[Any, Any, _Out4], + __get5: Get[_Out5] | Coroutine[Any, Any, _Out5], + __get6: Get[_Out6] | Coroutine[Any, Any, _Out6], + __get7: Get[_Out7] | Coroutine[Any, Any, _Out7], + __get8: Get[_Out8] | Coroutine[Any, Any, _Out8], + __get9: Get[_Out9] | Coroutine[Any, Any, _Out9], ) -> tuple[_Out0, _Out1, _Out2, _Out3, _Out4, _Out5, _Out6, _Out7, _Out8, _Out9]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Out0], - __get1: Get[_Out1], - __get2: Get[_Out2], - __get3: Get[_Out3], - __get4: Get[_Out4], - __get5: Get[_Out5], - __get6: Get[_Out6], - __get7: Get[_Out7], - __get8: Get[_Out8], +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], + __get2: Get[_Out2] | Coroutine[Any, Any, _Out2], + __get3: Get[_Out3] | Coroutine[Any, Any, _Out3], + __get4: Get[_Out4] | Coroutine[Any, Any, _Out4], + __get5: Get[_Out5] | Coroutine[Any, Any, _Out5], + __get6: Get[_Out6] | Coroutine[Any, Any, _Out6], + __get7: Get[_Out7] | Coroutine[Any, Any, _Out7], + __get8: Get[_Out8] | Coroutine[Any, Any, _Out8], ) -> tuple[_Out0, _Out1, _Out2, _Out3, _Out4, _Out5, _Out6, _Out7, _Out8]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Out0], - __get1: Get[_Out1], - __get2: Get[_Out2], - __get3: Get[_Out3], - __get4: Get[_Out4], - __get5: Get[_Out5], - __get6: Get[_Out6], - __get7: Get[_Out7], +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], + __get2: Get[_Out2] | Coroutine[Any, Any, _Out2], + __get3: Get[_Out3] | Coroutine[Any, Any, _Out3], + __get4: Get[_Out4] | Coroutine[Any, Any, _Out4], + __get5: Get[_Out5] | Coroutine[Any, Any, _Out5], + __get6: Get[_Out6] | Coroutine[Any, Any, _Out6], + __get7: Get[_Out7] | Coroutine[Any, Any, _Out7], ) -> tuple[_Out0, _Out1, _Out2, _Out3, _Out4, _Out5, _Out6, _Out7]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Out0], - __get1: Get[_Out1], - __get2: Get[_Out2], - __get3: Get[_Out3], - __get4: Get[_Out4], - __get5: Get[_Out5], - __get6: Get[_Out6], +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], + __get2: Get[_Out2] | Coroutine[Any, Any, _Out2], + __get3: Get[_Out3] | Coroutine[Any, Any, _Out3], + __get4: Get[_Out4] | Coroutine[Any, Any, _Out4], + __get5: Get[_Out5] | Coroutine[Any, Any, _Out5], + __get6: Get[_Out6] | Coroutine[Any, Any, _Out6], ) -> tuple[_Out0, _Out1, _Out2, _Out3, _Out4, _Out5, _Out6]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Out0], - __get1: Get[_Out1], - __get2: Get[_Out2], - __get3: Get[_Out3], - __get4: Get[_Out4], - __get5: Get[_Out5], +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], + __get2: Get[_Out2] | Coroutine[Any, Any, _Out2], + __get3: Get[_Out3] | Coroutine[Any, Any, _Out3], + __get4: Get[_Out4] | Coroutine[Any, Any, _Out4], + __get5: Get[_Out5] | Coroutine[Any, Any, _Out5], ) -> tuple[_Out0, _Out1, _Out2, _Out3, _Out4, _Out5]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Out0], - __get1: Get[_Out1], - __get2: Get[_Out2], - __get3: Get[_Out3], - __get4: Get[_Out4], +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], + __get2: Get[_Out2] | Coroutine[Any, Any, _Out2], + __get3: Get[_Out3] | Coroutine[Any, Any, _Out3], + __get4: Get[_Out4] | Coroutine[Any, Any, _Out4], ) -> tuple[_Out0, _Out1, _Out2, _Out3, _Out4]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Out0], - __get1: Get[_Out1], - __get2: Get[_Out2], - __get3: Get[_Out3], +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], + __get2: Get[_Out2] | Coroutine[Any, Any, _Out2], + __get3: Get[_Out3] | Coroutine[Any, Any, _Out3], ) -> tuple[_Out0, _Out1, _Out2, _Out3]: ... @overload -async def MultiGet( # noqa: F811 - __get0: Get[_Out0], __get1: Get[_Out1], __get2: Get[_Out2] +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], + __get2: Get[_Out2] | Coroutine[Any, Any, _Out2], ) -> tuple[_Out0, _Out1, _Out2]: ... @overload -async def MultiGet(__get0: Get[_Out0], __get1: Get[_Out1]) -> tuple[_Out0, _Out1]: # noqa: F811 +async def MultiGet( + __get0: Get[_Out0] | Coroutine[Any, Any, _Out0], + __get1: Get[_Out1] | Coroutine[Any, Any, _Out1], +) -> tuple[_Out0, _Out1]: ... -async def MultiGet( # noqa: F811 - __arg0: Iterable[Get[_Output]] | Get[_Out0], - __arg1: Get[_Out1] | None = None, - __arg2: Get[_Out2] | None = None, - __arg3: Get[_Out3] | None = None, - __arg4: Get[_Out4] | None = None, - __arg5: Get[_Out5] | None = None, - __arg6: Get[_Out6] | None = None, - __arg7: Get[_Out7] | None = None, - __arg8: Get[_Out8] | None = None, - __arg9: Get[_Out9] | None = None, - *__args: Get[_Output], +async def MultiGet( + __arg0: Iterable[Get[_Output] | Coroutine[Any, Any, _Output]] + | Get[_Out0] + | Coroutine[Any, Any, _Out0], + __arg1: Get[_Out1] | Coroutine[Any, Any, _Out1] | None = None, + __arg2: Get[_Out2] | Coroutine[Any, Any, _Out2] | None = None, + __arg3: Get[_Out3] | Coroutine[Any, Any, _Out3] | None = None, + __arg4: Get[_Out4] | Coroutine[Any, Any, _Out4] | None = None, + __arg5: Get[_Out5] | Coroutine[Any, Any, _Out5] | None = None, + __arg6: Get[_Out6] | Coroutine[Any, Any, _Out6] | None = None, + __arg7: Get[_Out7] | Coroutine[Any, Any, _Out7] | None = None, + __arg8: Get[_Out8] | Coroutine[Any, Any, _Out8] | None = None, + __arg9: Get[_Out9] | Coroutine[Any, Any, _Out9] | None = None, + *__args: Get[_Output] | Coroutine[Any, Any, _Output], ) -> ( tuple[_Output, ...] | tuple[_Out0, _Out1, _Out2, _Out3, _Out4, _Out5, _Out6, _Out7, _Out8, _Out9] @@ -349,7 +351,7 @@ async def MultiGet( # noqa: F811 """Yield a tuple of Get instances all at once. The `yield`ed value `self.gets` is interpreted by the engine within - `native_engine_generator_send()`. This class will yield a tuple of Get instances, + `generator_send()`. This class will yield a tuple of Get instances, which is converted into `PyGeneratorResponse::GetMulti`. The engine will fulfill these Get instances in parallel, and return a tuple of _Output @@ -372,102 +374,71 @@ async def MultiGet( # noqa: F811 return await _MultiGet(tuple(__arg0)) if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and isinstance(__arg2, Get) - and isinstance(__arg3, Get) - and isinstance(__arg4, Get) - and isinstance(__arg5, Get) - and isinstance(__arg6, Get) - and isinstance(__arg7, Get) - and isinstance(__arg8, Get) - and isinstance(__arg9, Get) - and all(isinstance(arg, Get) for arg in __args) - ): - return await _MultiGet( - ( - __arg0, - __arg1, - __arg2, - __arg3, - __arg4, - __arg5, - __arg6, - __arg7, - __arg8, - __arg9, - *__args, - ) - ) - - if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and isinstance(__arg2, Get) - and isinstance(__arg3, Get) - and isinstance(__arg4, Get) - and isinstance(__arg5, Get) - and isinstance(__arg6, Get) - and isinstance(__arg7, Get) - and isinstance(__arg8, Get) + isinstance(__arg0, (Get, Coroutine)) + and __arg1 is None + and __arg2 is None + and __arg3 is None + and __arg4 is None + and __arg5 is None + and __arg6 is None + and __arg7 is None + and __arg8 is None and __arg9 is None and not __args ): - return await _MultiGet( - (__arg0, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, __arg8) - ) + return await _MultiGet((__arg0,)) if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and isinstance(__arg2, Get) - and isinstance(__arg3, Get) - and isinstance(__arg4, Get) - and isinstance(__arg5, Get) - and isinstance(__arg6, Get) - and isinstance(__arg7, Get) + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and __arg2 is None + and __arg3 is None + and __arg4 is None + and __arg5 is None + and __arg6 is None + and __arg7 is None and __arg8 is None and __arg9 is None and not __args ): - return await _MultiGet((__arg0, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7)) + return await _MultiGet((__arg0, __arg1)) if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and isinstance(__arg2, Get) - and isinstance(__arg3, Get) - and isinstance(__arg4, Get) - and isinstance(__arg5, Get) - and isinstance(__arg6, Get) + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and isinstance(__arg2, (Get, Coroutine)) + and __arg3 is None + and __arg4 is None + and __arg5 is None + and __arg6 is None and __arg7 is None and __arg8 is None and __arg9 is None and not __args ): - return await _MultiGet((__arg0, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6)) + return await _MultiGet((__arg0, __arg1, __arg2)) if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and isinstance(__arg2, Get) - and isinstance(__arg3, Get) - and isinstance(__arg4, Get) - and isinstance(__arg5, Get) + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and isinstance(__arg2, (Get, Coroutine)) + and isinstance(__arg3, (Get, Coroutine)) + and __arg4 is None + and __arg5 is None and __arg6 is None and __arg7 is None and __arg8 is None and __arg9 is None and not __args ): - return await _MultiGet((__arg0, __arg1, __arg2, __arg3, __arg4, __arg5)) + return await _MultiGet((__arg0, __arg1, __arg2, __arg3)) if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and isinstance(__arg2, Get) - and isinstance(__arg3, Get) - and isinstance(__arg4, Get) + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and isinstance(__arg2, (Get, Coroutine)) + and isinstance(__arg3, (Get, Coroutine)) + and isinstance(__arg4, (Get, Coroutine)) and __arg5 is None and __arg6 is None and __arg7 is None @@ -478,64 +449,95 @@ async def MultiGet( # noqa: F811 return await _MultiGet((__arg0, __arg1, __arg2, __arg3, __arg4)) if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and isinstance(__arg2, Get) - and isinstance(__arg3, Get) - and __arg4 is None - and __arg5 is None + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and isinstance(__arg2, (Get, Coroutine)) + and isinstance(__arg3, (Get, Coroutine)) + and isinstance(__arg4, (Get, Coroutine)) + and isinstance(__arg5, (Get, Coroutine)) and __arg6 is None and __arg7 is None and __arg8 is None and __arg9 is None and not __args ): - return await _MultiGet((__arg0, __arg1, __arg2, __arg3)) + return await _MultiGet((__arg0, __arg1, __arg2, __arg3, __arg4, __arg5)) if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and isinstance(__arg2, Get) - and __arg3 is None - and __arg4 is None - and __arg5 is None - and __arg6 is None + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and isinstance(__arg2, (Get, Coroutine)) + and isinstance(__arg3, (Get, Coroutine)) + and isinstance(__arg4, (Get, Coroutine)) + and isinstance(__arg5, (Get, Coroutine)) + and isinstance(__arg6, (Get, Coroutine)) and __arg7 is None and __arg8 is None and __arg9 is None and not __args ): - return await _MultiGet((__arg0, __arg1, __arg2)) + return await _MultiGet((__arg0, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6)) if ( - isinstance(__arg0, Get) - and isinstance(__arg1, Get) - and __arg2 is None - and __arg3 is None - and __arg4 is None - and __arg5 is None - and __arg6 is None - and __arg7 is None + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and isinstance(__arg2, (Get, Coroutine)) + and isinstance(__arg3, (Get, Coroutine)) + and isinstance(__arg4, (Get, Coroutine)) + and isinstance(__arg5, (Get, Coroutine)) + and isinstance(__arg6, (Get, Coroutine)) + and isinstance(__arg7, (Get, Coroutine)) and __arg8 is None and __arg9 is None and not __args ): - return await _MultiGet((__arg0, __arg1)) + return await _MultiGet((__arg0, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7)) if ( - isinstance(__arg0, Get) - and __arg1 is None - and __arg2 is None - and __arg3 is None - and __arg4 is None - and __arg5 is None - and __arg6 is None - and __arg7 is None - and __arg8 is None + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and isinstance(__arg2, (Get, Coroutine)) + and isinstance(__arg3, (Get, Coroutine)) + and isinstance(__arg4, (Get, Coroutine)) + and isinstance(__arg5, (Get, Coroutine)) + and isinstance(__arg6, (Get, Coroutine)) + and isinstance(__arg7, (Get, Coroutine)) + and isinstance(__arg8, (Get, Coroutine)) and __arg9 is None and not __args ): - return await _MultiGet((__arg0,)) + return await _MultiGet( + (__arg0, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, __arg8) + ) + + if ( + isinstance(__arg0, (Get, Coroutine)) + and isinstance(__arg1, (Get, Coroutine)) + and isinstance(__arg2, (Get, Coroutine)) + and isinstance(__arg3, (Get, Coroutine)) + and isinstance(__arg4, (Get, Coroutine)) + and isinstance(__arg5, (Get, Coroutine)) + and isinstance(__arg6, (Get, Coroutine)) + and isinstance(__arg7, (Get, Coroutine)) + and isinstance(__arg8, (Get, Coroutine)) + and isinstance(__arg9, (Get, Coroutine)) + and all(isinstance(arg, Get) for arg in __args) + ): + return await _MultiGet( + ( + __arg0, + __arg1, + __arg2, + __arg3, + __arg4, + __arg5, + __arg6, + __arg7, + __arg8, + __arg9, + *__args, + ) + ) args = __arg0, __arg1, __arg2, __arg3, __arg4, __arg5, __arg6, __arg7, __arg8, __arg9, *__args @@ -602,63 +604,3 @@ class Params: def __init__(self, *args: Any) -> None: object.__setattr__(self, "params", tuple(args)) - - -# A specification for how the native engine interacts with @rule coroutines: -# - coroutines may await on any of `Get`, `MultiGet`, `Effect` or other coroutines. -# - we will send back a single `Any` or a tuple of `Any` to the coroutine, depending upon the variant of `Get`. -# - a coroutine will eventually return a single `Any`. -RuleInput = Union[ - # The value used to "start" a Generator. - None, - # A single value requested by a Get. - Any, - # Multiple values requested by a MultiGet. - Tuple[Any, ...], - # An exception to be raised in the Generator. - NativeEngineFailure, -] -RuleOutput = Union[Get, Tuple[Get, ...]] -RuleResult = Any -RuleCoroutine = Coroutine[RuleOutput, RuleInput, RuleResult] -NativeEngineGeneratorResponse = Union[ - PyGeneratorResponseGet, - PyGeneratorResponseGetMulti, - PyGeneratorResponseBreak, -] - - -def native_engine_generator_send( - rule: RuleCoroutine, arg: RuleInput -) -> NativeEngineGeneratorResponse: - err = arg if isinstance(arg, NativeEngineFailure) else None - throw = err and err.failure.get_error() - try: - res = rule.send(arg) if err is None else rule.throw(throw or err) - except StopIteration as e: - return PyGeneratorResponseBreak(e.value) - except Exception as e: - if throw and e.__cause__ is throw: - # Preserve the engine traceback by using the wrapped failure error as cause. The cause - # will be swapped back again in - # `src/rust/engine/src/python.rs:Failure::from_py_err_with_gil()` to preserve the python - # traceback. - e.__cause__ = err - raise - else: - # It isn't necessary to differentiate between `Get` and `Effect` here, as the static - # analysis of `@rule`s has already validated usage. - if isinstance(res, (Call, Get, Effect)): - return res - elif type(res) in (tuple, list): - return PyGeneratorResponseGetMulti(res) - else: - raise ValueError( - softwrap( - f""" - Async @rule error: unrecognized await object - - Expected a rule query such as `Get(..)` or similar, but got: {res!r} - """ - ) - )
diff --git a/src/python/pants/engine/internals/scheduler_test.py b/src/python/pants/engine/internals/scheduler_test.py --- a/src/python/pants/engine/internals/scheduler_test.py +++ b/src/python/pants/engine/internals/scheduler_test.py @@ -11,7 +11,7 @@ from pants.base.exceptions import IncorrectProductError from pants.engine.internals.scheduler import ExecutionError -from pants.engine.rules import Get, implicitly, rule +from pants.engine.rules import Get, MultiGet, implicitly, rule from pants.engine.unions import UnionRule, union from pants.testutil.rule_runner import QueryRule, RuleRunner, engine_error @@ -142,6 +142,11 @@ def c() -> C: async def a() -> A: _ = await b(**implicitly(int(1))) _ = await c() + b1, c1, b2 = await MultiGet( + b(**implicitly(int(1))), + c(), + Get(B, int(1)), + ) return A() @@ -481,8 +486,6 @@ def test_trace_includes_nested_exception_traceback() -> None: The above exception was the direct cause of the following exception: Traceback (most recent call last): - File LOCATION-INFO, in native_engine_generator_send - res = rule.send(arg) if err is None else rule.throw(throw or err) File LOCATION-INFO, in catch_and_reraise raise Exception("nested exception!") from e Exception: nested exception!
Allow gathering/joining multiple `async def` coroutines ala `MultiGet` **Is your feature request related to a problem? Please describe.** In https://github.com/pantsbuild/pants/pull/18303#issuecomment-1441079784, we identify that there's no native way for rule code to run multiple Python `async def` coroutines concurrently, similar to Python's `asyncio.gather` (or `std::future::join!` in Rust). Pants' `MultiGet` is related, but only supports `Get`s specifically. Being able to do this would allow embarrassingly parallel invocations of rule helpers in a loop to achieve maximum concurrency. Once this is done, the flake8 rule added in #18303 should be generalised to flag `await _some_helper()` inside a loop, in addition to `await Get(...)`/`await MultiGet(...)` in a loop. **Describe the solution you'd like** Some mechanism to schedule coroutines (and preferably arbitrary `Awaitable`/`Future` instances) to run concurrently. **Describe alternatives you've considered** N/A **Additional context** N/A
2023-10-10T18:04:11
pantsbuild/pants
20,065
pantsbuild__pants-20065
[ "18292" ]
4dc128b49615f7b7ac9ea549e1f27f98e64ddbac
diff --git a/src/python/pants/engine/internals/defaults.py b/src/python/pants/engine/internals/defaults.py --- a/src/python/pants/engine/internals/defaults.py +++ b/src/python/pants/engine/internals/defaults.py @@ -51,7 +51,7 @@ def create( return cls( *map(freeze, parametrize.args), **{kw: freeze(arg) for kw, arg in parametrize.kwargs.items()}, - ) + ).to_weak() @dataclass @@ -94,10 +94,30 @@ def get_frozen_defaults(self) -> BuildFileDefaults: { target_alias: FrozenDict( { - field_type.alias: self._freeze_field_value(field_type, default) - for field_alias, default in fields.items() - for field_type in self._target_type_field_types(types[target_alias]) - if field_alias in (field_type.alias, field_type.deprecated_alias) + **{ + field_type.alias: self._freeze_field_value(field_type, default) + for field_alias, default in fields.items() + for field_type in self._target_type_field_types(types[target_alias]) + if field_alias in (field_type.alias, field_type.deprecated_alias) + }, + **{ + key: ParametrizeDefault( + parametrize.group_name, + **{ + field_type.alias: self._freeze_field_value(field_type, default) + for field_alias, default in parametrize.kwargs.items() + for field_type in self._target_type_field_types( + types[target_alias] + ) + if field_alias + in (field_type.alias, field_type.deprecated_alias) + }, + ) + .to_weak() + .to_group() + for key, parametrize in fields.items() + if isinstance(parametrize, Parametrize) and parametrize.is_group + }, } ) for target_alias, fields in self.defaults.items() @@ -190,15 +210,24 @@ def _process_defaults( ).keys() ) - for field_alias in default.keys(): - if field_alias not in valid_field_aliases: - if ignore_unknown_fields: - del raw_values[field_alias] - else: - raise InvalidFieldException( - f"Unrecognized field `{field_alias}` for target {target_type.alias}. " - f"Valid fields are: {', '.join(sorted(valid_field_aliases))}.", - ) + def _check_field_alias(field_alias: str) -> None: + if field_alias in valid_field_aliases: + return + if not ignore_unknown_fields: + raise InvalidFieldException( + f"Unrecognized field `{field_alias}` for target {target_type.alias}. " + f"Valid fields are: {', '.join(sorted(valid_field_aliases))}.", + ) + elif field_alias in raw_values: + del raw_values[field_alias] + + for field_alias, field_value in default.items(): + if isinstance(field_value, Parametrize) and field_value.is_group: + field_value.to_weak() + for parametrize_field_alias in field_value.kwargs.keys(): + _check_field_alias(parametrize_field_alias) + else: + _check_field_alias(field_alias) # Merge all provided defaults for this call. defaults.setdefault(target_type.alias, {}).update(raw_values) diff --git a/src/python/pants/engine/internals/parametrize.py b/src/python/pants/engine/internals/parametrize.py --- a/src/python/pants/engine/internals/parametrize.py +++ b/src/python/pants/engine/internals/parametrize.py @@ -5,8 +5,14 @@ import dataclasses import itertools +import operator +from collections import defaultdict from dataclasses import dataclass -from typing import Any, Iterator, cast +from enum import Enum +from functools import reduce +from typing import Any, Iterator, Mapping, cast + +from typing_extensions import Self from pants.build_graph.address import BANNED_CHARS_IN_PARAMETERS from pants.engine.addresses import Address @@ -20,7 +26,7 @@ TargetTypesToGenerateTargetsRequests, ) from pants.util.frozendict import FrozenDict -from pants.util.strutil import bullet_list, softwrap +from pants.util.strutil import bullet_list, pluralize, softwrap def _named_args_explanation(arg: str) -> str: @@ -38,12 +44,39 @@ class Parametrize: means that individual Field instances need not be aware of it. """ + class _MergeBehaviour(Enum): + # Do not merge this parametrization. + never = "never" + # Discard this parametrization with `other`. + replace = "replace" + args: tuple[str, ...] kwargs: FrozenDict[str, ImmutableValue] + is_group: bool + merge_behaviour: _MergeBehaviour = dataclasses.field(compare=False) def __init__(self, *args: str, **kwargs: Any) -> None: object.__setattr__(self, "args", args) object.__setattr__(self, "kwargs", FrozenDict.deep_freeze(kwargs)) + object.__setattr__(self, "is_group", False) + object.__setattr__(self, "merge_behaviour", Parametrize._MergeBehaviour.never) + + def keys(self) -> tuple[str]: + return (f"parametrize_{hash(self.args)}:{id(self)}",) + + def __getitem__(self, key) -> Any: + if isinstance(key, str) and key.startswith("parametrize_"): + return self.to_group() + else: + raise KeyError(key) + + def to_group(self) -> Self: + object.__setattr__(self, "is_group", True) + return self + + def to_weak(self) -> Self: + object.__setattr__(self, "merge_behaviour", Parametrize._MergeBehaviour.replace) + return self def to_parameters(self) -> dict[str, Any]: """Validates and returns a mapping from aliases to parameter values. @@ -74,6 +107,37 @@ def to_parameters(self) -> dict[str, Any]: parameters[arg] = arg return parameters + @property + def group_name(self) -> str: + assert self.is_group + if len(self.args) == 1: + name = self.args[0] + banned_chars = BANNED_CHARS_IN_PARAMETERS & set(name) + if banned_chars: + raise Exception( + f"In {self}:\n Parametrization group name `{name}` contained separator characters " + f"(`{'`,`'.join(banned_chars)}`)." + ) + return name + else: + raise ValueError( + softwrap( + f""" + A parametrize group must begin with the group name followed by the target field + values for the group. + + Example: + + target( + ..., + **parametrize("group-a", field_a=1, field_b=True), + ) + + Got: `{self!r}` + """ + ) + ) + @classmethod def expand( cls, address: Address, fields: dict[str, Any | Parametrize] @@ -85,16 +149,26 @@ def expand( separate calls. """ try: + parametrizations = cls._collect_parametrizations(fields) + cls._check_parametrizations(parametrizations) parametrized: list[list[tuple[str, str, Any]]] = [ [ (field_name, alias, field_value) for alias, field_value in v.to_parameters().items() ] - for field_name, v in fields.items() - if isinstance(v, Parametrize) + for field_name, v in parametrizations.get(None, ()) + ] + parametrized_groups: list[tuple[str, str, Parametrize]] = [ + ("parametrize", group_name, vs[0][1]) + for group_name, vs in parametrizations.items() + if group_name is not None ] except Exception as e: - raise Exception(f"Failed to parametrize `{address}`:\n{e}") from e + raise Exception(f"Failed to parametrize `{address}`:\n {e}") from e + + if parametrized_groups: + # Add the groups as one vector for the cross-product. + parametrized.append(parametrized_groups) if not parametrized: yield (address, fields) @@ -111,14 +185,83 @@ def expand( {field_name: alias for field_name, alias, _ in parametrized_args} ) parametrized_args_fields = tuple( - (field_name, field_value) for field_name, _, field_value in parametrized_args + (field_name, field_value) + for field_name, _, field_value in parametrized_args + # Exclude any parametrize group + if not (isinstance(field_value, Parametrize) and field_value.is_group) ) expanded_fields: dict[str, Any] = dict(non_parametrized + parametrized_args_fields) + expanded_fields.update( + # There will be at most one group per cross product. + next( + ( + field_value.kwargs + for _, _, field_value in parametrized_args + if isinstance(field_value, Parametrize) and field_value.is_group + ), + {}, + ) + ) yield expanded_address, expanded_fields + @staticmethod + def _collect_parametrizations( + fields: dict[str, Any | Parametrize] + ) -> Mapping[str | None, list[tuple[str, Parametrize]]]: + parametrizations = defaultdict(list) + for field_name, v in fields.items(): + if not isinstance(v, Parametrize): + continue + group_name = None if not v.is_group else v.group_name + parametrizations[group_name].append((field_name, v)) + return parametrizations + + @staticmethod + def _check_parametrizations( + parametrizations: Mapping[str | None, list[tuple[str, Parametrize]]] + ) -> None: + for group_name, groups in parametrizations.items(): + if group_name is not None and len(groups) > 1: + group = Parametrize._combine(*(group for _, group in groups)) + groups.clear() + groups.append(("combined", group)) + + parametrize_field_names = {field_name for field_name, v in parametrizations.get(None, ())} + parametrize_field_names_from_groups = { + field_name + for group_name, groups in parametrizations.items() + if group_name is not None + for field_name in groups[0][1].kwargs.keys() + } + conflicting = parametrize_field_names.intersection(parametrize_field_names_from_groups) + if conflicting: + raise ValueError( + softwrap( + f""" + Conflicting parametrizations for {pluralize(len(conflicting), "field", include_count=False)}: + {', '.join(sorted(conflicting))} + """ + ) + ) + + @staticmethod + def _combine(head: Parametrize, *tail: Parametrize) -> Parametrize: + return reduce(operator.add, tail, head) + + def __add__(self, other: Parametrize) -> Parametrize: + if not isinstance(other, Parametrize): + raise TypeError(f"Can not combine {self} with {other!r}") + if self.merge_behaviour is Parametrize._MergeBehaviour.replace: + return other + if other.merge_behaviour is Parametrize._MergeBehaviour.replace: + return self + if self.is_group and other.is_group: + raise ValueError(f"Parametrization group name is not unique: {self.group_name!r}") + raise ValueError(f"Can not combine parametrizations: {self} | {other}") + def __repr__(self) -> str: - strs = [str(s) for s in self.args] - strs.extend(f"{alias}={value}" for alias, value in self.kwargs.items()) + strs = [repr(s) for s in self.args] + strs.extend(f"{alias}={value!r}" for alias, value in self.kwargs.items()) return f"parametrize({', '.join(strs)})"
diff --git a/src/python/pants/engine/internals/build_files_test.py b/src/python/pants/engine/internals/build_files_test.py --- a/src/python/pants/engine/internals/build_files_test.py +++ b/src/python/pants/engine/internals/build_files_test.py @@ -6,7 +6,7 @@ import logging import re from textwrap import dedent -from typing import cast +from typing import Any, Mapping, cast import pytest @@ -543,6 +543,70 @@ def test_parametrize_defaults(target_adaptor_rule_runner: RuleRunner) -> None: assert target_adaptor.kwargs["tags"] == ParametrizeDefault(a=("a", "root"), b=("non-root", "b")) +def test_parametrized_groups(target_adaptor_rule_runner: RuleRunner) -> None: + def _determenistic_parametrize_group_keys(value: Mapping[str, Any]) -> dict[str, Any]: + # The `parametrize` object uses a unique generated field name when splatted onto a target + # (in order to provide a helpful error message in case of non-unique group names), but the + # part up until `:` is determenistic on the group name, which we need to exploit in the + # tests using parametrize groups. + return {key.rsplit(":", 1)[0]: val for key, val in value.items()} + + target_adaptor_rule_runner.write_files( + { + "hello/BUILD": dedent( + """\ + mock_tgt( + description="desc for a and b", + **parametrize("a", tags=["opt-a"], resolve="lock-a"), + **parametrize("b", tags=["opt-b"], resolve="lock-b"), + ) + """ + ), + } + ) + + target_adaptor = target_adaptor_rule_runner.request( + TargetAdaptor, + [TargetAdaptorRequest(Address("hello"), description_of_origin="tests")], + ) + assert _determenistic_parametrize_group_keys( + target_adaptor.kwargs + ) == _determenistic_parametrize_group_keys( + dict( + description="desc for a and b", + **Parametrize("a", tags=["opt-a"], resolve="lock-a"), # type: ignore[arg-type] + **Parametrize("b", tags=["opt-b"], resolve="lock-b"), + ) + ) + + +def test_default_parametrized_groups(target_adaptor_rule_runner: RuleRunner) -> None: + target_adaptor_rule_runner.write_files( + { + "hello/BUILD": dedent( + """\ + __defaults__({mock_tgt: dict(**parametrize("a", tags=["from default"]))}) + mock_tgt( + tags=["from target"], + **parametrize("a"), + **parametrize("b", tags=["from b"]), + ) + """ + ), + } + ) + address = Address("hello") + target_adaptor = target_adaptor_rule_runner.request( + TargetAdaptor, + [TargetAdaptorRequest(address, description_of_origin="tests")], + ) + targets = tuple(Parametrize.expand(address, target_adaptor.kwargs)) + assert targets == ( + (address.parametrize(dict(parametrize="a")), dict(tags=["from target"])), + (address.parametrize(dict(parametrize="b")), dict(tags=("from b",))), + ) + + def test_augment_target_field_defaults(target_adaptor_rule_runner: RuleRunner) -> None: target_adaptor_rule_runner.write_files( { diff --git a/src/python/pants/engine/internals/defaults_test.py b/src/python/pants/engine/internals/defaults_test.py --- a/src/python/pants/engine/internals/defaults_test.py +++ b/src/python/pants/engine/internals/defaults_test.py @@ -4,6 +4,7 @@ from __future__ import annotations from collections import namedtuple +from typing import Any, Mapping import pytest @@ -87,6 +88,14 @@ def test_assumptions( ) +def _determenistic_parametrize_group_keys(value: Mapping[str, Any]) -> dict[str, Any]: + # The `parametrize` object uses a unique generated field name when splatted onto a target (in + # order to provide a helpful error message in case of non-unique group names), but the part up + # until `:` is determenistic on the group name, which we need to exploit in the tests using + # parametrize groups. + return {key.rsplit(":", 1)[0]: val for key, val in value.items()} + + Scenario = namedtuple( "Scenario", "path, args, kwargs, expected_defaults, expected_error, parent_defaults", @@ -235,15 +244,49 @@ def test_assumptions( ), pytest.param( Scenario( - args=({Test1Target.alias: {"tags": Parametrize(["foo"], ["bar"], baz=["baz"])}},), + args=( + { + Test1Target.alias: { + "tags": Parametrize(["foo"], ["bar"], baz=["baz"]), + **Parametrize( + "splat", description="splat-desc", dependencies=["splat:dep"] + ), + } + }, + ), expected_defaults={ - "test_type_1": { - "tags": ParametrizeDefault(("foo",), ("bar",), baz=("baz",)), # type: ignore[arg-type] - } + "test_type_1": _determenistic_parametrize_group_keys( + { + "tags": ParametrizeDefault(("foo",), ("bar",), baz=("baz",)), # type: ignore[arg-type] + **ParametrizeDefault( + "splat", description="splat-desc", dependencies=["splat:dep"] + ), + } + ) }, ), id="parametrize default field value", ), + pytest.param( + Scenario( + args=( + { + Test1Target.alias: { + **Parametrize("splat", description="splat-desc", whats_this="now"), + } + }, + ), + kwargs=dict(ignore_unknown_fields=True), + expected_defaults={ + "test_type_1": _determenistic_parametrize_group_keys( + { + **ParametrizeDefault("splat", description="splat-desc") # type: ignore[list-item] + } + ) + }, + ), + id="parametrize ignore unknown fields", + ), pytest.param( Scenario( args=( @@ -281,6 +324,7 @@ def test_set_defaults( ) defaults.set_defaults(*scenario.args, **scenario.kwargs) actual_defaults = { - tgt: dict(field_values) for tgt, field_values in defaults.get_frozen_defaults().items() + tgt: _determenistic_parametrize_group_keys(field_values) + for tgt, field_values in defaults.get_frozen_defaults().items() } assert scenario.expected_defaults == actual_defaults diff --git a/src/python/pants/engine/internals/parametrize_test.py b/src/python/pants/engine/internals/parametrize_test.py --- a/src/python/pants/engine/internals/parametrize_test.py +++ b/src/python/pants/engine/internals/parametrize_test.py @@ -52,6 +52,19 @@ def test_to_parameters_failure(exception_str: str, args: list[Any], kwargs: dict assert exception_str in str(exc.value) [email protected]( + "exception_str,args,kwargs", + [ + ("A parametrize group must begin with the group name", [], {}), + ("group name `bladder:dust` contained separator characters (`:`).", ["bladder:dust"], {}), + ], +) +def test_bad_group_name(exception_str: str, args: list[Any], kwargs: dict[str, Any]) -> None: + with pytest.raises(Exception) as exc: + Parametrize(*args, **kwargs).to_group().group_name + assert exception_str in str(exc.value) + + @pytest.mark.parametrize( "expected,fields", [ @@ -73,17 +86,77 @@ def test_to_parameters_failure(exception_str: str, args: list[Any], kwargs: dict ], {"f": Parametrize("b", "c"), "x": Parametrize("d", "e")}, ), + ( + [ + ("a@parametrize=A", {"f0": "c", "f1": 1, "f2": 2}), + ("a@parametrize=B", {"f0": "c", "f1": 3, "f2": 4}), + ], + { + "f0": "c", + **Parametrize("A", f1=1, f2=2), + **Parametrize("B", f1=3, f2=4), + }, + ), + ( + [ + ("a@parametrize=A", {"f": 1}), + ("a@parametrize=B", {"f": 2}), + ("a@parametrize=C", {"f": "x", "g": ()}), + ], + # Using a dict constructor rather than a dict literal to get the same semantics as when + # we declare a target in a BUILD file. + dict( + # Field overridden by some parametrize groups. + f="x", + **Parametrize("A", f=1), # type: ignore[arg-type] + **Parametrize("B", f=2), + **Parametrize("C", g=[]), + ), + ), ], ) def test_expand( expected: list[tuple[str, dict[str, Any]]], fields: dict[str, Any | Parametrize] ) -> None: assert sorted(expected) == sorted( - (address.spec, result_fields) - for address, result_fields in Parametrize.expand(Address("a"), fields) + ( + (address.spec, result_fields) + for address, result_fields in Parametrize.expand(Address("a"), fields) + ), + key=lambda value: value[0], ) [email protected]( + "fields, expected_error", + [ + ( + dict( + f=Parametrize("x", "y"), + g=Parametrize("x", "y"), + h=Parametrize("x", "y"), + x=5, + z=6, + **Parametrize("A", f=1), # type: ignore[arg-type] + **Parametrize("B", g=2, x=3), + ), + "Failed to parametrize `a:a`:\n Conflicting parametrizations for fields: f, g", + ), + ( + dict( + f="x", + **Parametrize("A", a=1, b=3), # type: ignore[arg-type] + **Parametrize("A", a=2, c=4), + ), + "Failed to parametrize `a:a`:\n Parametrization group name is not unique: 'A'", + ), + ], +) +def test_expand_error_cases(fields: dict[str, Any], expected_error: str) -> None: + with pytest.raises(Exception, match=expected_error): + _ = list(Parametrize.expand(Address("a"), fields)) + + def test_get_superset_targets() -> None: def tgt(addr: Address) -> GenericTarget: return GenericTarget({}, addr)
Support for pairing specific resolves and interpreter constraints when using `parameterize` Survey submitter said: > make it easier (without a macro) to use paramatierze with interpreter_constraints/resolves without generating the full cross product
More generally, I think this request is a request for a way to use `parametrize()` without it doing a Cartesian product of all fields. So, something like this should have only 3 instances instead of 9 (3 fields * 3 parametrize entries each). ```python pex_binary( ... resolve=parametrize("py36", "py37", "py38"), interpreter_constraints=parametrize( py36=["CPython==3.6.*"], py37=["CPython==3.7.*"], py38=["CPython==3.8.*"], ), output_path=parametrize( py36="st2-py36.pex", py37="st2-py37.pex", py38="st2-py38.pex", ), ) ``` Maybe this could be done by adding a new special kwarg to parametrize like `cartesian=False` (that seems obtuse - and would probably need a better name). So, something like this: ```python pex_binary( ... resolve=parametrize("py36", "py37", "py38", cartesian=False), interpreter_constraints=parametrize( py36=["CPython==3.6.*"], py37=["CPython==3.7.*"], py38=["CPython==3.8.*"], cartesian=False, ), output_path=parametrize( py36="st2-py36.pex", py37="st2-py37.pex", py38="st2-py38.pex", cartesian=False, ), ) ``` Yea. This was discussed in the [original design](https://docs.google.com/document/d/1mzZWnXiE6OkgMH_Dm7WeA3ck9veusQmr_c6GWPb_tsQ/edit#): one other potential syntax for this that was discussed then was: ```python pex_binary( ... **parametrize( py36=dict( resolve="py36", interpreter_constraints=["CPython==3.6.*"], output_path="st2-py36.pex", ), py37=dict( .. }, py38=dict( .. ), ) ) ``` ...which I think could be implemented by having `parametrize` always expand to a `dict` containing one well-known member, and then adjusting each syntax to identify that kwarg, and re-apply it appropriately. The primary question I think is whether it is too magical a syntax (Python users will definitely say "what the heck" when they see it). One way to ameliorate that might be to give the keyword a different name that makes it more obvious what is happening: `parametrize_multiple` or something. One big change from the original design is that at the time `__defaults__` didn't exist: now that it does, the whole "configuration" concept (which was never implemented) is much less relevant, IMO. > The primary question I think is whether it is too magical a syntax Agreed, maybe we could make this syntax work? ```python @parametrize( py36=dict( resolve="py36", interpreter_constraints=["CPython==3.6.*"], output_path="st2-py36.pex", ), py37=dict( .. }, py38=dict( .. ), ) pex_binary( ... ) ``` > > The primary question I think is whether it is too magical a syntax > > Agreed, maybe we could make this syntax work? > ```python > @parametrize( > py36=dict( > resolve="py36", > interpreter_constraints=["CPython==3.6.*"], > output_path="st2-py36.pex", > ), > py37=dict( > .. > }, > py38=dict( > .. > ), > ) > pex_binary( > ... > ) > ``` > This is not valid python (you can only decorate class or function definitions). But we could use a `with` block: ```python with parametrize( py36=dict( resolve="py36", interpreter_constraints=["CPython==3.6.*"], output_path="st2-py36.pex", ), py37=dict( ... }, py38=dict( ... ), ): pex_binary( ... ) ``` Or maybe allow parametrize to take a target as an arg: ```python parametrize( # arg for the target (but only one) pex_binary( ... ), # kwargs for the target field dicts (like overriddes) py36=dict( resolve="py36", interpreter_constraints=["CPython==3.6.*"], output_path="st2-py36.pex", ), py37=dict( ... }, py38=dict( ... ), ) ``` I think this one is my favorite interface so far. > This is not valid python Doh. of course. What I like with the context approach, is that it could be used ~sensibly also with `__defaults__`: ```python with parametrize(...): # Parametrized defaults for all `pex_binary` targets in this subtree. __defaults__(pex_binary=dict(...)) ``` Another idea is to support specifying groups of parametrized fields that should go together as one: ```python pex_binary( ... resolve=parametrize("py36", "py37", "py38"), interpreter_constraints=parametrize( py36=["CPython==3.6.*"], py37=["CPython==3.7.*"], py38=["CPython==3.8.*"], ), output_path=parametrize( py36="st2-py36.pex", py37="st2-py37.pex", py38="st2-py38.pex", ), group_parametrized_fields=[("resolve", "interpreter_constraints", "output_path")], ) ``` Or, as inline options (which is pretty close to @cognifloyd's `cartesian=False` option but supports fields that should not take part in this grouping): ```python pex_binary( ... resolve=parametrize("py36", "py37", "py38", parametrize_group="py-version"), interpreter_constraints=parametrize( py36=["CPython==3.6.*"], py37=["CPython==3.7.*"], py38=["CPython==3.8.*"], parametrize_group="py-version", ), output_path=parametrize( py36="st2-py36.pex", py37="st2-py37.pex", py38="st2-py38.pex", parametrize_group="py-version", ), ) ``` I don't like the idea of injecting a `group_parametrized_fields` field to every target. I like `parametrize_group` as a kwarg to `parametrize`. I think that's the cleanest UX suggestion so far. Using the term `cartesian` would be awful ux imo, so this is much better. Given build files are Python, another option might be allowing using a normal loop: ```python py_versions = [("py36", "CPython==3.6.*"), ...] for short, ic in py_versions: pex_binary( name=placeholder_name("whatever", short=short, ic=ic), resolve=short, interpreter_constraints=ic, output_path="st2-{short}.pex" ) ``` Where `placeholder_name` is a new (as yet unnamed) construct for explicitly computing the appropriate name/address as `parametrize` would. Potentially this might even be unnecessary, if there's no functionality built off the `name@k=v` constructed address, e.g. a user can just compute an appropriate name themselves (for that specific example, `name=f"whatever-{short}"` is probably good). If there is special functionality related to parametrized addresses, then it might be. This does make the build file config less declarative, though. Any extra non-grouped parametrizations can be nested loops, or just `parametrize` calls within the target. > Or, as inline options (which is pretty close to cognifloyd's cartesian=False option but supports fields that should not take part in this grouping): I wonder if that might be error-prone and/or limiting: - I'd be slightly concerned about making a typo like `parametrize_group="py-versoin"` in one of the groups and accidentally ending up with a multiplication. - It seems annoying to list the paired options far apart from each other. - If parametrising by a non-string values (or values that aren't simple strings), passing those values as kwargs to a later `parametrize` call seems difficult? Thoughts? The loop construct works today, except for the `placeholder_name` obviously. I'm not aware of anything relying on the parametrized naming of things so this could well serve as a work-around for that--but I see it as such, a work around. I agree with the raised points about the ergonomics of the previous idea and agree it would be better to allow providing the grouped parametrized values together as one unit. (so, maybe something like the "parametrize-as-context-manager" approach or along those lines). @cognifloyd > I don't like the idea of injecting a `group_parametrized_fields` field to every target. To be clear, I think this would be a construct on the `TargetAdaptor` and not be registered as a target field in the normal sense at all. With that said, it would likely be preferable with a solution that didn't have to touch on the low level adaptors at all. with all of this, I think the original one presented by @stuhood hits the closest, maybe even support using the target type for each group to make it perhaps clearer what is going on: ```python pex_binary( ... **parametrize_group( py36=pex_binary( resolve="py36", interpreter_constraints=["CPython==3.6.*"], output_path="st2-py36.pex", ), py37=pex_binary( resolve="py37", interpreter_constraints=["CPython==3.7.*"], output_path="st2-py37.pex", }, py38=pex_binary( resolve="py38", interpreter_constraints=["CPython==3.8.*"], output_path="st2-py38.pex", ), ) ) ``` And thinking about how this could be implemented, I think this would just be syntactic sugar for something that you could do directly with just a regular target and some options to each `parametrize`d field value, like the `parametrize_group=` but now with the benefit of not having to worry about typos etc. i.e. the above could be the equiv of: ```python pex_binary( ... resolve=parametrize(py36="py36", py37="py37", py38="py38", parametrize_group=1111), interpreter_constraints=parametrize( py36=["CPython==3.6.*"], py37=["CPython==3.7.*"], py38=["CPython==3.8.*"], parametrize_group=1111, ), output_path=parametrize( py36="st2-py36.pex", py37="st2-py37.pex", py38="st2-py38.pex", parametrize_group=1111, ), ) ``` ---- This should be able to support multiple templates too: ```python target( ..., **parametrize_group(a=target(f1=12, f2=98), b=target(f1=34, f2=76)), **parametrize_group(c=target(f3="q", f4="w"), d=target(f3="e", f4="r")), ) ``` sugar for: ```python target( ..., f1=parametrize(a=12, b=34, parametrize_group=1111), f2=parametrize(a=98, b=76, parametrize_group=1111), f3=parametrize(c="q", d="e", parametrize_group=2222), f4=parametrize(c="w, d="r", parametrize_group=2222), ) ``` resulting in these expanded targets: ```python target(..., f1=12, f2=98, f3="q", f4="w") target(..., f1=12, f2=98, f3="e", f4="r") target(..., f1=34, f2=76, f3="q", f4="w") target(..., f1=34, f2=76, f3="e", f4="r") ``` > Given build files are Python, another option might be allowing using a normal loop: That is effectively what I'm doing today: ```python for ic_name, ic in supported_python_interpreter_constraints().items(): pex_binary( name=f"st2-{ic_name}.pex", output_path=f"st2-{ic_name}.pex", interpreter_constraints=ic, dependencies=[ # this should depend on all python_distribution targets ... ], include_tools=True, # include pex.tools to populate a venv from the pex include_sources=False, # always includes generated wheels, so transitive sources not needed venv_hermetic_scripts=False, # do not add -sE to script shebangs ) ``` And I have `supported_python_interpreter_constraints()` defined as a macro: ```python # use this to parametrize targets as necessary. # eg: interpreter_constraints=parametrize(**supported_python_interpreter_constraints()) def supported_python_interpreter_constraints(): return dict( py36=["CPython==3.6.*"], py37=["CPython==3.7.*"], py38=["CPython==3.8.*"], ) ``` --------------------------- The `parametrize_group` thing looks great @kaos. Using `**parametrize_group(` instead of just `**parametrize(` is excellent because it highlights that "this is related to, but not the same as, `parametrize`". So, I vote for the suggested UX in https://github.com/pantsbuild/pants/issues/18292#issuecomment-1523406501 throwing some more ideas on this bonfire: ```python pex_binary( parametrize("py36", resolve="py36", interpreter_constraints=["CPython==3.6.*"], output_path="st2-py36.pex", ), parametrize("py37", resolve="py37", interpreter_constraints=["CPython==3.7.*"], output_path="st2-py37.pex", ), parametrize("py38", resolve="py38", interpreter_constraints=["CPython==3.8.*"], output_path="st2-py38.pex", ), ..., ) ``` That is, you can provide a `parametrize` object as a positional arg to the target, with the first value being the parametriziation "name", and the kwargs are field values for that group.
2023-10-22T02:28:53
pantsbuild/pants
20,069
pantsbuild__pants-20069
[ "19186" ]
73c64b2ceff0bac8ee801615e4ae6b6723d123b8
diff --git a/src/python/pants/backend/codegen/protobuf/python/additional_fields.py b/src/python/pants/backend/codegen/protobuf/python/additional_fields.py --- a/src/python/pants/backend/codegen/protobuf/python/additional_fields.py +++ b/src/python/pants/backend/codegen/protobuf/python/additional_fields.py @@ -33,10 +33,15 @@ def rules(): return [ ProtobufSourceTarget.register_plugin_field(ProtobufPythonInterpreterConstraintsField), ProtobufSourcesGeneratorTarget.register_plugin_field( - ProtobufPythonInterpreterConstraintsField + ProtobufPythonInterpreterConstraintsField, + as_moved_field=True, ), ProtobufSourceTarget.register_plugin_field(ProtobufPythonResolveField), - ProtobufSourcesGeneratorTarget.register_plugin_field(ProtobufPythonResolveField), + ProtobufSourcesGeneratorTarget.register_plugin_field( + ProtobufPythonResolveField, as_moved_field=True + ), ProtobufSourceTarget.register_plugin_field(PythonSourceRootField), - ProtobufSourcesGeneratorTarget.register_plugin_field(PythonSourceRootField), + ProtobufSourcesGeneratorTarget.register_plugin_field( + PythonSourceRootField, as_moved_field=True + ), ]
`protobuf_sources` interacts badly with multiple Python resolves **Describe the bug** I found two issues while trying to get a few protobuf sources to be part of multiple resolves. I'm not sure if it's a setup-specific thing, haven't set up a full repro yet. The base setup is the following: We have a set of resolves that apply to the exact same set of code. To solve this we have the following snippet in the root: ```python __defaults__( { python_source: dict(resolve=parametrize("cpu", "gpu", "reqs")), python_sources: dict(resolve=parametrize("cpu", "gpu", "reqs")), pex_binary: dict(resolve=parametrize("cpu", "gpu", "reqs")), } ) ``` However; parametrizing `protobuf_sources.python_resolve` here fails with the following error: https://github.com/pantsbuild/pants/blob/a34feabef5400eb52472c34900ed39438dfa1d55/src/python/pants/engine/internals/graph.py#L437-L441 Then; I tried to simply generate all the variants in a loop: ```python3 for resolve in ['reqs', 'cpu', 'gpu']: protobuf_sources( name=f'proto_{resolve}', python_resolve=resolve, ..., ) ``` However; we have two files in our set: `foo_v2`, which imports `foo_v1`. Thus, this approach to ambiguity of *which* `foo_v1.proto` it would be importing. Thus, I had to expand to two `protobuf_source` statements with explicit dependencies: ```python3 for resolve in ['reqs', 'cpu', 'gpu']: protobuf_source( name=f"foo_v1_{resolve}", source="foo_v1.proto", grpc=True, python_resolve=resolve, ) protobuf_source( name=f"foo_v2_{resolve}", source="foo_v2.proto", grpc=True, python_resolve=resolve, dependencies=[f":foo_v1_{resolve}"], ) ``` **Pants version** Stable, 2.15.0 **OS** Linux **Additional info** Will try to isolate a repro soon!
@tgolsson thank you for opening this issue. It affects me as well and would be great to solve.
2023-10-23T01:12:00
pantsbuild/pants
20,098
pantsbuild__pants-20098
[ "20084" ]
941ce5bbcff66f8241bd03e33f6b7ff17488ec9d
diff --git a/src/python/pants/backend/python/lint/ruff/rules.py b/src/python/pants/backend/python/lint/ruff/rules.py --- a/src/python/pants/backend/python/lint/ruff/rules.py +++ b/src/python/pants/backend/python/lint/ruff/rules.py @@ -4,12 +4,13 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Any +from typing import Any, Tuple -from pants.backend.python.lint.ruff.subsystem import Ruff, RuffFieldSet +from pants.backend.python.lint.ruff.subsystem import Ruff, RuffFieldSet, RuffMode from pants.backend.python.util_rules import pex from pants.backend.python.util_rules.pex import PexRequest, VenvPex, VenvPexProcess from pants.core.goals.fix import FixResult, FixTargetsRequest +from pants.core.goals.fmt import FmtResult, FmtTargetsRequest from pants.core.goals.lint import LintResult, LintTargetsRequest from pants.core.util_rules.config_files import ConfigFiles, ConfigFilesRequest from pants.core.util_rules.partitions import PartitionerType @@ -39,10 +40,16 @@ class RuffLintRequest(LintTargetsRequest): partitioner_type = PartitionerType.DEFAULT_SINGLE_PARTITION +class RuffFormatRequest(FmtTargetsRequest): + field_set_type = RuffFieldSet + tool_subsystem = Ruff + partitioner_type = PartitionerType.DEFAULT_SINGLE_PARTITION + + @dataclass(frozen=True) class _RunRuffRequest: snapshot: Snapshot - is_fix: bool + mode: RuffMode @rule(level=LogLevel.DEBUG) @@ -64,8 +71,20 @@ async def run_ruff( ) conf_args = [f"--config={ruff.config}"] if ruff.config else [] + + extra_initial_args: Tuple[str, ...] = ("check",) + if request.mode == RuffMode.FORMAT: + extra_initial_args = ("format",) + elif request.mode == RuffMode.FIX: + extra_initial_args = ( + "check", + "--fix", + ) + # `--force-exclude` applies file excludes from config to files provided explicitly - initial_args = ("--force-exclude",) + (("--fix",) if request.is_fix else ()) + # The format argument must be passed before force-exclude if Ruff is used for formatting. + # For other cases, the flags should work the same regardless of the order. + initial_args = extra_initial_args + ("--force-exclude",) result = await Get( FallibleProcessResult, @@ -84,7 +103,7 @@ async def run_ruff( @rule(desc="Fix with ruff", level=LogLevel.DEBUG) async def ruff_fix(request: RuffFixRequest.Batch, ruff: Ruff) -> FixResult: result = await Get( - FallibleProcessResult, _RunRuffRequest(snapshot=request.snapshot, is_fix=True) + FallibleProcessResult, _RunRuffRequest(snapshot=request.snapshot, mode=RuffMode.FIX) ) return await FixResult.create(request, result) @@ -95,15 +114,24 @@ async def ruff_lint(request: RuffLintRequest.Batch[RuffFieldSet, Any]) -> LintRe SourceFiles, SourceFilesRequest(field_set.source for field_set in request.elements) ) result = await Get( - FallibleProcessResult, _RunRuffRequest(snapshot=source_files.snapshot, is_fix=False) + FallibleProcessResult, _RunRuffRequest(snapshot=source_files.snapshot, mode=RuffMode.LINT) ) return LintResult.create(request, result) +@rule(desc="Format with ruff", level=LogLevel.DEBUG) +async def ruff_fmt(request: RuffFormatRequest.Batch, ruff: Ruff) -> FmtResult: + result = await Get( + FallibleProcessResult, _RunRuffRequest(snapshot=request.snapshot, mode=RuffMode.FORMAT) + ) + return await FmtResult.create(request, result) + + def rules(): return [ *collect_rules(), *RuffFixRequest.rules(), *RuffLintRequest.rules(), + *RuffFormatRequest.rules(), *pex.rules(), ] diff --git a/src/python/pants/backend/python/lint/ruff/subsystem.py b/src/python/pants/backend/python/lint/ruff/subsystem.py --- a/src/python/pants/backend/python/lint/ruff/subsystem.py +++ b/src/python/pants/backend/python/lint/ruff/subsystem.py @@ -5,6 +5,7 @@ import os.path from dataclasses import dataclass +from enum import Enum from typing import Iterable from pants.backend.python.lint.ruff.skip_field import SkipRuffField @@ -36,6 +37,12 @@ def opt_out(cls, tgt: Target) -> bool: return tgt.get(SkipRuffField).value +class RuffMode(str, Enum): + FIX = "fix" + FORMAT = "fmt" + LINT = "lint" + + # -------------------------------------------------------------------------------------- # Subsystem # -------------------------------------------------------------------------------------- @@ -44,16 +51,16 @@ def opt_out(cls, tgt: Target) -> bool: class Ruff(PythonToolBase): options_scope = "ruff" name = "Ruff" - help = "The Ruff Python formatter (https://github.com/charliermarsh/ruff)." + help = "The Ruff Python formatter (https://github.com/astral-sh/ruff)." default_main = ConsoleScript("ruff") - default_requirements = ["ruff>=0.0.213,<1"] + default_requirements = ["ruff>=0.1.2,<1"] register_interpreter_constraints = True default_lockfile_resource = ("pants.backend.python.lint.ruff", "ruff.lock") - skip = SkipOption("fmt", "lint") + skip = SkipOption("fmt", "fix", "lint") args = ArgsListOption(example="--exclude=foo --ignore=E501") config = FileOption( default=None, @@ -61,7 +68,7 @@ class Ruff(PythonToolBase): help=softwrap( f""" Path to the `pyproject.toml` or `ruff.toml` file to use for configuration - (https://github.com/charliermarsh/ruff#configuration). + (https://github.com/astral-sh/ruff#configuration). Setting this option will disable `[{options_scope}].config_discovery`. Use this option if the config is located in a non-standard location. @@ -83,7 +90,7 @@ class Ruff(PythonToolBase): ) def config_request(self, dirs: Iterable[str]) -> ConfigFilesRequest: - # See https://github.com/charliermarsh/ruff#configuration for how ruff discovers + # See https://github.com/astral-sh/ruff#configuration for how ruff discovers # config files. return ConfigFilesRequest( specified=self.config,
diff --git a/src/python/pants/backend/python/lint/ruff/rules_integration_test.py b/src/python/pants/backend/python/lint/ruff/rules_integration_test.py --- a/src/python/pants/backend/python/lint/ruff/rules_integration_test.py +++ b/src/python/pants/backend/python/lint/ruff/rules_integration_test.py @@ -9,12 +9,13 @@ from pants.backend.python import target_types_rules from pants.backend.python.lint.ruff import skip_field -from pants.backend.python.lint.ruff.rules import RuffFixRequest, RuffLintRequest +from pants.backend.python.lint.ruff.rules import RuffFixRequest, RuffFormatRequest, RuffLintRequest from pants.backend.python.lint.ruff.rules import rules as ruff_rules from pants.backend.python.lint.ruff.subsystem import RuffFieldSet from pants.backend.python.lint.ruff.subsystem import rules as ruff_subsystem_rules from pants.backend.python.target_types import PythonSourcesGeneratorTarget from pants.core.goals.fix import FixResult +from pants.core.goals.fmt import FmtResult from pants.core.goals.lint import LintResult from pants.core.util_rules import config_files from pants.core.util_rules.partitions import _EmptyMetadata @@ -24,8 +25,9 @@ from pants.testutil.python_interpreter_selection import all_major_minor_python_versions from pants.testutil.rule_runner import QueryRule, RuleRunner -GOOD_FILE = 'a = "string without any placeholders"' -BAD_FILE = 'a = f"string without any placeholders"' +GOOD_FILE = 'a = "string without any placeholders"\n' +BAD_FILE = 'a = f"string without any placeholders"\n' +UNFORMATTED_FILE = 'a ="string without any placeholders"\n' @pytest.fixture @@ -39,6 +41,7 @@ def rule_runner() -> RuleRunner: *target_types_rules.rules(), QueryRule(FixResult, [RuffFixRequest.Batch]), QueryRule(LintResult, [RuffLintRequest.Batch]), + QueryRule(FmtResult, [RuffFormatRequest.Batch]), QueryRule(SourceFiles, (SourceFilesRequest,)), ], target_types=[PythonSourcesGeneratorTarget], @@ -50,7 +53,7 @@ def run_ruff( targets: list[Target], *, extra_args: list[str] | None = None, -) -> tuple[FixResult, LintResult]: +) -> tuple[FixResult, LintResult, FmtResult]: args = ["--backend-packages=pants.backend.python.lint.ruff", *(extra_args or ())] rule_runner.set_options(args, env_inherit={"PATH", "PYENV_ROOT", "HOME"}) @@ -79,8 +82,19 @@ def run_ruff( ), ], ) + fmt_result = rule_runner.request( + FmtResult, + [ + RuffFormatRequest.Batch( + "", + input_sources.snapshot.files, + partition_metadata=None, + snapshot=input_sources.snapshot, + ) + ], + ) - return fix_result, lint_result + return fix_result, lint_result, fmt_result @pytest.mark.platform_specific_behavior @@ -91,7 +105,7 @@ def run_ruff( def test_passing(rule_runner: RuleRunner, major_minor_interpreter: str) -> None: rule_runner.write_files({"f.py": GOOD_FILE, "BUILD": "python_sources(name='t')"}) tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py")) - fix_result, lint_result = run_ruff( + fix_result, lint_result, fmt_result = run_ruff( rule_runner, [tgt], extra_args=[f"--python-interpreter-constraints=['=={major_minor_interpreter}.*']"], @@ -101,17 +115,21 @@ def test_passing(rule_runner: RuleRunner, major_minor_interpreter: str) -> None: assert fix_result.stdout == "" assert not fix_result.did_change assert fix_result.output == rule_runner.make_snapshot({"f.py": GOOD_FILE}) + assert not fmt_result.did_change + assert fmt_result.output == rule_runner.make_snapshot({"f.py": GOOD_FILE}) def test_failing(rule_runner: RuleRunner) -> None: rule_runner.write_files({"f.py": BAD_FILE, "BUILD": "python_sources(name='t')"}) tgt = rule_runner.get_target(Address("", target_name="t", relative_file_path="f.py")) - fix_result, lint_result = run_ruff(rule_runner, [tgt]) + fix_result, lint_result, fmt_result = run_ruff(rule_runner, [tgt]) assert lint_result.exit_code == 1 assert fix_result.stdout == "Found 1 error (1 fixed, 0 remaining).\n" assert fix_result.stderr == "" assert fix_result.did_change assert fix_result.output == rule_runner.make_snapshot({"f.py": GOOD_FILE}) + assert not fmt_result.did_change + assert fmt_result.output == rule_runner.make_snapshot({"f.py": BAD_FILE}) def test_multiple_targets(rule_runner: RuleRunner) -> None: @@ -119,19 +137,25 @@ def test_multiple_targets(rule_runner: RuleRunner) -> None: { "good.py": GOOD_FILE, "bad.py": BAD_FILE, + "unformatted.py": UNFORMATTED_FILE, "BUILD": "python_sources(name='t')", } ) tgts = [ rule_runner.get_target(Address("", target_name="t", relative_file_path="good.py")), rule_runner.get_target(Address("", target_name="t", relative_file_path="bad.py")), + rule_runner.get_target(Address("", target_name="t", relative_file_path="unformatted.py")), ] - fix_result, lint_result = run_ruff(rule_runner, tgts) + fix_result, lint_result, fmt_result = run_ruff(rule_runner, tgts) assert lint_result.exit_code == 1 assert fix_result.output == rule_runner.make_snapshot( - {"good.py": GOOD_FILE, "bad.py": GOOD_FILE} + {"good.py": GOOD_FILE, "bad.py": GOOD_FILE, "unformatted.py": UNFORMATTED_FILE} ) assert fix_result.did_change is True + assert fmt_result.output == rule_runner.make_snapshot( + {"good.py": GOOD_FILE, "bad.py": BAD_FILE, "unformatted.py": GOOD_FILE} + ) + assert fmt_result.did_change is True @pytest.mark.parametrize( @@ -163,6 +187,6 @@ def test_config_file( rel_file_path = file_path.relative_to(*file_path.parts[:1]) if spec_path else file_path addr = Address(spec_path, relative_file_path=str(rel_file_path)) tgt = rule_runner.get_target(addr) - fix_result, lint_result = run_ruff(rule_runner, [tgt], extra_args=extra_args) + fix_result, lint_result, fmt_result = run_ruff(rule_runner, [tgt], extra_args=extra_args) assert lint_result.exit_code == bool(should_change) assert fix_result.did_change is should_change
Support code formatting using Ruff **Is your feature request related to a problem? Please describe.** A Ruff formatter was [just released](https://astral.sh/blog/the-ruff-formatter) and it is _allegedly_ much more performant than Black according to the post. It would be nice if we could run formatting using Ruff via Pants. **Describe the solution you'd like** We should be able to use the Ruff formatter as part of the Ruff integration, as an alternative to Black. **Describe alternatives you've considered** N/A **Additional context** I'm happy to work on this feature myself!
It looks like I can't actually assign the issue to myself, but feel free to assign this issue to me! Yayyy, finally, I've been waiting for this since I first saw Ruff. We already run some fixing via ruff no? So this shouldn't be hard? I don't think it'll be too hard - we should be able to add on to the existing Ruff linter integration for this.
2023-10-26T14:41:58
pantsbuild/pants
20,114
pantsbuild__pants-20114
[ "20067" ]
57a3b7c38ed370a7c863a79fe320015fbe00c9eb
diff --git a/src/python/pants_release/generate_github_workflows.py b/src/python/pants_release/generate_github_workflows.py --- a/src/python/pants_release/generate_github_workflows.py +++ b/src/python/pants_release/generate_github_workflows.py @@ -620,14 +620,14 @@ def bootstrap_jobs( human_readable_job_name += ", test and lint Rust" human_readable_step_name = "Test and lint Rust" # We pass --tests to skip doc tests because our generated protos contain - # invalid doc tests in their comments. + # invalid doc tests in their comments, and --benches to ensure that the + # benchmarks can at least execute once correctly step_cmd = "\n".join( [ "./build-support/bin/check_rust_pre_commit.sh", helper.maybe_append_cargo_test_parallelism( - "./cargo test --locked --all --tests -- --nocapture" + "./cargo test --locked --all --tests --benches -- --nocapture" ), - "./cargo check --benches", "./cargo doc", ] )
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -198,9 +198,7 @@ jobs: ./build-support/bin/check_rust_pre_commit.sh - ./cargo test --locked --all --tests -- --nocapture - - ./cargo check --benches + ./cargo test --locked --all --tests --benches -- --nocapture ./cargo doc' timeout-minutes: 60
Validate benchmarks run successfully in CI It seems like the benchmark tests aren't currently run in CI, and thus can degrade. For instance #20057. I believe that `cargo test --benches` (or something along those lines) allows running benchmarks in "test mode" where they only execute once to provide some sort of assurance that they're functional. I wonder if we could do that too and how big of an impact on CI time it would be. _Originally posted by @huonw in https://github.com/pantsbuild/pants/pull/20057#pullrequestreview-1687414306_
2023-10-29T03:50:30
pantsbuild/pants
20,157
pantsbuild__pants-20157
[ "20156" ]
4bb7688ba9a2d04f8951b18fda9d1500be448339
diff --git a/src/python/pants/backend/scala/bsp/rules.py b/src/python/pants/backend/scala/bsp/rules.py --- a/src/python/pants/backend/scala/bsp/rules.py +++ b/src/python/pants/backend/scala/bsp/rules.py @@ -21,6 +21,10 @@ ) from pants.backend.scala.subsystems.scala import ScalaSubsystem from pants.backend.scala.target_types import ScalaFieldSet, ScalaSourceField +from pants.backend.scala.util_rules.versions import ( + ScalaArtifactsForVersionRequest, + ScalaArtifactsForVersionResult, +) from pants.base.build_root import BuildRoot from pants.bsp.protocol import BSPHandlerMapping from pants.bsp.spec.base import BuildTargetIdentifier @@ -148,22 +152,15 @@ async def collect_thirdparty_modules( async def _materialize_scala_runtime_jars(scala_version: str) -> Snapshot: + scala_artifacts = await Get( + ScalaArtifactsForVersionResult, ScalaArtifactsForVersionRequest(scala_version) + ) + tool_classpath = await Get( ToolClasspath, ToolClasspathRequest( artifact_requirements=ArtifactRequirements.from_coordinates( - [ - Coordinate( - group="org.scala-lang", - artifact="scala-compiler", - version=scala_version, - ), - Coordinate( - group="org.scala-lang", - artifact="scala-library", - version=scala_version, - ), - ] + scala_artifacts.all_coordinates ), ), ) @@ -279,11 +276,17 @@ async def bsp_resolve_scala_metadata( java_version=f"1.{jdk.jre_major_version}", ) + scala_version_parts = scala_version.split(".") + scala_binary_version = ( + ".".join(scala_version_parts[0:2]) + if int(scala_version_parts[0]) < 3 + else scala_version_parts[0] + ) return BSPBuildTargetsMetadataResult( metadata=ScalaBuildTarget( scala_organization="org.scala-lang", scala_version=scala_version, - scala_binary_version=".".join(scala_version.split(".")[0:2]), + scala_binary_version=scala_binary_version, platform=ScalaPlatform.JVM, jars=scala_jar_uris, jvm_build_target=jvm_build_target,
BSP failure when downlading Scala 3 artifacts **Describe the bug** When using Scala 3 and launching the BSP, IntelliJ fails to resolve and download Scala 3 artifacts with following error message: ``` Resolution error: Error downloading org.scala-lang:scala-compiler:3.3.1 not found: https://maven-central.storage-download.googleapis.com/maven2/org/scala-lang/scala-compiler/3.3.1/scala-compiler-3.3.1.pom not found: https://repo1.maven.org/maven2/org/scala-lang/scala-compiler/3.3.1/scala-compiler-3.3.1.pom Error downloading org.scala-lang:scala-library:3.3.1 not found: https://maven-central.storage-download.googleapis.com/maven2/org/scala-lang/scala-library/3.3.1/scala-library-3.3.1.pom not found: https://repo1.maven.org/maven2/org/scala-lang/scala-library/3.3.1/scala-library-3.3.1.pom ``` This is down to referencing the wrong Scala 3 artifacts, as for Scala 3, the right artifact names are `scala3-library_3` and `scala3-compiler_3`. **Pants version** 2.18.0rc5 **OS** both **Additional info** N/A
2023-11-08T09:56:28
pantsbuild/pants
20,163
pantsbuild__pants-20163
[ "20156" ]
7f2f6a91f9aff5df92a5f8a8c6e1d96102415aad
diff --git a/src/python/pants/backend/scala/bsp/rules.py b/src/python/pants/backend/scala/bsp/rules.py --- a/src/python/pants/backend/scala/bsp/rules.py +++ b/src/python/pants/backend/scala/bsp/rules.py @@ -21,6 +21,10 @@ ) from pants.backend.scala.subsystems.scala import ScalaSubsystem from pants.backend.scala.target_types import ScalaFieldSet, ScalaSourceField +from pants.backend.scala.util_rules.versions import ( + ScalaArtifactsForVersionRequest, + ScalaArtifactsForVersionResult, +) from pants.base.build_root import BuildRoot from pants.bsp.protocol import BSPHandlerMapping from pants.bsp.spec.base import BuildTargetIdentifier @@ -148,22 +152,15 @@ async def collect_thirdparty_modules( async def _materialize_scala_runtime_jars(scala_version: str) -> Snapshot: + scala_artifacts = await Get( + ScalaArtifactsForVersionResult, ScalaArtifactsForVersionRequest(scala_version) + ) + tool_classpath = await Get( ToolClasspath, ToolClasspathRequest( artifact_requirements=ArtifactRequirements.from_coordinates( - [ - Coordinate( - group="org.scala-lang", - artifact="scala-compiler", - version=scala_version, - ), - Coordinate( - group="org.scala-lang", - artifact="scala-library", - version=scala_version, - ), - ] + scala_artifacts.all_coordinates ), ), ) @@ -278,11 +275,17 @@ async def bsp_resolve_scala_metadata( java_version=f"1.{jdk.jre_major_version}", ) + scala_version_parts = scala_version.split(".") + scala_binary_version = ( + ".".join(scala_version_parts[0:2]) + if int(scala_version_parts[0]) < 3 + else scala_version_parts[0] + ) return BSPBuildTargetsMetadataResult( metadata=ScalaBuildTarget( scala_organization="org.scala-lang", scala_version=scala_version, - scala_binary_version=".".join(scala_version.split(".")[0:2]), + scala_binary_version=scala_binary_version, platform=ScalaPlatform.JVM, jars=scala_jar_uris, jvm_build_target=jvm_build_target,
BSP failure when downlading Scala 3 artifacts **Describe the bug** When using Scala 3 and launching the BSP, IntelliJ fails to resolve and download Scala 3 artifacts with following error message: ``` Resolution error: Error downloading org.scala-lang:scala-compiler:3.3.1 not found: https://maven-central.storage-download.googleapis.com/maven2/org/scala-lang/scala-compiler/3.3.1/scala-compiler-3.3.1.pom not found: https://repo1.maven.org/maven2/org/scala-lang/scala-compiler/3.3.1/scala-compiler-3.3.1.pom Error downloading org.scala-lang:scala-library:3.3.1 not found: https://maven-central.storage-download.googleapis.com/maven2/org/scala-lang/scala-library/3.3.1/scala-library-3.3.1.pom not found: https://repo1.maven.org/maven2/org/scala-lang/scala-library/3.3.1/scala-library-3.3.1.pom ``` This is down to referencing the wrong Scala 3 artifacts, as for Scala 3, the right artifact names are `scala3-library_3` and `scala3-compiler_3`. **Pants version** 2.18.0rc5 **OS** both **Additional info** N/A
2023-11-08T19:57:02
pantsbuild/pants
20,177
pantsbuild__pants-20177
[ "18629" ]
e542661c5d712e15093beb9e6a1539305e532396
diff --git a/src/python/pants/backend/helm/dependency_inference/chart.py b/src/python/pants/backend/helm/dependency_inference/chart.py --- a/src/python/pants/backend/helm/dependency_inference/chart.py +++ b/src/python/pants/backend/helm/dependency_inference/chart.py @@ -4,11 +4,13 @@ from __future__ import annotations import logging +import os from dataclasses import dataclass from typing import Iterable from pants.backend.helm.resolve import artifacts from pants.backend.helm.resolve.artifacts import ThirdPartyHelmArtifactMapping +from pants.backend.helm.resolve.remotes import HelmRemotes from pants.backend.helm.subsystems.helm import HelmSubsystem from pants.backend.helm.target_types import ( AllHelmChartTargets, @@ -96,6 +98,16 @@ class InferHelmChartDependenciesRequest(InferDependenciesRequest): infer_from = HelmChartDependenciesInferenceFieldSet +def resolve_dependency_url(remotes: HelmRemotes, dependency: HelmChartDependency) -> str | None: + if not dependency.repository: + registry = remotes.default_registry + if registry: + return os.path.join(registry.address, dependency.name) + return None + else: + return os.path.join(dependency.repository, dependency.name) + + @rule(desc="Inferring Helm chart dependencies", level=LogLevel.DEBUG) async def infer_chart_dependencies_via_metadata( request: InferHelmChartDependenciesRequest, @@ -113,15 +125,6 @@ async def infer_chart_dependencies_via_metadata( remotes = subsystem.remotes() - def resolve_dependency_url(dependency: HelmChartDependency) -> str | None: - if not dependency.repository: - registry = remotes.default_registry - if registry: - return f"{registry.address}/{dependency.name}" - return None - else: - return f"{dependency.repository}/{dependency.name}" - # Associate dependencies in Chart.yaml with addresses. dependencies: OrderedSet[Address] = OrderedSet() for chart_dep in metadata.dependencies: @@ -131,7 +134,7 @@ def resolve_dependency_url(dependency: HelmChartDependency) -> str | None: if first_party_dep: candidate_addrs.append(first_party_dep) - dependency_url = resolve_dependency_url(chart_dep) + dependency_url = resolve_dependency_url(remotes, chart_dep) third_party_dep = third_party_mapping.get(dependency_url) if dependency_url else None if third_party_dep: candidate_addrs.append(third_party_dep)
diff --git a/src/python/pants/backend/helm/dependency_inference/chart_test.py b/src/python/pants/backend/helm/dependency_inference/chart_test.py --- a/src/python/pants/backend/helm/dependency_inference/chart_test.py +++ b/src/python/pants/backend/helm/dependency_inference/chart_test.py @@ -9,17 +9,21 @@ FirstPartyHelmChartMapping, HelmChartDependenciesInferenceFieldSet, InferHelmChartDependenciesRequest, + resolve_dependency_url, ) from pants.backend.helm.dependency_inference.chart import rules as chart_infer_rules from pants.backend.helm.resolve import artifacts +from pants.backend.helm.resolve.remotes import HelmRemotes from pants.backend.helm.target_types import HelmArtifactTarget, HelmChartTarget from pants.backend.helm.target_types import rules as target_types_rules from pants.backend.helm.util_rules import chart +from pants.backend.helm.util_rules.chart_metadata import HelmChartDependency from pants.engine.addresses import Address from pants.engine.internals.scheduler import ExecutionError from pants.engine.rules import QueryRule from pants.engine.target import InferredDependencies from pants.testutil.rule_runner import RuleRunner +from pants.util.frozendict import FrozenDict from pants.util.strutil import bullet_list @@ -215,3 +219,21 @@ def test_raise_error_when_unknown_dependency_is_found(rule_runner: RuleRunner) - InferredDependencies, [InferHelmChartDependenciesRequest(HelmChartDependenciesInferenceFieldSet.create(tgt))], ) + + [email protected]( + "dependency,expected", + [ + ( + HelmChartDependency(repository="https://repo.example.com", name="name"), + "https://repo.example.com/name", + ), + ( + HelmChartDependency(repository="https://repo.example.com/", name="name"), + "https://repo.example.com/name", + ), + ], +) +def test_18629(dependency, expected) -> None: + """Test that we properly resolve dependency urls.""" + assert resolve_dependency_url(HelmRemotes(tuple(), FrozenDict()), dependency) == expected
Support optional 3rd party dependencies in helm **Is your feature request related to a problem? Please describe.** I am generating a helm chart that would ordinarily have chart dependencies that are optional based on a condition. The method of defining helm artifacts doesn't seem to allow for this. **Describe the solution you'd like** Preferably defining a 3rd party helm artifact would simply allow it to be used manually inside the chart.yaml instead of injecting the chart automatically (or at least have the option) so that you could manually configure the chart yaml as you would like. **Describe alternatives you've considered** I think I could make proxy 1st party chart that references the 3rd party chart and then make that optional but that is very awkward. **Additional context** Add any other context or screenshots about the feature request here.
You should be able to conditionally include helm charts using `condition` like in normal helm charts : ``` # Chart.yaml apiVersion: v2 name: actual-project version: "0.1.0" dependencies: - name: cert-manager version: "1.13.2" condition: cert-manager.enabled repository: "https://charts.jetstack.io" ``` You still need to define the dependency in a BUILD file, so Pants knows what you're referencing: ``` # BUILD helm_chart() helm_artifact( name="cert-manager", repository="https://charts.jetstack.io", artifact="cert-manager", version="v1.13.2" ) ``` I think we could add a feature to automatically create the `helm_artifact`. @lilatomic It turns out that this doesn't work if you keep a trailing slash on the end of the repository, which is what I had done. I was confused as to why your example worked for me but didn't work for my real life usecase, trial and error narrowed it down to me having my repository as `https://charts.jetstack.io/` not `https://charts.jetstack.io` in the Chart.yaml. Trailing slash in the helm_artifact makes no difference. Oh, then that's a bug on our part. a trailing `/` is valid in the Chart.yaml for dependency repositories (although helm too had to add this as a feature https://github.com/helm/helm/pull/1603)
2023-11-14T08:01:02
pantsbuild/pants
20,191
pantsbuild__pants-20191
[ "20178" ]
5cb1a91e32030a87c7aff1a6ea9a646c5470597f
diff --git a/src/python/pants/engine/internals/parser.py b/src/python/pants/engine/internals/parser.py --- a/src/python/pants/engine/internals/parser.py +++ b/src/python/pants/engine/internals/parser.py @@ -270,6 +270,12 @@ def __str__(self) -> str: return self._type_alias def __call__(self, **kwargs: Any) -> TargetAdaptor: + if self._parse_state.is_bootstrap and any( + isinstance(v, _UnrecognizedSymbol) for v in kwargs.values() + ): + # Remove any field values that are not recognized during the bootstrap phase. + kwargs = {k: v for k, v in kwargs.items() if not isinstance(v, _UnrecognizedSymbol)} + # Target names default to the name of the directory their BUILD file is in # (as long as it's not the root directory). if "name" not in kwargs:
diff --git a/src/python/pants/engine/internals/build_files_test.py b/src/python/pants/engine/internals/build_files_test.py --- a/src/python/pants/engine/internals/build_files_test.py +++ b/src/python/pants/engine/internals/build_files_test.py @@ -775,6 +775,42 @@ def test_default_plugin_field_bootstrap() -> None: assert dict(tags=("ok",)) == dict(address_family.defaults["mock_tgt"]) +def test_environment_target_macro_field_value() -> None: + rule_runner = RuleRunner( + rules=[QueryRule(AddressFamily, [AddressFamilyDir])], + target_types=[MockTgt], + is_bootstrap=True, + ) + rule_runner.set_options( + args=("--build-file-prelude-globs=prelude.py",), + ) + rule_runner.write_files( + { + "prelude.py": dedent( + """ + def tags(): + return ["foo", "bar"] + """ + ), + "BUILD": dedent( + """ + mock_tgt(name="tgt", tags=tags()) + """ + ), + } + ) + + # Parse the root BUILD file. + address_family = rule_runner.request(AddressFamily, [AddressFamilyDir("")]) + tgt = address_family.name_to_target_adaptors["tgt"][1] + # We're pretending that field values returned from a called macro function doesn't exist during + # bootstrap. This is to allow the semi-dubios use of macro calls for environment target field + # values that are not required, and depending on how they are used, it may work to only have + # those field values set during normal lookup. + assert not tgt.kwargs + assert tgt == TargetAdaptor("mock_tgt", "tgt", "BUILD:2") + + def test_build_file_env_vars(target_adaptor_rule_runner: RuleRunner) -> None: target_adaptor_rule_runner.write_files( {
<unrecognized symbol> Error when using marco inside BUILD file **Describe the bug** I tried upgrading pants to 2.18.0. I have a macro file `build_file_prelude_globs = ["pants_plugins/macros.py"]` which worked in in pants 2.16.0 and 2.17.0. When running `pants` with version `2.18.0` I get: ``` Exception caught: (pants.engine.internals.scheduler.ExecutionError) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/bin/pants", line 8, in <module> sys.exit(main()) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 112, in main PantsLoader.main() File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 108, in main cls.run_default_entrypoint() File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 91, in run_default_entrypoint exit_code = runner.run(start_time) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_runner.py", line 142, in run runner = LocalPantsRunner.create( File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/local_pants_runner.py", line 93, in create build_config = options_initializer.build_config(options_bootstrapper, env) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/options_initializer.py", line 153, in build_config return _initialize_build_configuration(self._plugin_resolver, options_bootstrapper, env) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/options_initializer.py", line 52, in _initialize_build_configuration working_set = plugin_resolver.resolve(options_bootstrapper, env, backends_requirements) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/plugin_resolver.py", line 141, in resolve for resolved_plugin_location in self._resolve_plugins(options_bootstrapper, env, request): File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/plugin_resolver.py", line 163, in _resolve_plugins params = Params(request, determine_bootstrap_environment(session)) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/core/util_rules/environments.py", line 448, in determine_bootstrap_environment session.product_request(ChosenLocalEnvironmentName, [Params()])[0], File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 581, in product_request return self.execute(request) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 522, in execute self._raise_on_error([t for _, t in throws]) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 506, in _raise_on_error raise ExecutionError( Exception message: 1 Exception encountered: InvalidTargetException: BUILD:25: The 'subprocess_environment_env_vars' field in target //:local-environment must be an iterable of strings (e.g. a list of strings), but was `env_vars_devcontainer()` with type `<unrecognized symbol>`. NoneType: None ``` It's a really simple macro which just returns something like `["env1=val1", "...."]` **Pants version** 2.18.0 **OS** WSL devcontainer. **Additional info** Reminds me of https://github.com/pantsbuild/pants/issues/19156
The issue is with using macros for environment targets. That is currently not supported. It may have been silently ignored before, where as now you get a proper error message. Did `pants peek //:local-environment` provide the expected value for `subprocess_environment_env_vars` on 2.17.0? Edit: yes, it did.
2023-11-15T22:57:16
pantsbuild/pants
20,198
pantsbuild__pants-20198
[ "20178" ]
93c8a8fe37afeb94a28af3afe278f63dde245b4f
diff --git a/src/python/pants/engine/internals/parser.py b/src/python/pants/engine/internals/parser.py --- a/src/python/pants/engine/internals/parser.py +++ b/src/python/pants/engine/internals/parser.py @@ -270,6 +270,12 @@ def __str__(self) -> str: return self._type_alias def __call__(self, **kwargs: Any) -> TargetAdaptor: + if self._parse_state.is_bootstrap and any( + isinstance(v, _UnrecognizedSymbol) for v in kwargs.values() + ): + # Remove any field values that are not recognized during the bootstrap phase. + kwargs = {k: v for k, v in kwargs.items() if not isinstance(v, _UnrecognizedSymbol)} + # Target names default to the name of the directory their BUILD file is in # (as long as it's not the root directory). if "name" not in kwargs:
diff --git a/src/python/pants/engine/internals/build_files_test.py b/src/python/pants/engine/internals/build_files_test.py --- a/src/python/pants/engine/internals/build_files_test.py +++ b/src/python/pants/engine/internals/build_files_test.py @@ -775,6 +775,42 @@ def test_default_plugin_field_bootstrap() -> None: assert dict(tags=("ok",)) == dict(address_family.defaults["mock_tgt"]) +def test_environment_target_macro_field_value() -> None: + rule_runner = RuleRunner( + rules=[QueryRule(AddressFamily, [AddressFamilyDir])], + target_types=[MockTgt], + is_bootstrap=True, + ) + rule_runner.set_options( + args=("--build-file-prelude-globs=prelude.py",), + ) + rule_runner.write_files( + { + "prelude.py": dedent( + """ + def tags(): + return ["foo", "bar"] + """ + ), + "BUILD": dedent( + """ + mock_tgt(name="tgt", tags=tags()) + """ + ), + } + ) + + # Parse the root BUILD file. + address_family = rule_runner.request(AddressFamily, [AddressFamilyDir("")]) + tgt = address_family.name_to_target_adaptors["tgt"][1] + # We're pretending that field values returned from a called macro function doesn't exist during + # bootstrap. This is to allow the semi-dubios use of macro calls for environment target field + # values that are not required, and depending on how they are used, it may work to only have + # those field values set during normal lookup. + assert not tgt.kwargs + assert tgt == TargetAdaptor("mock_tgt", "tgt", "BUILD:2") + + def test_build_file_env_vars(target_adaptor_rule_runner: RuleRunner) -> None: target_adaptor_rule_runner.write_files( {
<unrecognized symbol> Error when using marco inside BUILD file **Describe the bug** I tried upgrading pants to 2.18.0. I have a macro file `build_file_prelude_globs = ["pants_plugins/macros.py"]` which worked in in pants 2.16.0 and 2.17.0. When running `pants` with version `2.18.0` I get: ``` Exception caught: (pants.engine.internals.scheduler.ExecutionError) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/bin/pants", line 8, in <module> sys.exit(main()) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 112, in main PantsLoader.main() File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 108, in main cls.run_default_entrypoint() File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 91, in run_default_entrypoint exit_code = runner.run(start_time) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_runner.py", line 142, in run runner = LocalPantsRunner.create( File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/local_pants_runner.py", line 93, in create build_config = options_initializer.build_config(options_bootstrapper, env) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/options_initializer.py", line 153, in build_config return _initialize_build_configuration(self._plugin_resolver, options_bootstrapper, env) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/options_initializer.py", line 52, in _initialize_build_configuration working_set = plugin_resolver.resolve(options_bootstrapper, env, backends_requirements) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/plugin_resolver.py", line 141, in resolve for resolved_plugin_location in self._resolve_plugins(options_bootstrapper, env, request): File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/plugin_resolver.py", line 163, in _resolve_plugins params = Params(request, determine_bootstrap_environment(session)) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/core/util_rules/environments.py", line 448, in determine_bootstrap_environment session.product_request(ChosenLocalEnvironmentName, [Params()])[0], File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 581, in product_request return self.execute(request) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 522, in execute self._raise_on_error([t for _, t in throws]) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 506, in _raise_on_error raise ExecutionError( Exception message: 1 Exception encountered: InvalidTargetException: BUILD:25: The 'subprocess_environment_env_vars' field in target //:local-environment must be an iterable of strings (e.g. a list of strings), but was `env_vars_devcontainer()` with type `<unrecognized symbol>`. NoneType: None ``` It's a really simple macro which just returns something like `["env1=val1", "...."]` **Pants version** 2.18.0 **OS** WSL devcontainer. **Additional info** Reminds me of https://github.com/pantsbuild/pants/issues/19156
The issue is with using macros for environment targets. That is currently not supported. It may have been silently ignored before, where as now you get a proper error message. Did `pants peek //:local-environment` provide the expected value for `subprocess_environment_env_vars` on 2.17.0? Edit: yes, it did. OK, to clarify. Macros are not loaded during the bootstrap phase when environment targets are loaded. However, it seems that in certain cases, they are loaded again later with macros present and those that use environment targets in that setting, it may work using macros. I'd suggest not relying on this behaviour as it is rather nuanced and may change unexpectedly between pants releases. I have submitted a fix however to re-open the previous loop-hole.
2023-11-16T22:39:15
pantsbuild/pants
20,199
pantsbuild__pants-20199
[ "20178" ]
76c752c5af26420c495f7bdaee6352b893c8d435
diff --git a/src/python/pants/engine/internals/parser.py b/src/python/pants/engine/internals/parser.py --- a/src/python/pants/engine/internals/parser.py +++ b/src/python/pants/engine/internals/parser.py @@ -270,6 +270,12 @@ def __str__(self) -> str: return self._type_alias def __call__(self, **kwargs: Any) -> TargetAdaptor: + if self._parse_state.is_bootstrap and any( + isinstance(v, _UnrecognizedSymbol) for v in kwargs.values() + ): + # Remove any field values that are not recognized during the bootstrap phase. + kwargs = {k: v for k, v in kwargs.items() if not isinstance(v, _UnrecognizedSymbol)} + # Target names default to the name of the directory their BUILD file is in # (as long as it's not the root directory). if "name" not in kwargs:
diff --git a/src/python/pants/engine/internals/build_files_test.py b/src/python/pants/engine/internals/build_files_test.py --- a/src/python/pants/engine/internals/build_files_test.py +++ b/src/python/pants/engine/internals/build_files_test.py @@ -711,6 +711,42 @@ def test_default_plugin_field_bootstrap() -> None: assert dict(tags=("ok",)) == dict(address_family.defaults["mock_tgt"]) +def test_environment_target_macro_field_value() -> None: + rule_runner = RuleRunner( + rules=[QueryRule(AddressFamily, [AddressFamilyDir])], + target_types=[MockTgt], + is_bootstrap=True, + ) + rule_runner.set_options( + args=("--build-file-prelude-globs=prelude.py",), + ) + rule_runner.write_files( + { + "prelude.py": dedent( + """ + def tags(): + return ["foo", "bar"] + """ + ), + "BUILD": dedent( + """ + mock_tgt(name="tgt", tags=tags()) + """ + ), + } + ) + + # Parse the root BUILD file. + address_family = rule_runner.request(AddressFamily, [AddressFamilyDir("")]) + tgt = address_family.name_to_target_adaptors["tgt"][1] + # We're pretending that field values returned from a called macro function doesn't exist during + # bootstrap. This is to allow the semi-dubios use of macro calls for environment target field + # values that are not required, and depending on how they are used, it may work to only have + # those field values set during normal lookup. + assert not tgt.kwargs + assert tgt == TargetAdaptor("mock_tgt", "tgt", "BUILD:2") + + def test_build_file_env_vars(target_adaptor_rule_runner: RuleRunner) -> None: target_adaptor_rule_runner.write_files( {
<unrecognized symbol> Error when using marco inside BUILD file **Describe the bug** I tried upgrading pants to 2.18.0. I have a macro file `build_file_prelude_globs = ["pants_plugins/macros.py"]` which worked in in pants 2.16.0 and 2.17.0. When running `pants` with version `2.18.0` I get: ``` Exception caught: (pants.engine.internals.scheduler.ExecutionError) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/bin/pants", line 8, in <module> sys.exit(main()) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 112, in main PantsLoader.main() File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 108, in main cls.run_default_entrypoint() File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_loader.py", line 91, in run_default_entrypoint exit_code = runner.run(start_time) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/pants_runner.py", line 142, in run runner = LocalPantsRunner.create( File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/bin/local_pants_runner.py", line 93, in create build_config = options_initializer.build_config(options_bootstrapper, env) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/options_initializer.py", line 153, in build_config return _initialize_build_configuration(self._plugin_resolver, options_bootstrapper, env) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/options_initializer.py", line 52, in _initialize_build_configuration working_set = plugin_resolver.resolve(options_bootstrapper, env, backends_requirements) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/plugin_resolver.py", line 141, in resolve for resolved_plugin_location in self._resolve_plugins(options_bootstrapper, env, request): File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/init/plugin_resolver.py", line 163, in _resolve_plugins params = Params(request, determine_bootstrap_environment(session)) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/core/util_rules/environments.py", line 448, in determine_bootstrap_environment session.product_request(ChosenLocalEnvironmentName, [Params()])[0], File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 581, in product_request return self.execute(request) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 522, in execute self._raise_on_error([t for _, t in throws]) File "/home/vscode/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/engine/internals/scheduler.py", line 506, in _raise_on_error raise ExecutionError( Exception message: 1 Exception encountered: InvalidTargetException: BUILD:25: The 'subprocess_environment_env_vars' field in target //:local-environment must be an iterable of strings (e.g. a list of strings), but was `env_vars_devcontainer()` with type `<unrecognized symbol>`. NoneType: None ``` It's a really simple macro which just returns something like `["env1=val1", "...."]` **Pants version** 2.18.0 **OS** WSL devcontainer. **Additional info** Reminds me of https://github.com/pantsbuild/pants/issues/19156
The issue is with using macros for environment targets. That is currently not supported. It may have been silently ignored before, where as now you get a proper error message. Did `pants peek //:local-environment` provide the expected value for `subprocess_environment_env_vars` on 2.17.0? Edit: yes, it did. OK, to clarify. Macros are not loaded during the bootstrap phase when environment targets are loaded. However, it seems that in certain cases, they are loaded again later with macros present and those that use environment targets in that setting, it may work using macros. I'd suggest not relying on this behaviour as it is rather nuanced and may change unexpectedly between pants releases. I have submitted a fix however to re-open the previous loop-hole.
2023-11-16T22:39:18
pantsbuild/pants
20,217
pantsbuild__pants-20217
[ "20210" ]
98b9c979096b8e8e0bc8ce3466730c6dcb73e70e
diff --git a/src/python/pants/backend/helm/target_types.py b/src/python/pants/backend/helm/target_types.py --- a/src/python/pants/backend/helm/target_types.py +++ b/src/python/pants/backend/helm/target_types.py @@ -498,6 +498,11 @@ class HelmDeploymentValuesField(DictStringToStringField, AsyncFieldMixin): @deprecated("2.19.0.dev0", start_version="2.18.0.dev0") def format_with( self, interpolation_context: InterpolationContext, *, ignore_missing: bool = False + ) -> dict[str, str]: + return self._format_with(interpolation_context, ignore_missing=ignore_missing) + + def _format_with( + self, interpolation_context: InterpolationContext, *, ignore_missing: bool = False ) -> dict[str, str]: source = InterpolationContext.TextSource( self.address, @@ -625,7 +630,7 @@ class HelmDeploymentFieldSet(FieldSet): def format_values( self, interpolation_context: InterpolationContext, *, ignore_missing: bool = False ) -> dict[str, str]: - return self.values.format_with(interpolation_context, ignore_missing=ignore_missing) + return self.values._format_with(interpolation_context, ignore_missing=ignore_missing) class AllHelmDeploymentTargets(Targets): diff --git a/src/python/pants/backend/helm/util_rules/renderer.py b/src/python/pants/backend/helm/util_rules/renderer.py --- a/src/python/pants/backend/helm/util_rules/renderer.py +++ b/src/python/pants/backend/helm/util_rules/renderer.py @@ -326,7 +326,7 @@ async def setup_render_helm_deployment_process( request.field_set.release_name.value or request.field_set.address.target_name.replace("_", "-") ) - inline_values = request.field_set.values.format_with( + inline_values = request.field_set.values._format_with( interpolation_context, ignore_missing=is_render_cmd )
helm 2.18.0 interpolation DEPRECATED warnings appear regardless actual use **Describe the bug** When using the helm backend these warnings are emitted ``` 11:11:03.64 [WARN] DEPRECATED: pants.backend.helm.target_types.HelmDeploymentValuesField.format_with() is scheduled to be removed in version 2.19.0.dev0. ==> /home/ecsb/.cache/nce/3d6643e46b53e4cc0b2a0d5c768866226ddce3de1f57f80c4a02d8d39800fa8e/bindings/venvs/2.18.0/lib/python3.9/site-packages/pants/util/memo.py:123 return memoized_results[key] result = func(*args, **kwargs) memoized_results[key] = result 11:11:03.64 [WARN] DEPRECATED: Using the {env.VAR_NAME} interpolation syntax is scheduled to be removed in version 2.19.0.dev0. ``` Even when the `{env.VAR_NAME}` interpolation syntax is not used anywhere in the target repository. (Besides `grep`, I also tried upgrading to the 2.19.0 series to make sure everything still worked.) **Pants version** 2.18.0 **OS** Linux **Additional info** I remain confused *when* pants chooses to emit DEPRECATED as I can't get it print consistently with `pants --no-local-cache --no-pantsd` https://pantsbuild.slack.com/archives/C046T6T9U/p1700496601965609
2023-11-20T23:56:32
pantsbuild/pants
20,221
pantsbuild__pants-20221
[ "20219" ]
57d1801c80f8273ca386fba198495a05a45f60ae
diff --git a/src/python/pants/util/frozendict.py b/src/python/pants/util/frozendict.py --- a/src/python/pants/util/frozendict.py +++ b/src/python/pants/util/frozendict.py @@ -85,19 +85,27 @@ def __iter__(self) -> Iterator[K]: def __reversed__(self) -> Iterator[K]: return reversed(tuple(self._data)) - def __eq__(self, other: Any) -> bool: - if not isinstance(other, FrozenDict): - return NotImplemented - return tuple(self.items()) == tuple(other.items()) + def __eq__(self, other: Any) -> Any: + # defer to dict's __eq__ + return self._data == other def __lt__(self, other: Any) -> bool: if not isinstance(other, FrozenDict): return NotImplemented - return tuple(self._data.items()) < tuple(other._data.items()) + # If sorting each of these on every __lt__ call ends up being a problem we could consider + # optimising this, by, for instance, sorting on construction. + return sorted(self._data.items()) < sorted(other._data.items()) def _calculate_hash(self) -> int: try: - return hash(tuple(self._data.items())) + h = 0 + for pair in self._data.items(): + # xor is commutative, i.e. we get the same hash no matter the order of items. This + # "relies" on "hash" of the individual elements being unpredictable enough that such + # a naive aggregation is okay. In addition, the Python hash isn't / shouldn't be + # used for cryptographically sensitive purposes. + h ^= hash(pair) + return h except TypeError as e: raise TypeError( softwrap(
diff --git a/src/python/pants/util/frozendict_test.py b/src/python/pants/util/frozendict_test.py --- a/src/python/pants/util/frozendict_test.py +++ b/src/python/pants/util/frozendict_test.py @@ -92,24 +92,41 @@ def test_eq() -> None: fd1 = FrozenDict(d1) assert fd1 == fd1 assert fd1 == FrozenDict(d1) - # Order matters. - assert fd1 != FrozenDict({"b": 1, "a": 0}) - # Must be an instance of FrozenDict. - assert fd1 != d1 - + # Order doesn't matter. + assert fd1 == FrozenDict({"b": 1, "a": 0}) + # A FrozenDict is equal to plain `dict`s with equivalent contents. + assert fd1 == d1 + assert d1 == fd1 [email protected](reason="FrozenDict equality broken for different insertion orders.") -def test_eq_different_orders() -> None: - fd1 = FrozenDict({"a": 0, "b": 1}) - fd2 = FrozenDict({"b": 1, "a": 0}) - assert fd1 == fd2 + # A different dict is not equal. + d2 = {"a": 1, "b": 0} + fd2 = FrozenDict(d2) + assert fd2 != fd1 + assert fd1 != d2 + assert d2 != fd1 def test_lt() -> None: d = {"a": 0, "b": 1} - assert FrozenDict(d) < FrozenDict({"a": 1, "b": 2}) - # Order matters. - assert FrozenDict(d) < FrozenDict({"b": 1, "a": 0}) + + ordered = [ + {"a": 0}, + d, + {"a": 0, "b": 2}, + {"a": 1}, + {"a": 1, "b": 0}, + {"b": -1}, + {"c": -2}, + ] + # Do all comparisions: the list is in order, so the comparisons of the dicts should match the + # comparison of indices. + for i, di in enumerate(ordered): + for j, dj in enumerate(ordered): + assert (FrozenDict(di) < FrozenDict(dj)) == (i < j) + + # Order doesn't matter. + assert FrozenDict(d) < FrozenDict({"b": 2, "a": 0}) + # Must be an instance of FrozenDict. with pytest.raises(TypeError): FrozenDict(d) < d @@ -118,8 +135,22 @@ def test_lt() -> None: def test_hash() -> None: d1 = {"a": 0, "b": 1} assert hash(FrozenDict(d1)) == hash(FrozenDict(d1)) - # Order matters. - assert hash(FrozenDict(d1)) != hash(FrozenDict({"b": 1, "a": 0})) + # Order doesn't matters. + assert hash(FrozenDict(d1)) == hash(FrozenDict({"b": 1, "a": 0})) + + # Confirm that `hash` is likely doing something "correct", and not just implemented as `return + # 0` or similar. + unique_hashes = set() + for i in range(1000): + unique_hashes.add(hash(FrozenDict({"a": i, "b": i}))) + + # It would be incredibly unlikely for 1000 different examples to have so many collisions that we + # saw fewer than 500 unique hash values. (It would be unlikely to see even one collision + # assuming `hash` acts like a uniform random variable: by + # https://en.wikipedia.org/wiki/Birthday_problem, the probability of seeing a single collision + # with m = 2**64 (the size of the output of hash) and n = 1000 is approximately n**2/(2*m) = + # 2.7e-14). + assert len(unique_hashes) >= 500 def test_works_with_dataclasses() -> None:
pants.util.frozendict.FrozenDict has error prone order-sensitive comparisons **Describe the bug** The `FrozenDict` type is order sensitive, which differs to a normal `dict`. It also gives `False` when comparing to a normal dict. This makes it easy to get unexpected behaviour, and likely leads to unnecessary cache misses. https://github.com/pantsbuild/pants/blob/57d1801c80f8273ca386fba198495a05a45f60ae/src/python/pants/util/frozendict.py#L15-L21 ```python d1 = {'a': 0, 'b': 1} d2 = {'b': 1, 'a': 0} print(d1 == d2) # True print(FrozenDict(d1) == FrozenDict(d2)) # False print(FrozenDict(d1) == d1) # False ``` NB. this seems to apply to all methods that call `tuple(self.items())` or similar: `__eq__`, `__lt__`, `_calculate_hash`/`__hash__`. **Pants version** `main` **OS** N/A **Additional info** This caused half of #20210, see #20220.
2023-11-21T05:11:42
pantsbuild/pants
20,239
pantsbuild__pants-20239
[ "20229", "20229" ]
dcf34ab43e75f23fbfdb66993fe1746ae0378f6f
diff --git a/src/python/pants/jvm/package/deploy_jar.py b/src/python/pants/jvm/package/deploy_jar.py --- a/src/python/pants/jvm/package/deploy_jar.py +++ b/src/python/pants/jvm/package/deploy_jar.py @@ -155,6 +155,8 @@ async def package_deploy_jar( ), ) + jar_digest = await Get(Digest, AddPrefix(jar_digest, str(output_filename.parent))) + # # 4. Apply shading rules # @@ -170,9 +172,8 @@ async def package_deploy_jar( ) jar_digest = shaded_jar.digest - prefixed_output_digest = await Get(Digest, AddPrefix(jar_digest, str(output_filename.parent))) artifact = BuiltPackageArtifact(relpath=str(output_filename)) - return BuiltPackage(digest=prefixed_output_digest, artifacts=(artifact,)) + return BuiltPackage(digest=jar_digest, artifacts=(artifact,)) def rules():
diff --git a/src/python/pants/jvm/package/deploy_jar_test.py b/src/python/pants/jvm/package/deploy_jar_test.py --- a/src/python/pants/jvm/package/deploy_jar_test.py +++ b/src/python/pants/jvm/package/deploy_jar_test.py @@ -15,6 +15,7 @@ from pants.build_graph.address import Address from pants.core.goals.package import BuiltPackage from pants.core.util_rules.system_binaries import BashBinary, UnzipBinary +from pants.engine.fs import Snapshot from pants.engine.process import Process, ProcessResult from pants.jvm import jdk_rules from pants.jvm.classpath import rules as classpath_rules @@ -420,6 +421,52 @@ def test_deploy_jar_shaded(rule_runner: RuleRunner) -> None: _deploy_jar_test(rule_runner, "example_app_deploy_jar") +@maybe_skip_jdk_test +def test_deploy_jar_shaded_in_subdir(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "subdir/BUILD": dedent( + """\ + deploy_jar( + name="example_app_deploy_jar", + main="org.pantsbuild.example.Example", + output_path="subdir/dave.jar", + dependencies=[ + ":example", + ], + shading_rules=[ + shading_rename( + pattern="com.fasterxml.jackson.core.**", + replacement="jackson.core.@1", + ) + ] + ) + + java_sources( + name="example", + sources=["**/*.java", ], + dependencies=[ + ":com.fasterxml.jackson.core_jackson-databind", + ], + ) + + jvm_artifact( + name = "com.fasterxml.jackson.core_jackson-databind", + group = "com.fasterxml.jackson.core", + artifact = "jackson-databind", + version = "2.12.5", + ) + """ + ), + "3rdparty/jvm/default.lock": COURSIER_LOCKFILE_SOURCE, + "subdir/Example.java": JAVA_MAIN_SOURCE, + "subdir/lib/ExampleLib.java": JAVA_JSON_MANGLING_LIB_SOURCE, + } + ) + + _deploy_jar_test(rule_runner, "example_app_deploy_jar", path="subdir") + + @maybe_skip_jdk_test def test_deploy_jar_reproducible(rule_runner: RuleRunner) -> None: rule_runner.set_options(args=["--jvm-reproducible-jars"], env_inherit=PYTHON_BOOTSTRAP_ENV) @@ -475,23 +522,28 @@ def test_deploy_jar_reproducible(rule_runner: RuleRunner) -> None: def _deploy_jar_test( - rule_runner: RuleRunner, target_name: str, args: Iterable[str] | None = None + rule_runner: RuleRunner, + target_name: str, + args: Iterable[str] | None = None, + path: str = "", ) -> None: rule_runner.set_options(args=(args or ()), env_inherit=PYTHON_BOOTSTRAP_ENV) - tgt = rule_runner.get_target(Address("", target_name=target_name)) + tgt = rule_runner.get_target(Address(path, target_name=target_name)) jdk = rule_runner.request(InternalJdk, []) fat_jar = rule_runner.request( BuiltPackage, [DeployJarFieldSet.create(tgt)], ) + digest_files = rule_runner.request(Snapshot, [fat_jar.digest]).files + assert len(digest_files) == 1 process_result = rule_runner.request( ProcessResult, [ JvmProcess( jdk=jdk, - argv=("-jar", "dave.jar"), + argv=("-jar", digest_files[0]), classpath_entries=[], description="Run that test jar", input_digest=fat_jar.digest,
Shading throws `NoSuchFileException` given a `deploy_jar` in a subdirectory **Describe the bug** Given a `deploy_jar` target in a subdirectory shading process throws an exception `NoSuchFileException` **Pants version** 2.18.0 **OS** Ubuntu 22.04 **Additional info** `helloworld/HelloWorld.java`: ```java package helloworld; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` `helloworld/BUILD`: ```python java_sources(name="src") ``` `subdir/BUILD`: ```python deploy_jar( name="fat", main="helloworld.HelloWorld", dependencies=["//helloworld:src"], shading_rules=[ shading_keep(pattern="helloworld.**"), ], ) ``` It's important to put deploy_jar into a subdirectory. It works without errors if you put it into root BUILD file. Steps to reproduce: - pants generate-lockfiles - pants subdir:fat I get this: ``` ProcessExecutionFailure: Process 'Shading JAR subdir/fat.jar' failed with exit code 899. ... java.nio.file.NoSuchFileException: subdir/fat.jar ... ``` Shading throws `NoSuchFileException` given a `deploy_jar` in a subdirectory **Describe the bug** Given a `deploy_jar` target in a subdirectory shading process throws an exception `NoSuchFileException` **Pants version** 2.18.0 **OS** Ubuntu 22.04 **Additional info** `helloworld/HelloWorld.java`: ```java package helloworld; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` `helloworld/BUILD`: ```python java_sources(name="src") ``` `subdir/BUILD`: ```python deploy_jar( name="fat", main="helloworld.HelloWorld", dependencies=["//helloworld:src"], shading_rules=[ shading_keep(pattern="helloworld.**"), ], ) ``` It's important to put deploy_jar into a subdirectory. It works without errors if you put it into root BUILD file. Steps to reproduce: - pants generate-lockfiles - pants subdir:fat I get this: ``` ProcessExecutionFailure: Process 'Shading JAR subdir/fat.jar' failed with exit code 899. ... java.nio.file.NoSuchFileException: subdir/fat.jar ... ```
2023-11-24T20:38:42
pantsbuild/pants
20,250
pantsbuild__pants-20250
[ "20246" ]
74f2f03f9eb392303218c0948d8cd8463e1cce38
diff --git a/src/python/pants/backend/python/framework/django/dependency_inference.py b/src/python/pants/backend/python/framework/django/dependency_inference.py --- a/src/python/pants/backend/python/framework/django/dependency_inference.py +++ b/src/python/pants/backend/python/framework/django/dependency_inference.py @@ -23,6 +23,7 @@ from pants.backend.python.util_rules import pex from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints from pants.backend.python.util_rules.pex import PexRequest, VenvPex, VenvPexProcess +from pants.base.specs import FileGlobSpec, RawSpecs from pants.core.util_rules.source_files import SourceFilesRequest from pants.core.util_rules.stripped_source_files import StrippedSourceFiles from pants.engine.fs import CreateDigest, FileContent @@ -30,7 +31,7 @@ from pants.engine.internals.selectors import Get from pants.engine.process import ProcessResult from pants.engine.rules import collect_rules, rule -from pants.engine.target import InferDependenciesRequest, InferredDependencies +from pants.engine.target import InferDependenciesRequest, InferredDependencies, Targets from pants.engine.unions import UnionRule from pants.util.logging import LogLevel from pants.util.resources import read_resource @@ -41,19 +42,17 @@ class InferDjangoDependencies(InferDependenciesRequest): _visitor_resource = "scripts/dependency_visitor.py" +_implicit_dependency_packages = ( + "management.commands", + "migrations", +) -@rule -async def django_parser_script( +async def _django_migration_dependencies( request: InferDjangoDependencies, python_setup: PythonSetup, django_apps: DjangoApps, ) -> InferredDependencies: - source_field = request.field_set.source - # NB: This doesn't consider https://docs.djangoproject.com/en/4.2/ref/settings/#std-setting-MIGRATION_MODULES - if not PurePath(source_field.file_path).match("migrations/*.py"): - return InferredDependencies([]) - stripped_sources = await Get( StrippedSourceFiles, SourceFilesRequest([request.field_set.source]) ) @@ -117,6 +116,77 @@ async def django_parser_script( ) +async def _django_app_implicit_dependencies( + request: InferDjangoDependencies, + python_setup: PythonSetup, + django_apps: DjangoApps, +) -> InferredDependencies: + file_path = request.field_set.source.file_path + apps = [ + django_app for django_app in django_apps.values() if django_app.config_file == file_path + ] + if not apps: + return InferredDependencies([]) + + app_package = apps[0].name + + implicit_dependency_packages = [ + f"{app_package}.{subpackage}" for subpackage in _implicit_dependency_packages + ] + + resolve = request.field_set.resolve.normalized_value(python_setup) + + resolved_dependencies = await Get( + ResolvedParsedPythonDependencies, + ResolvedParsedPythonDependenciesRequest( + request.field_set, + ParsedPythonDependencies( + ParsedPythonImports( + (package, ParsedPythonImportInfo(0, False)) + for package in implicit_dependency_packages + ), + ParsedPythonAssetPaths(), + ), + resolve, + ), + ) + + spec_paths = [ + address.spec_path + for result in resolved_dependencies.resolve_results.values() + if result.status in (ImportOwnerStatus.unambiguous, ImportOwnerStatus.disambiguated) + for address in result.address + ] + + targets = await Get( + Targets, + RawSpecs, + RawSpecs.create( + specs=[FileGlobSpec(f"{spec_path}/*.py") for spec_path in spec_paths], + description_of_origin="Django implicit dependency detection", + ), + ) + + return InferredDependencies(sorted(target.address for target in targets)) + + +@rule +async def infer_django_dependencies( + request: InferDjangoDependencies, + python_setup: PythonSetup, + django_apps: DjangoApps, +) -> InferredDependencies: + source_field = request.field_set.source + # NB: This doesn't consider https://docs.djangoproject.com/en/4.2/ref/settings/#std-setting-MIGRATION_MODULES + path = PurePath(source_field.file_path) + if path.match("migrations/*.py"): + return await _django_migration_dependencies(request, python_setup, django_apps) + elif path.match("apps.py"): + return await _django_app_implicit_dependencies(request, python_setup, django_apps) + else: + return InferredDependencies([]) + + def rules(): return [ *collect_rules(), diff --git a/src/python/pants/backend/python/framework/django/detect_apps.py b/src/python/pants/backend/python/framework/django/detect_apps.py --- a/src/python/pants/backend/python/framework/django/detect_apps.py +++ b/src/python/pants/backend/python/framework/django/detect_apps.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import os from collections import defaultdict from dataclasses import dataclass @@ -27,12 +28,30 @@ @dataclass(frozen=True) -class DjangoApps: - label_to_name: FrozenDict[str, str] +class DjangoApp: + name: str + config_file: str - def add_from_json(self, json_bytes: bytes) -> "DjangoApps": - apps = dict(self.label_to_name, **json.loads(json_bytes.decode())) - return DjangoApps(FrozenDict(sorted(apps.items()))) + +class DjangoApps(FrozenDict[str, DjangoApp]): + @property + def label_to_name(self) -> FrozenDict[str, str]: + return FrozenDict((label, app.name) for label, app in self.items()) + + @property + def label_to_file(self) -> FrozenDict[str, str]: + return FrozenDict((label, app.config_file) for label, app in self.items()) + + def add_from_json(self, json_bytes: bytes, strip_prefix="") -> "DjangoApps": + json_dict: dict[str, dict[str, str]] = json.loads(json_bytes.decode()) + apps = { + label: DjangoApp( + val["app_name"], val["config_file"].partition(f"{strip_prefix}{os.sep}")[2] + ) + for label, val in json_dict.items() + } + combined = dict(self, **apps) + return DjangoApps(sorted(combined.items())) _script_resource = "scripts/app_detector.py" @@ -119,7 +138,10 @@ async def detect_django_apps(python_setup: PythonSetup) -> DjangoApps: description="Detect Django apps", ), ) - django_apps = django_apps.add_from_json(process_result.stdout or b"{}") + django_apps = django_apps.add_from_json( + process_result.stdout or b"{}", strip_prefix=apps_sandbox_prefix + ) + return django_apps diff --git a/src/python/pants/backend/python/framework/django/scripts/app_detector.py b/src/python/pants/backend/python/framework/django/scripts/app_detector.py --- a/src/python/pants/backend/python/framework/django/scripts/app_detector.py +++ b/src/python/pants/backend/python/framework/django/scripts/app_detector.py @@ -77,7 +77,7 @@ def handle_file(apps, path): visitor.visit(tree) if visitor.app_name: - apps[visitor.app_label] = visitor.app_name + apps[visitor.app_label] = {"app_name": visitor.app_name, "config_file": path} def main(paths):
diff --git a/src/python/pants/backend/python/framework/django/dependency_inference_test.py b/src/python/pants/backend/python/framework/django/dependency_inference_test.py --- a/src/python/pants/backend/python/framework/django/dependency_inference_test.py +++ b/src/python/pants/backend/python/framework/django/dependency_inference_test.py @@ -46,12 +46,12 @@ def rule_runner() -> RuleRunner: return rule_runner -def do_test_migration_dependencies(rule_runner: RuleRunner, constraints: str) -> None: - rule_runner.write_files( - { - "BUILD": "python_source(name='t', source='path/to/app0/migrations/0001_initial.py')", - "path/to/app0/migrations/0001_initial.py": dedent( - """\ +def files(constraints: str) -> dict[str, str]: + return { + "BUILD": "python_source(name='t', source='path/to/app0/migrations/0001_initial.py')", + "path/to/app0/migrations/__init__.py": "", + "path/to/app0/migrations/0001_initial.py": dedent( + """\ class Migration(migrations.Migration): dependencies = [ ("app1", "0012_some_migration"), @@ -60,43 +60,82 @@ class Migration(migrations.Migration): operations = [] """ - ), - "path/to/app1/BUILD": dedent( - f"""\ + ), + "path/to/app1/BUILD": dedent( + f"""\ python_source( + name="app1", source="apps.py", interpreter_constraints=['{constraints}'], ) + python_source( + name="initpy", + source="__init__.py", + ) """ - ), - "path/to/app1/apps.py": dedent( - """\ + ), + "path/to/app1/__init__.py": "", + "path/to/app1/apps.py": dedent( + """\ class App1AppConfig(AppConfig): name = "path.to.app1" label = "app1" """ - ), - "path/to/app1/migrations/BUILD": "python_source(source='0012_some_migration.py')", - "path/to/app1/migrations/0012_some_migration.py": "", - "another/path/app2/BUILD": dedent( - f"""\ + ), + "path/to/app1/management/commands/BUILD": dedent( + """\ + python_source(source='do_a_thing.py') + python_source( + name="initpy", + source="__init__.py", + ) + """ + ), + "path/to/app1/management/commands/__init__.py": "", + "path/to/app1/management/commands/do_a_thing.py": "", + "path/to/app1/migrations/BUILD": dedent( + """\ + python_source(source='0012_some_migration.py') + python_source( + name="initpy", + source="__init__.py", + ) + """ + ), + "path/to/app1/migrations/__init__.py": "", + "path/to/app1/migrations/0012_some_migration.py": "", + "another/path/app2/BUILD": dedent( + f"""\ python_source( source="apps.py", interpreter_constraints=['{constraints}'], ) """ - ), - "another/path/app2/apps.py": dedent( - """\ + ), + "another/path/app2/__init__.py": "", + "another/path/app2/apps.py": dedent( + """\ class App2AppConfig(AppConfig): name = "another.path.app2" label = "app2_label" """ - ), - "another/path/app2/migrations/BUILD": "python_source(source='0042_another_migration.py')", - "another/path/app2/migrations/0042_another_migration.py": "", - } - ) + ), + "another/path/app2/migrations/BUILD": dedent( + """\ + python_source(source='0042_another_migration.py') + python_source( + name="initpy", + source="__init__.py", + ) + """ + ), + "another/path/app2/migrations/__init__.py": "", + "another/path/app2/migrations/0042_another_migration.py": "", + } + + +def do_test_migration_dependencies(rule_runner: RuleRunner, constraints: str) -> None: + rule_runner.write_files(files(constraints)) tgt = rule_runner.get_target(Address("", target_name="t")) result = rule_runner.request( InferredDependencies, @@ -112,21 +151,45 @@ class App2AppConfig(AppConfig): } +def do_test_implicit_app_dependencies(rule_runner: RuleRunner, constraints: str) -> None: + rule_runner.write_files(files(constraints)) + tgt = rule_runner.get_target(Address("path/to/app1", target_name="app1")) + print(tgt) + result = rule_runner.request( + InferredDependencies, + [ + dependency_inference.InferDjangoDependencies( + PythonImportDependenciesInferenceFieldSet.create(tgt) + ) + ], + ) + assert set(result.include) == { + Address("path/to/app1/migrations", target_name="migrations"), + Address("path/to/app1/migrations", target_name="initpy"), + Address("path/to/app1/management/commands", target_name="commands"), + Address("path/to/app1/management/commands", target_name="initpy"), + } + + @skip_unless_python27_present def test_works_with_python2(rule_runner: RuleRunner) -> None: do_test_migration_dependencies(rule_runner, constraints="CPython==2.7.*") + do_test_implicit_app_dependencies(rule_runner, constraints="CPython==2.7.*") @skip_unless_python37_present def test_works_with_python37(rule_runner: RuleRunner) -> None: do_test_migration_dependencies(rule_runner, constraints="CPython==3.7.*") + do_test_implicit_app_dependencies(rule_runner, constraints="CPython==3.7.*") @skip_unless_python38_present def test_works_with_python38(rule_runner: RuleRunner) -> None: do_test_migration_dependencies(rule_runner, constraints="CPython==3.8.*") + do_test_implicit_app_dependencies(rule_runner, constraints="CPython==3.8.*") @skip_unless_python39_present def test_works_with_python39(rule_runner: RuleRunner) -> None: do_test_migration_dependencies(rule_runner, constraints="CPython==3.9.*") + do_test_implicit_app_dependencies(rule_runner, constraints="CPython==3.9.*") diff --git a/src/python/pants/backend/python/framework/django/detect_apps_test.py b/src/python/pants/backend/python/framework/django/detect_apps_test.py --- a/src/python/pants/backend/python/framework/django/detect_apps_test.py +++ b/src/python/pants/backend/python/framework/django/detect_apps_test.py @@ -7,7 +7,7 @@ from pants.backend.python.dependency_inference import parse_python_dependencies from pants.backend.python.framework.django import detect_apps -from pants.backend.python.framework.django.detect_apps import DjangoApps +from pants.backend.python.framework.django.detect_apps import DjangoApp, DjangoApps from pants.backend.python.target_types import PythonSourceTarget from pants.backend.python.util_rules import pex from pants.core.util_rules import stripped_source_files @@ -114,7 +114,13 @@ class App3AppConfig(AppConfig): [], ) assert result == DjangoApps( - FrozenDict({"app1": "path.to.app1", "app2_label": "another.path.app2", "app3": "some.app3"}) + FrozenDict( + { + "app1": DjangoApp("path.to.app1", "path/to/app1/apps.py"), + "app2_label": DjangoApp("another.path.app2", "another/path/app2/apps.py"), + "app3": DjangoApp("some.app3", "some/app3/apps.py"), + } + ) )
Django `manage.py` files should infer dependencies on migrations from `INSTALLED_APPS` Currently, running any Django management command that depends on migrations requires running `manage.py` outside the sandbox, or (apparently) explicitly declaring migrations packages as dependencies of `manage.py`. `manage.py` knows which migrations to run by way of the apps declared in the `INSTALLED_APPS` value in a Django settings file. With the experimental Django plugin, it appears that Django migrations are able to infer dependencies on other migrations by way of understanding the `AppConfig.name` value in the `apps.py` file for those other migrations. It appears that the leaf migrations still need to be declared automatically to be picked up as a dependency. With that in mind, it looks like `INSTALLED_APPS` values can be inspected -- they either declare a package spec, or an `AppConfig` class, with a name that consists of a package spec. That should be enough information to infer dependencies on those migrations. Pants should do that :) **UPDATE**: It looks like management commands are in the same boat, and should also get picked up.
The trouble with `INSTALLED_APPS` is that it may not consist only of hardcoded values in a single place, so static analysis may work for simple cases.. perhaps good enough? @kaos Agreed, it's not going to be complete. It'll be about as good as our ability to infer string imports, which exists for other strings in `settings.py` files, so probably good enough? String imports should already get us an inferred dep from settings.py to the package containing an app. But that just turns into a dep on that package's `__init__.py`, which is typically empty. So the question in my mind is: do we want to 1) infer a dep from settings.py on the migrations inside that package, or 2) infer a dep from an app package's `__init__.py` onto various things inside its package (in this case, migrations). The latter seems "correct" in the sense that this is probably what you mean when you list an app in settings.py. You're not saying "depend on this app's migrations", you're saying "depend on ~everything in this app". Doing fine-grained deps on slivers of code inside apps may be incompatible with Django's whole thing. I'm not at all sure what the right answer is. @benjyw Well, for starters, Python packages don't need `__init__.py ` files any more, and running `PANTS_PYTHON_INFER_STRING_IMPORTS_MIN_DOTS=1 pants dependencies src/python/DjangoProjectName/config/settings/base.py` with an `INSTALLED_APP` that contains no `__init__.py` doesn't work. The good news is that it's also valid to point `INSTALLED_APPS` to an `AppConfig` class. How would we feel about hanging the inferred dependencies (the `migrations` and `management/commands` packages) off `apps.py`? Yeah, that makes sense. In practice - unrelated to Pants - Django chokes without `__init__.py`s, as it relies on them for its own inferr-y things, but you're right that app.py is the right place for this. This seems easy enough to prototype. I'll have a go over the next day or three. On Wed, 29 Nov 2023, 15:00 Benjy Weinberger, ***@***.***> wrote: > String imports should already get us an inferred dep from settings.py to > the package containing an app. But that just turns into a dep on that > package's __init__.py, which is typically empty. > > So the question in my mind is: do we want to 1) infer a dep from > settings.py on the migrations inside that package, or 2) infer a dep from > an app package's __init__.py onto various things inside its package (in > this case, migrations). > > The latter seems "correct" in the sense that this is probably what you > mean when you list an app in settings.py. You're not saying "depend on this > app's migrations", you're saying "depend on ~everything in this app". Doing > fine-grained deps on slivers of code inside apps may be incompatible with > Django's whole thing. > > I'm not at all sure what the right answer is. > > — > Reply to this email directly, view it on GitHub > <https://github.com/pantsbuild/pants/issues/20246#issuecomment-1832835952>, > or unsubscribe > <https://github.com/notifications/unsubscribe-auth/AAEX5XCMUJWJJQBJNULBXHDYG65BTAVCNFSM6AAAAAA775KRV2VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQMZSHAZTKOJVGI> > . > You are receiving this because you authored the thread.Message ID: > ***@***.***> > Another idea could be to depend on the owning primary target of `__init__.py` instead. In our django project at $-work, we don't have `app.py` we have `apps.py`. Also, I think it makes sense to depend on all top-level modules in the app, as have been pointed out already, Django won't work well with a subset of those any way. What I mean with "primary owning target" is that if we look up `__init__.py` and find it is owned by a `python_source` target that has been generated from a `python_sources` target, the target generator would be the primary target in this case. If we depend on that, we'll depend on all files that is picked up by the sources field of the `python_sources` target and don't need worry about what files are present and not nor what they're called. And if some project needs/wants some file(s) to be excluded from this inferred dependency you can split them up into multiple targets, and only have the ones you do want together with the `__init__.py` one. Does this make sense to you? > In our django project at $-work, we don't have `app.py` we have `apps.py` yup, `apps.py` is the standard. The trick is that at the moment, there's no transitive dependency to the `migrations` or `management.commands` subpackages, and I'm not sure how depending on the `__init__.py` at the same level as `apps.py` would help with that. My current approach, which I'm going to try out in an internal plugin, is going to be to use the existing `app_detector.py` script to output the package names that the `apps.py` file depends on, and then see if we can resolve known subpackages of each of those package names arising from `AppConfig`. I think that'll work OK in my case, and it should be a matter of expanding from there. yea, incremental progress is likely the only viable way here.. I have an internal plugin that will find all migrations in the same directory as an `__init__.py` file in a `migrations` (also a `management.commands`) subpackage of a package declared in an `AppConfig` class. I'll tidy it up for external use later today.
2023-11-30T23:02:13
pantsbuild/pants
20,253
pantsbuild__pants-20253
[ "20229" ]
3c02f8d22d94b404a990e646d184f19584d0d368
diff --git a/src/python/pants/jvm/package/deploy_jar.py b/src/python/pants/jvm/package/deploy_jar.py --- a/src/python/pants/jvm/package/deploy_jar.py +++ b/src/python/pants/jvm/package/deploy_jar.py @@ -155,6 +155,8 @@ async def package_deploy_jar( ), ) + jar_digest = await Get(Digest, AddPrefix(jar_digest, str(output_filename.parent))) + # # 4. Apply shading rules # @@ -170,9 +172,8 @@ async def package_deploy_jar( ) jar_digest = shaded_jar.digest - prefixed_output_digest = await Get(Digest, AddPrefix(jar_digest, str(output_filename.parent))) artifact = BuiltPackageArtifact(relpath=str(output_filename)) - return BuiltPackage(digest=prefixed_output_digest, artifacts=(artifact,)) + return BuiltPackage(digest=jar_digest, artifacts=(artifact,)) def rules():
diff --git a/src/python/pants/jvm/package/deploy_jar_test.py b/src/python/pants/jvm/package/deploy_jar_test.py --- a/src/python/pants/jvm/package/deploy_jar_test.py +++ b/src/python/pants/jvm/package/deploy_jar_test.py @@ -15,6 +15,7 @@ from pants.build_graph.address import Address from pants.core.goals.package import BuiltPackage from pants.core.util_rules.system_binaries import BashBinary, UnzipBinary +from pants.engine.fs import Snapshot from pants.engine.process import Process, ProcessResult from pants.jvm import jdk_rules from pants.jvm.classpath import rules as classpath_rules @@ -420,6 +421,52 @@ def test_deploy_jar_shaded(rule_runner: RuleRunner) -> None: _deploy_jar_test(rule_runner, "example_app_deploy_jar") +@maybe_skip_jdk_test +def test_deploy_jar_shaded_in_subdir(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "subdir/BUILD": dedent( + """\ + deploy_jar( + name="example_app_deploy_jar", + main="org.pantsbuild.example.Example", + output_path="subdir/dave.jar", + dependencies=[ + ":example", + ], + shading_rules=[ + shading_rename( + pattern="com.fasterxml.jackson.core.**", + replacement="jackson.core.@1", + ) + ] + ) + + java_sources( + name="example", + sources=["**/*.java", ], + dependencies=[ + ":com.fasterxml.jackson.core_jackson-databind", + ], + ) + + jvm_artifact( + name = "com.fasterxml.jackson.core_jackson-databind", + group = "com.fasterxml.jackson.core", + artifact = "jackson-databind", + version = "2.12.5", + ) + """ + ), + "3rdparty/jvm/default.lock": COURSIER_LOCKFILE_SOURCE, + "subdir/Example.java": JAVA_MAIN_SOURCE, + "subdir/lib/ExampleLib.java": JAVA_JSON_MANGLING_LIB_SOURCE, + } + ) + + _deploy_jar_test(rule_runner, "example_app_deploy_jar", path="subdir") + + @maybe_skip_jdk_test def test_deploy_jar_reproducible(rule_runner: RuleRunner) -> None: rule_runner.set_options(args=["--jvm-reproducible-jars"], env_inherit=PYTHON_BOOTSTRAP_ENV) @@ -475,23 +522,28 @@ def test_deploy_jar_reproducible(rule_runner: RuleRunner) -> None: def _deploy_jar_test( - rule_runner: RuleRunner, target_name: str, args: Iterable[str] | None = None + rule_runner: RuleRunner, + target_name: str, + args: Iterable[str] | None = None, + path: str = "", ) -> None: rule_runner.set_options(args=(args or ()), env_inherit=PYTHON_BOOTSTRAP_ENV) - tgt = rule_runner.get_target(Address("", target_name=target_name)) + tgt = rule_runner.get_target(Address(path, target_name=target_name)) jdk = rule_runner.request(InternalJdk, []) fat_jar = rule_runner.request( BuiltPackage, [DeployJarFieldSet.create(tgt)], ) + digest_files = rule_runner.request(Snapshot, [fat_jar.digest]).files + assert len(digest_files) == 1 process_result = rule_runner.request( ProcessResult, [ JvmProcess( jdk=jdk, - argv=("-jar", "dave.jar"), + argv=("-jar", digest_files[0]), classpath_entries=[], description="Run that test jar", input_digest=fat_jar.digest,
Shading throws `NoSuchFileException` given a `deploy_jar` in a subdirectory **Describe the bug** Given a `deploy_jar` target in a subdirectory shading process throws an exception `NoSuchFileException` **Pants version** 2.18.0 **OS** Ubuntu 22.04 **Additional info** `helloworld/HelloWorld.java`: ```java package helloworld; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` `helloworld/BUILD`: ```python java_sources(name="src") ``` `subdir/BUILD`: ```python deploy_jar( name="fat", main="helloworld.HelloWorld", dependencies=["//helloworld:src"], shading_rules=[ shading_keep(pattern="helloworld.**"), ], ) ``` It's important to put deploy_jar into a subdirectory. It works without errors if you put it into root BUILD file. Steps to reproduce: - pants generate-lockfiles - pants subdir:fat I get this: ``` ProcessExecutionFailure: Process 'Shading JAR subdir/fat.jar' failed with exit code 899. ... java.nio.file.NoSuchFileException: subdir/fat.jar ... ```
2023-12-01T23:02:36
pantsbuild/pants
20,254
pantsbuild__pants-20254
[ "20229" ]
085aee67b0c3db449c2def82cf7775c117116af9
diff --git a/src/python/pants/jvm/package/deploy_jar.py b/src/python/pants/jvm/package/deploy_jar.py --- a/src/python/pants/jvm/package/deploy_jar.py +++ b/src/python/pants/jvm/package/deploy_jar.py @@ -155,6 +155,8 @@ async def package_deploy_jar( ), ) + jar_digest = await Get(Digest, AddPrefix(jar_digest, str(output_filename.parent))) + # # 4. Apply shading rules # @@ -170,9 +172,8 @@ async def package_deploy_jar( ) jar_digest = shaded_jar.digest - prefixed_output_digest = await Get(Digest, AddPrefix(jar_digest, str(output_filename.parent))) artifact = BuiltPackageArtifact(relpath=str(output_filename)) - return BuiltPackage(digest=prefixed_output_digest, artifacts=(artifact,)) + return BuiltPackage(digest=jar_digest, artifacts=(artifact,)) def rules():
diff --git a/src/python/pants/jvm/package/deploy_jar_test.py b/src/python/pants/jvm/package/deploy_jar_test.py --- a/src/python/pants/jvm/package/deploy_jar_test.py +++ b/src/python/pants/jvm/package/deploy_jar_test.py @@ -15,6 +15,7 @@ from pants.build_graph.address import Address from pants.core.goals.package import BuiltPackage from pants.core.util_rules.system_binaries import BashBinary, UnzipBinary +from pants.engine.fs import Snapshot from pants.engine.process import Process, ProcessResult from pants.jvm import jdk_rules from pants.jvm.classpath import rules as classpath_rules @@ -420,6 +421,52 @@ def test_deploy_jar_shaded(rule_runner: RuleRunner) -> None: _deploy_jar_test(rule_runner, "example_app_deploy_jar") +@maybe_skip_jdk_test +def test_deploy_jar_shaded_in_subdir(rule_runner: RuleRunner) -> None: + rule_runner.write_files( + { + "subdir/BUILD": dedent( + """\ + deploy_jar( + name="example_app_deploy_jar", + main="org.pantsbuild.example.Example", + output_path="subdir/dave.jar", + dependencies=[ + ":example", + ], + shading_rules=[ + shading_rename( + pattern="com.fasterxml.jackson.core.**", + replacement="jackson.core.@1", + ) + ] + ) + + java_sources( + name="example", + sources=["**/*.java", ], + dependencies=[ + ":com.fasterxml.jackson.core_jackson-databind", + ], + ) + + jvm_artifact( + name = "com.fasterxml.jackson.core_jackson-databind", + group = "com.fasterxml.jackson.core", + artifact = "jackson-databind", + version = "2.12.5", + ) + """ + ), + "3rdparty/jvm/default.lock": COURSIER_LOCKFILE_SOURCE, + "subdir/Example.java": JAVA_MAIN_SOURCE, + "subdir/lib/ExampleLib.java": JAVA_JSON_MANGLING_LIB_SOURCE, + } + ) + + _deploy_jar_test(rule_runner, "example_app_deploy_jar", path="subdir") + + @maybe_skip_jdk_test def test_deploy_jar_reproducible(rule_runner: RuleRunner) -> None: rule_runner.set_options(args=["--jvm-reproducible-jars"], env_inherit=PYTHON_BOOTSTRAP_ENV) @@ -475,23 +522,28 @@ def test_deploy_jar_reproducible(rule_runner: RuleRunner) -> None: def _deploy_jar_test( - rule_runner: RuleRunner, target_name: str, args: Iterable[str] | None = None + rule_runner: RuleRunner, + target_name: str, + args: Iterable[str] | None = None, + path: str = "", ) -> None: rule_runner.set_options(args=(args or ()), env_inherit=PYTHON_BOOTSTRAP_ENV) - tgt = rule_runner.get_target(Address("", target_name=target_name)) + tgt = rule_runner.get_target(Address(path, target_name=target_name)) jdk = rule_runner.request(InternalJdk, []) fat_jar = rule_runner.request( BuiltPackage, [DeployJarFieldSet.create(tgt)], ) + digest_files = rule_runner.request(Snapshot, [fat_jar.digest]).files + assert len(digest_files) == 1 process_result = rule_runner.request( ProcessResult, [ JvmProcess( jdk=jdk, - argv=("-jar", "dave.jar"), + argv=("-jar", digest_files[0]), classpath_entries=[], description="Run that test jar", input_digest=fat_jar.digest,
Shading throws `NoSuchFileException` given a `deploy_jar` in a subdirectory **Describe the bug** Given a `deploy_jar` target in a subdirectory shading process throws an exception `NoSuchFileException` **Pants version** 2.18.0 **OS** Ubuntu 22.04 **Additional info** `helloworld/HelloWorld.java`: ```java package helloworld; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` `helloworld/BUILD`: ```python java_sources(name="src") ``` `subdir/BUILD`: ```python deploy_jar( name="fat", main="helloworld.HelloWorld", dependencies=["//helloworld:src"], shading_rules=[ shading_keep(pattern="helloworld.**"), ], ) ``` It's important to put deploy_jar into a subdirectory. It works without errors if you put it into root BUILD file. Steps to reproduce: - pants generate-lockfiles - pants subdir:fat I get this: ``` ProcessExecutionFailure: Process 'Shading JAR subdir/fat.jar' failed with exit code 899. ... java.nio.file.NoSuchFileException: subdir/fat.jar ... ```
2023-12-01T23:02:37
pantsbuild/pants
20,261
pantsbuild__pants-20261
[ "20024" ]
4741b38dbfe6f15207a48f68d4e6a9c4314a6349
diff --git a/src/python/pants/engine/fs.py b/src/python/pants/engine/fs.py --- a/src/python/pants/engine/fs.py +++ b/src/python/pants/engine/fs.py @@ -53,6 +53,12 @@ class FileContent: content: bytes is_executable: bool = False + def __post_init__(self): + if not isinstance(self.content, bytes): + raise TypeError( + f"Expected 'content' to be bytes, but got {type(self.content).__name__}" + ) + def __repr__(self) -> str: return ( f"FileContent(path={self.path}, content=(len:{len(self.content)}), "
diff --git a/src/python/pants/engine/fs_test.py b/src/python/pants/engine/fs_test.py --- a/src/python/pants/engine/fs_test.py +++ b/src/python/pants/engine/fs_test.py @@ -142,6 +142,18 @@ def try_with_backoff(assertion_fn: Callable[[], bool], count: int = 4) -> bool: return False +# ----------------------------------------------------------------------------------------------- +# `FileContent` +# ----------------------------------------------------------------------------------------------- + + +def test_file_content_non_bytes(): + with pytest.raises(TypeError) as exc: + FileContent(path="4.txt", content="four") + + assert str(exc.value) == "Expected 'content' to be bytes, but got str" + + # ----------------------------------------------------------------------------------------------- # `PathGlobs`, including `GlobMatchErrorBehavior` and symlink handling # -----------------------------------------------------------------------------------------------
Type error on FileContent results in infinite loop **Describe the bug** I'm working on a custom plugin and I did this: ``` content = FileContent(path=versions_file_path, content="some string") digest = await Get(Digest, CreateDigest([content])) ``` That resulted in the infamous `Filesystem changed during run: retrying 'MyGoal'` infinite loop. I was really confused. Upon further inspection of the run logs, I found this: ``` 09:14:56.95 [31m[ERROR][0m panic at 'called `Result::unwrap()` on an `Err` value: "Field `content` was not convertible to type alloc::vec::Vec<u8>: PyErr { type: <class 'TypeError'>, value: TypeError(\"'str' object cannot be interpreted as an integer\"), traceback: None }"', src/intrinsics.rs:422 ``` So I updated the code above to call `.encode()` on the string before passing it as content and things started working. However, I feel like my mistake should have resulted in an error / failure instead of the infinite `Filesystem changed` loop as this just made things harder to debug. **Pants version** 2.16.0 **OS** MacOS **Additional info** I like pants
Good catch @hopper-signifyd . We'd welcome a PR to detect the wrong arg type in the FileContent ctor and error sensibly.
2023-12-04T16:11:06
pantsbuild/pants
20,267
pantsbuild__pants-20267
[ "15651" ]
214e939bb909056d38b465c8a10564a61cc27356
diff --git a/src/python/pants/backend/scala/bsp/rules.py b/src/python/pants/backend/scala/bsp/rules.py --- a/src/python/pants/backend/scala/bsp/rules.py +++ b/src/python/pants/backend/scala/bsp/rules.py @@ -19,7 +19,14 @@ ScalaTestClassesParams, ScalaTestClassesResult, ) +from pants.backend.scala.compile.scalac_plugins import ( + ScalaPlugins, + ScalaPluginsForTargetRequest, + ScalaPluginsRequest, + ScalaPluginTargetsForTarget, +) from pants.backend.scala.subsystems.scala import ScalaSubsystem +from pants.backend.scala.subsystems.scalac import Scalac from pants.backend.scala.target_types import ScalaFieldSet, ScalaSourceField from pants.backend.scala.util_rules.versions import ( ScalaArtifactsForVersionRequest, @@ -334,9 +341,7 @@ class HandleScalacOptionsResult: @_uncacheable_rule async def handle_bsp_scalac_options_request( - request: HandleScalacOptionsRequest, - build_root: BuildRoot, - workspace: Workspace, + request: HandleScalacOptionsRequest, build_root: BuildRoot, workspace: Workspace, scalac: Scalac ) -> HandleScalacOptionsResult: targets = await Get(Targets, BuildTargetIdentifier, request.bsp_target_id) thirdparty_modules = await Get( @@ -344,15 +349,30 @@ async def handle_bsp_scalac_options_request( ) resolve = thirdparty_modules.resolve - resolve_digest = await Get( - Digest, AddPrefix(thirdparty_modules.merged_digest, f"jvm/resolves/{resolve.name}/lib") + scalac_plugin_targets = await MultiGet( + Get(ScalaPluginTargetsForTarget, ScalaPluginsForTargetRequest(tgt, resolve.name)) + for tgt in targets + ) + + local_plugins_prefix = f"jvm/resolves/{resolve.name}/plugins" + local_plugins = await Get( + ScalaPlugins, ScalaPluginsRequest.from_target_plugins(scalac_plugin_targets, resolve) + ) + + thirdparty_modules_prefix = f"jvm/resolves/{resolve.name}/lib" + thirdparty_modules_digest, local_plugins_digest = await MultiGet( + Get(Digest, AddPrefix(thirdparty_modules.merged_digest, thirdparty_modules_prefix)), + Get(Digest, AddPrefix(local_plugins.classpath.digest, local_plugins_prefix)), ) + resolve_digest = await Get( + Digest, MergeDigests([thirdparty_modules_digest, local_plugins_digest]) + ) workspace.write_digest(resolve_digest, path_prefix=".pants.d/bsp") classpath = tuple( build_root.pathlib_path.joinpath( - f".pants.d/bsp/jvm/resolves/{resolve.name}/lib/{filename}" + f".pants.d/bsp/{thirdparty_modules_prefix}/{filename}" ).as_uri() for cp_entry in thirdparty_modules.entries.values() for filename in cp_entry.filenames @@ -361,7 +381,7 @@ async def handle_bsp_scalac_options_request( return HandleScalacOptionsResult( ScalacOptionsItem( target=request.bsp_target_id, - options=(), + options=(*local_plugins.args(local_plugins_prefix), *scalac.args), classpath=classpath, class_directory=build_root.pathlib_path.joinpath( f".pants.d/bsp/{jvm_classes_directory(request.bsp_target_id)}"
BSP: Ensure that Scala compiler plugins are detected by the frontend Currently, we do not expose any of `scalac`'s arguments via the `buildTarget/scalacOptions` message: https://github.com/pantsbuild/pants/blob/be411561c0ea282c6557854e3519d07a26354b79/src/python/pants/backend/scala/bsp/rules.py#L377 It's likely (although I'm [attempting to confirm upstream](https://discord.com/channels/931170831139217469/931171260824707072/979125460275458119)), that correctly exposing the arguments (including plugin instantion arguments: [computed here](https://github.com/pantsbuild/pants/blob/be411561c0ea282c6557854e3519d07a26354b79/src/python/pants/backend/scala/compile/scalac.py#L180-L188)) would be sufficient for this detection.
2023-12-06T09:51:39
pantsbuild/pants
20,271
pantsbuild__pants-20271
[ "20260" ]
21005f2ba5f0c6e799db7aa01cbb0ee984c42ca9
diff --git a/src/python/pants/jvm/jdk_rules.py b/src/python/pants/jvm/jdk_rules.py --- a/src/python/pants/jvm/jdk_rules.py +++ b/src/python/pants/jvm/jdk_rules.py @@ -214,19 +214,24 @@ async def prepare_jdk_environment( if version is DefaultJdk.SYSTEM: coursier_jdk_option = "--system-jvm" else: - coursier_jdk_option = shlex.quote(f"--jvm={version}") + coursier_jdk_option = f"--jvm={version}" + + if not coursier.jvm_index: + coursier_options = ["java-home", coursier_jdk_option] + else: + jvm_index_option = f"--jvm-index={coursier.jvm_index}" + coursier_options = ["java-home", jvm_index_option, coursier_jdk_option] # TODO(#16104) This argument re-writing code should use the native {chroot} support. # See also `run` for other argument re-writing code. def prefixed(arg: str) -> str: + quoted = shlex.quote(arg) if arg.startswith("__"): - return f"${{PANTS_INTERNAL_ABSOLUTE_PREFIX}}{arg}" + return f"${{PANTS_INTERNAL_ABSOLUTE_PREFIX}}{quoted}" else: - return arg + return quoted - optionally_prefixed_coursier_args = [ - prefixed(arg) for arg in coursier.args(["java-home", coursier_jdk_option]) - ] + optionally_prefixed_coursier_args = [prefixed(arg) for arg in coursier.args(coursier_options)] # NB: We `set +e` in the subshell to ensure that it exits as well. # see https://unix.stackexchange.com/a/23099 java_home_command = " ".join(("set +e;", *optionally_prefixed_coursier_args)) diff --git a/src/python/pants/jvm/resolve/coursier_setup.py b/src/python/pants/jvm/resolve/coursier_setup.py --- a/src/python/pants/jvm/resolve/coursier_setup.py +++ b/src/python/pants/jvm/resolve/coursier_setup.py @@ -22,7 +22,7 @@ from pants.engine.platform import Platform from pants.engine.process import Process from pants.engine.rules import Get, MultiGet, collect_rules, rule -from pants.option.option_types import StrListOption +from pants.option.option_types import StrListOption, StrOption from pants.util.frozendict import FrozenDict from pants.util.logging import LogLevel from pants.util.memo import memoized_property @@ -86,7 +86,6 @@ """ ) - # TODO: Coursier renders setrlimit error line on macOS. # see https://github.com/pantsbuild/pants/issues/13942. POST_PROCESS_COURSIER_STDERR_SCRIPT = textwrap.dedent( # noqa: PNT20 @@ -149,12 +148,26 @@ class CoursierSubsystem(TemplatedExternalTool): Maven style repositories to resolve artifacts from. Coursier will resolve these repositories in the order in which they are - specifed, and re-ordering repositories will cause artifacts to be + specified, and re-ordering repositories will cause artifacts to be re-downloaded. This can result in artifacts in lockfiles becoming invalid. """ ), ) + jvm_index = StrOption( + default="", + help=softwrap( + """ + The JVM index to be used by Coursier. + + Possible values are: + - cs: The default JVM index used and maintained by Coursier. + - cs-maven: Fetches a JVM index from the io.get-coursier:jvm-index Maven repository. + - <URL>: An arbitrary URL for a JVM index. Ex. https://url/of/your/index.json + """ + ), + ) + def generate_exe(self, plat: Platform) -> str: tool_version = self.known_version(plat) url = (tool_version and tool_version.url_override) or self.generate_url(plat) @@ -170,6 +183,7 @@ class Coursier: coursier: DownloadedExternalTool _digest: Digest repos: FrozenOrderedSet[str] + jvm_index: str _append_only_caches: FrozenDict[str, str] bin_dir: ClassVar[str] = "__coursier" @@ -314,6 +328,7 @@ async def setup_coursier( ), ), repos=FrozenOrderedSet(coursier_subsystem.repos), + jvm_index=coursier_subsystem.jvm_index, _append_only_caches=python.APPEND_ONLY_CACHES, )
diff --git a/src/python/pants/jvm/jdk_rules_test.py b/src/python/pants/jvm/jdk_rules_test.py --- a/src/python/pants/jvm/jdk_rules_test.py +++ b/src/python/pants/jvm/jdk_rules_test.py @@ -215,3 +215,34 @@ def test_pass_jvm_options_to_java_program(rule_runner: RuleRunner) -> None: assert "java.specification.version=11" in jvm_properties assert "pants.jvm.global=true" in jvm_properties assert "pants.jvm.extra=true" in jvm_properties + + +@maybe_skip_jdk_test +def test_jvm_not_found_when_empty_jvm_index(rule_runner: RuleRunner) -> None: + # Prepare empty JVM Index file + filename = "index.json" + file_content = textwrap.dedent( + """\ + {} + """ + ) + rule_runner.write_files({filename: file_content}) + + jdk_release_version = "21" + jdk_binary = f"adoptium:1.{jdk_release_version}" + + # Assert jdk_binary is found with default JVM Index + rule_runner.set_options([f"--jvm-tool-jdk={jdk_binary}"], env_inherit=PYTHON_BOOTSTRAP_ENV) + assert f'openjdk version "{jdk_release_version}' in run_javac_version(rule_runner) + + # Assert jdk_binary is not found with empty JVM Index + rule_runner.set_options( + [ + f"--coursier-jvm-index={rule_runner.build_root}/{filename}", + f"--jvm-tool-jdk={jdk_binary}", + ], + env_inherit=PYTHON_BOOTSTRAP_ENV, + ) + expected_exception_msg = rf".*?JVM {jdk_binary} not found in index.*?" + with pytest.raises(ExecutionError, match=expected_exception_msg): + run_javac_version(rule_runner)
Failure to Prepare JDK Environment Behind Proxy **Describe the bug** Commands on Scala targets that require a JDK, such as `pants check ::` and `pants lint ::`, fail when the JVM index used by Coursier is unavailable. **Pants version** 2.18.0 **OS** Linux **Additional info** The following is a sample of the output from a server running behind a proxy, and therefore unable to reach the JVM index used by Coursier: ``` pants --changed-since=### lint 86.22s Ensure download of JDK --jvm=zulu:8.0.372. [INFO] Long running tasks: 79.06s Run `scalafmt` on 73 files. 79.06s Run `scalafmt` on 18 files. 79.06s Run `scalafmt` on 5 files. [INFO] Long running tasks: 109.15s Run `scalafmt` on 73 files. 109.15s Run `scalafmt` on 18 files. 109.15s Run `scalafmt` on 5 files. [ERROR] 1 Exception encountered: Engine traceback: in `lint` goal ProcessExecutionFailure: Process 'Run `scalafmt` on 5 files.' failed with exit code 1. stdout: stderr: Downloading https://github.com/coursier/jvm-index/raw/master/index.json Downloaded https://github.com/coursier/jvm-index/raw/master/index.json Exception in thread "main" java.lang.Exception: Error while getting https://github.com/coursier/jvm-index/raw/master/index.json: download error: Caught java.net.ConnectException (Connection timed out) while downloading https://github.com/coursier/jvm-index/raw/master/index.json at coursier.jvm.JvmIndex$.$anonfun$load$5(JvmIndex.scala:142) at coursier.jvm.JvmIndex$.$anonfun$load$5$adapted(JvmIndex.scala:140) at coursier.util.Task$.$anonfun$flatMap$extension$1(Task.scala:14) at coursier.util.Task$.$anonfun$flatMap$extension$1$adapted(Task.scala:14) at coursier.util.Task$.wrap(Task.scala:82) at coursier.util.Task$.$anonfun$flatMap$2(Task.scala:14) at scala.concurrent.Future.$anonfun$flatMap$1(Future.scala:307) at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:41) at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:64) at [email protected]/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) at [email protected]/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) at [email protected]/java.lang.Thread.run(Thread.java:833) at com.oracle.svm.core.thread.PlatformThreads.threadStartRoutine(PlatformThreads.java:775) at com.oracle.svm.core.posix.thread.PosixPlatformThreads.pthreadStartRoutine(PosixPlatformThreads.java:203) ```
I would like to try resolving this by adding the ability to pass a `jvm-index` argument to Coursier from Pants. The Coursier argument is described here https://get-coursier.io/docs/cli-java#jvm-index. That seems like a reasonable approach.
2023-12-08T07:04:42
pantsbuild/pants
20,276
pantsbuild__pants-20276
[ "20275" ]
3b90d9ea1f9e1987ed0655b32edacdb9dd223eb6
diff --git a/src/python/pants/backend/terraform/utils.py b/src/python/pants/backend/terraform/utils.py --- a/src/python/pants/backend/terraform/utils.py +++ b/src/python/pants/backend/terraform/utils.py @@ -1,7 +1,7 @@ # Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). +import os.path import shlex -from pathlib import PurePath def terraform_arg(name: str, value: str) -> str: @@ -11,4 +11,4 @@ def terraform_arg(name: str, value: str) -> str: def terraform_relpath(chdir: str, target: str) -> str: """Compute the relative path of a target file to the Terraform deployment root.""" - return PurePath(target).relative_to(chdir).as_posix() + return os.path.relpath(target, start=chdir)
diff --git a/src/python/pants/backend/terraform/utils_test.py b/src/python/pants/backend/terraform/utils_test.py new file mode 100644 --- /dev/null +++ b/src/python/pants/backend/terraform/utils_test.py @@ -0,0 +1,39 @@ +# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). +import pytest + +from pants.backend.terraform.utils import terraform_relpath + + [email protected]( + "chdir, target, expected_result", + [ + pytest.param( + "path/to/deployment", + "path/to/deployment/file.txt", + "file.txt", + id="file_in_same_directory", + ), + pytest.param( + "path/to/deployment", + "path/to/other/file.txt", + "../other/file.txt", + id="file_in_different_directory", + ), + pytest.param( + "path/to/deployment", + "path/to/deployment/subdir/file.txt", + "subdir/file.txt", + id="file_in_subdirectory", + ), + pytest.param( + "path/to/deployment/subdir", + "path/to/deployment/file.txt", + "../file.txt", + id="file_in_parent_directory", + ), + ], +) +def test_terraform_relpath(chdir: str, target: str, expected_result: str): + result = terraform_relpath(chdir, target) + assert result == expected_result
`terraform_deployment` cannot load vars files if the root `terraform_module` is not in the same dir **Describe the bug** root/BUILD: ``` terraform_deployment(root_module="//mod0:mod0", var_files=["a.tfvars"]) ``` root/a.tfvars: ``` var0 = "hihello" ``` mod/BUILD: ``` terraform_module() ``` mod/main.tf: ``` resource "null_resource" "dep" {} ``` running `pants experimental-deploy //root:root` yields: ``` Engine traceback: in select .. in pants.core.goals.deploy.run_deploy `experimental-deploy` goal Traceback (most recent call last): File "/home/lilatomic/vnd/pants/src/python/pants/core/goals/deploy.py", line 176, in run_deploy deploy_processes = await MultiGet( File "/home/lilatomic/vnd/pants/src/python/pants/engine/internals/selectors.py", line 374, in MultiGet return await _MultiGet(tuple(__arg0)) File "/home/lilatomic/vnd/pants/src/python/pants/engine/internals/selectors.py", line 172, in __await__ result = yield self.gets ValueError: 'root/a.tfvars' is not in the subpath of 'mod0' OR one path is relative and the other is absolute. ``` **Pants version** 2.18+
problem is in `terraform_relpath`. The idea is that the dir in the root module is the value of the argument `chdir` to Terraform. This effectively changes Terraforms cwd, which means that we have to find the relative path to the var_file. In the example above, we want to synthesise the Terraform invocation: `terraform -chdir=mod0/ apply -var-file=../root/a.tfvars`. Turns out `PurePath(target).relative_to(chdir)` doesn't do that if they're not in the subpath.
2023-12-09T23:56:27
pantsbuild/pants
20,300
pantsbuild__pants-20300
[ "20275" ]
8486d3605e78ba7797b58eafc124af63d4d967a7
diff --git a/src/python/pants/backend/terraform/utils.py b/src/python/pants/backend/terraform/utils.py --- a/src/python/pants/backend/terraform/utils.py +++ b/src/python/pants/backend/terraform/utils.py @@ -1,7 +1,7 @@ # Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). +import os.path import shlex -from pathlib import PurePath def terraform_arg(name: str, value: str) -> str: @@ -11,4 +11,4 @@ def terraform_arg(name: str, value: str) -> str: def terraform_relpath(chdir: str, target: str) -> str: """Compute the relative path of a target file to the Terraform deployment root.""" - return PurePath(target).relative_to(chdir).as_posix() + return os.path.relpath(target, start=chdir)
diff --git a/src/python/pants/backend/terraform/utils_test.py b/src/python/pants/backend/terraform/utils_test.py new file mode 100644 --- /dev/null +++ b/src/python/pants/backend/terraform/utils_test.py @@ -0,0 +1,39 @@ +# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). +import pytest + +from pants.backend.terraform.utils import terraform_relpath + + [email protected]( + "chdir, target, expected_result", + [ + pytest.param( + "path/to/deployment", + "path/to/deployment/file.txt", + "file.txt", + id="file_in_same_directory", + ), + pytest.param( + "path/to/deployment", + "path/to/other/file.txt", + "../other/file.txt", + id="file_in_different_directory", + ), + pytest.param( + "path/to/deployment", + "path/to/deployment/subdir/file.txt", + "subdir/file.txt", + id="file_in_subdirectory", + ), + pytest.param( + "path/to/deployment/subdir", + "path/to/deployment/file.txt", + "../file.txt", + id="file_in_parent_directory", + ), + ], +) +def test_terraform_relpath(chdir: str, target: str, expected_result: str): + result = terraform_relpath(chdir, target) + assert result == expected_result
`terraform_deployment` cannot load vars files if the root `terraform_module` is not in the same dir **Describe the bug** root/BUILD: ``` terraform_deployment(root_module="//mod0:mod0", var_files=["a.tfvars"]) ``` root/a.tfvars: ``` var0 = "hihello" ``` mod/BUILD: ``` terraform_module() ``` mod/main.tf: ``` resource "null_resource" "dep" {} ``` running `pants experimental-deploy //root:root` yields: ``` Engine traceback: in select .. in pants.core.goals.deploy.run_deploy `experimental-deploy` goal Traceback (most recent call last): File "/home/lilatomic/vnd/pants/src/python/pants/core/goals/deploy.py", line 176, in run_deploy deploy_processes = await MultiGet( File "/home/lilatomic/vnd/pants/src/python/pants/engine/internals/selectors.py", line 374, in MultiGet return await _MultiGet(tuple(__arg0)) File "/home/lilatomic/vnd/pants/src/python/pants/engine/internals/selectors.py", line 172, in __await__ result = yield self.gets ValueError: 'root/a.tfvars' is not in the subpath of 'mod0' OR one path is relative and the other is absolute. ``` **Pants version** 2.18+
problem is in `terraform_relpath`. The idea is that the dir in the root module is the value of the argument `chdir` to Terraform. This effectively changes Terraforms cwd, which means that we have to find the relative path to the var_file. In the example above, we want to synthesise the Terraform invocation: `terraform -chdir=mod0/ apply -var-file=../root/a.tfvars`. Turns out `PurePath(target).relative_to(chdir)` doesn't do that if they're not in the subpath.
2023-12-17T02:46:06
pantsbuild/pants
20,301
pantsbuild__pants-20301
[ "20275" ]
745258b9da6705e2965e45f9360d2e2a914005f5
diff --git a/src/python/pants/backend/terraform/utils.py b/src/python/pants/backend/terraform/utils.py --- a/src/python/pants/backend/terraform/utils.py +++ b/src/python/pants/backend/terraform/utils.py @@ -1,7 +1,7 @@ # Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). +import os.path import shlex -from pathlib import PurePath def terraform_arg(name: str, value: str) -> str: @@ -11,4 +11,4 @@ def terraform_arg(name: str, value: str) -> str: def terraform_relpath(chdir: str, target: str) -> str: """Compute the relative path of a target file to the Terraform deployment root.""" - return PurePath(target).relative_to(chdir).as_posix() + return os.path.relpath(target, start=chdir)
diff --git a/src/python/pants/backend/terraform/utils_test.py b/src/python/pants/backend/terraform/utils_test.py new file mode 100644 --- /dev/null +++ b/src/python/pants/backend/terraform/utils_test.py @@ -0,0 +1,39 @@ +# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). +import pytest + +from pants.backend.terraform.utils import terraform_relpath + + [email protected]( + "chdir, target, expected_result", + [ + pytest.param( + "path/to/deployment", + "path/to/deployment/file.txt", + "file.txt", + id="file_in_same_directory", + ), + pytest.param( + "path/to/deployment", + "path/to/other/file.txt", + "../other/file.txt", + id="file_in_different_directory", + ), + pytest.param( + "path/to/deployment", + "path/to/deployment/subdir/file.txt", + "subdir/file.txt", + id="file_in_subdirectory", + ), + pytest.param( + "path/to/deployment/subdir", + "path/to/deployment/file.txt", + "../file.txt", + id="file_in_parent_directory", + ), + ], +) +def test_terraform_relpath(chdir: str, target: str, expected_result: str): + result = terraform_relpath(chdir, target) + assert result == expected_result
`terraform_deployment` cannot load vars files if the root `terraform_module` is not in the same dir **Describe the bug** root/BUILD: ``` terraform_deployment(root_module="//mod0:mod0", var_files=["a.tfvars"]) ``` root/a.tfvars: ``` var0 = "hihello" ``` mod/BUILD: ``` terraform_module() ``` mod/main.tf: ``` resource "null_resource" "dep" {} ``` running `pants experimental-deploy //root:root` yields: ``` Engine traceback: in select .. in pants.core.goals.deploy.run_deploy `experimental-deploy` goal Traceback (most recent call last): File "/home/lilatomic/vnd/pants/src/python/pants/core/goals/deploy.py", line 176, in run_deploy deploy_processes = await MultiGet( File "/home/lilatomic/vnd/pants/src/python/pants/engine/internals/selectors.py", line 374, in MultiGet return await _MultiGet(tuple(__arg0)) File "/home/lilatomic/vnd/pants/src/python/pants/engine/internals/selectors.py", line 172, in __await__ result = yield self.gets ValueError: 'root/a.tfvars' is not in the subpath of 'mod0' OR one path is relative and the other is absolute. ``` **Pants version** 2.18+
problem is in `terraform_relpath`. The idea is that the dir in the root module is the value of the argument `chdir` to Terraform. This effectively changes Terraforms cwd, which means that we have to find the relative path to the var_file. In the example above, we want to synthesise the Terraform invocation: `terraform -chdir=mod0/ apply -var-file=../root/a.tfvars`. Turns out `PurePath(target).relative_to(chdir)` doesn't do that if they're not in the subpath.
2023-12-17T02:46:08
pantsbuild/pants
20,314
pantsbuild__pants-20314
[ "20313" ]
78775b9716f93609a599d9efd17e169e574f17f2
diff --git a/src/python/pants/core/util_rules/adhoc_binaries.py b/src/python/pants/core/util_rules/adhoc_binaries.py --- a/src/python/pants/core/util_rules/adhoc_binaries.py +++ b/src/python/pants/core/util_rules/adhoc_binaries.py @@ -104,10 +104,11 @@ async def download_python_binary( cp -r python "{installation_root}" touch "{installation_root}/DONE" fi + echo "$(realpath "{installation_root}")/bin/python3" """ ) - await Get( + result = await Get( ProcessResult, Process( [bash_binary.path, "-c", installation_script], @@ -123,7 +124,7 @@ async def download_python_binary( ), ) - return _PythonBuildStandaloneBinary(f"{installation_root}/bin/python3") + return _PythonBuildStandaloneBinary(result.stdout.decode().splitlines()[-1].strip()) @dataclass(frozen=True)
diff --git a/src/python/pants/core/util_rules/adhoc_binaries_test.py b/src/python/pants/core/util_rules/adhoc_binaries_test.py --- a/src/python/pants/core/util_rules/adhoc_binaries_test.py +++ b/src/python/pants/core/util_rules/adhoc_binaries_test.py @@ -6,14 +6,17 @@ import pytest from pants.build_graph.address import Address -from pants.core.target_types import FileTarget from pants.core.util_rules import adhoc_binaries from pants.core.util_rules.adhoc_binaries import ( - PythonBuildStandaloneBinary, _DownloadPythonBuildStandaloneBinaryRequest, _PythonBuildStandaloneBinary, ) -from pants.core.util_rules.environments import EnvironmentTarget, LocalEnvironmentTarget +from pants.core.util_rules.environments import ( + DockerEnvironmentTarget, + EnvironmentTarget, + LocalEnvironmentTarget, +) +from pants.engine.environment import EnvironmentName from pants.testutil.rule_runner import MockGet, QueryRule, RuleRunner, run_rule_with_mocks @@ -27,7 +30,7 @@ def rule_runner() -> RuleRunner: [_DownloadPythonBuildStandaloneBinaryRequest], ), ], - target_types=[LocalEnvironmentTarget, FileTarget], + target_types=[LocalEnvironmentTarget, DockerEnvironmentTarget], ) @@ -47,32 +50,29 @@ def test_local(env_tgt) -> None: assert result == adhoc_binaries.PythonBuildStandaloneBinary(sys.executable) -def test_docker_uses_helper() -> None: - result = run_rule_with_mocks( - adhoc_binaries.get_python_for_scripts, - rule_args=[EnvironmentTarget("docker", FileTarget({"source": ""}, address=Address("")))], - mock_gets=[ - MockGet( - output_type=_PythonBuildStandaloneBinary, - input_types=(_DownloadPythonBuildStandaloneBinaryRequest,), - mock=lambda _: _PythonBuildStandaloneBinary(""), - ) +def test_docker_uses_helper(rule_runner: RuleRunner) -> None: + rule_runner = RuleRunner( + rules=[ + *adhoc_binaries.rules(), + QueryRule( + _PythonBuildStandaloneBinary, + [_DownloadPythonBuildStandaloneBinaryRequest], + ), ], + target_types=[DockerEnvironmentTarget], + inherent_environment=EnvironmentName("docker"), ) - assert result == PythonBuildStandaloneBinary("") - - -def test_docker_helper(rule_runner: RuleRunner): rule_runner.write_files( { - "BUILD": "local_environment(name='local')", + "BUILD": "docker_environment(name='docker', image='ubuntu:latest')", } ) rule_runner.set_options( - ["--environments-preview-names={'local': '//:local'}"], env_inherit={"PATH"} + ["--environments-preview-names={'docker': '//:docker'}"], env_inherit={"PATH"} ) pbs = rule_runner.request( _PythonBuildStandaloneBinary, [_DownloadPythonBuildStandaloneBinaryRequest()], ) - assert not pbs.path.startswith("/") + assert pbs.path.startswith("/pants-named-caches") + assert pbs.path.endswith("/bin/python3")
Pants-provided-Python for Pex CLI doesn't work in docker environments **Describe the bug** Trying to use docker_environment to run a test on a machine without Python installed will result in an error: ``` Failed to find a compatible PEX_PYTHON=.python-build-standalone/c12164f0e9228ec20704c1aba97eb31b8e2a482d41943d541cc8e3a9e84f7349/bin/python3. No interpreters could be found on the system. ``` **Pants version** 2.20 **OS** Linux host and linux container **Additional info**
2023-12-19T16:32:48
pantsbuild/pants
20,339
pantsbuild__pants-20339
[ "20313" ]
1fc3179fa6353017d57dfa218a07724cb5672a21
diff --git a/src/python/pants/core/util_rules/adhoc_binaries.py b/src/python/pants/core/util_rules/adhoc_binaries.py --- a/src/python/pants/core/util_rules/adhoc_binaries.py +++ b/src/python/pants/core/util_rules/adhoc_binaries.py @@ -104,10 +104,11 @@ async def download_python_binary( cp -r python "{installation_root}" touch "{installation_root}/DONE" fi + echo "$(realpath "{installation_root}")/bin/python3" """ ) - await Get( + result = await Get( ProcessResult, Process( [bash_binary.path, "-c", installation_script], @@ -123,7 +124,7 @@ async def download_python_binary( ), ) - return _PythonBuildStandaloneBinary(f"{installation_root}/bin/python3") + return _PythonBuildStandaloneBinary(result.stdout.decode().splitlines()[-1].strip()) @dataclass(frozen=True)
diff --git a/src/python/pants/core/util_rules/adhoc_binaries_test.py b/src/python/pants/core/util_rules/adhoc_binaries_test.py --- a/src/python/pants/core/util_rules/adhoc_binaries_test.py +++ b/src/python/pants/core/util_rules/adhoc_binaries_test.py @@ -6,14 +6,17 @@ import pytest from pants.build_graph.address import Address -from pants.core.target_types import FileTarget from pants.core.util_rules import adhoc_binaries from pants.core.util_rules.adhoc_binaries import ( - PythonBuildStandaloneBinary, _DownloadPythonBuildStandaloneBinaryRequest, _PythonBuildStandaloneBinary, ) -from pants.core.util_rules.environments import EnvironmentTarget, LocalEnvironmentTarget +from pants.core.util_rules.environments import ( + DockerEnvironmentTarget, + EnvironmentTarget, + LocalEnvironmentTarget, +) +from pants.engine.environment import EnvironmentName from pants.testutil.rule_runner import MockGet, QueryRule, RuleRunner, run_rule_with_mocks @@ -27,7 +30,7 @@ def rule_runner() -> RuleRunner: [_DownloadPythonBuildStandaloneBinaryRequest], ), ], - target_types=[LocalEnvironmentTarget, FileTarget], + target_types=[LocalEnvironmentTarget, DockerEnvironmentTarget], ) @@ -47,32 +50,29 @@ def test_local(env_tgt) -> None: assert result == adhoc_binaries.PythonBuildStandaloneBinary(sys.executable) -def test_docker_uses_helper() -> None: - result = run_rule_with_mocks( - adhoc_binaries.get_python_for_scripts, - rule_args=[EnvironmentTarget("docker", FileTarget({"source": ""}, address=Address("")))], - mock_gets=[ - MockGet( - output_type=_PythonBuildStandaloneBinary, - input_types=(_DownloadPythonBuildStandaloneBinaryRequest,), - mock=lambda _: _PythonBuildStandaloneBinary(""), - ) +def test_docker_uses_helper(rule_runner: RuleRunner) -> None: + rule_runner = RuleRunner( + rules=[ + *adhoc_binaries.rules(), + QueryRule( + _PythonBuildStandaloneBinary, + [_DownloadPythonBuildStandaloneBinaryRequest], + ), ], + target_types=[DockerEnvironmentTarget], + inherent_environment=EnvironmentName("docker"), ) - assert result == PythonBuildStandaloneBinary("") - - -def test_docker_helper(rule_runner: RuleRunner): rule_runner.write_files( { - "BUILD": "local_environment(name='local')", + "BUILD": "docker_environment(name='docker', image='ubuntu:latest')", } ) rule_runner.set_options( - ["--environments-preview-names={'local': '//:local'}"], env_inherit={"PATH"} + ["--environments-preview-names={'docker': '//:docker'}"], env_inherit={"PATH"} ) pbs = rule_runner.request( _PythonBuildStandaloneBinary, [_DownloadPythonBuildStandaloneBinaryRequest()], ) - assert not pbs.path.startswith("/") + assert pbs.path.startswith("/pants-named-caches") + assert pbs.path.endswith("/bin/python3")
Pants-provided-Python for Pex CLI doesn't work in docker environments **Describe the bug** Trying to use docker_environment to run a test on a machine without Python installed will result in an error: ``` Failed to find a compatible PEX_PYTHON=.python-build-standalone/c12164f0e9228ec20704c1aba97eb31b8e2a482d41943d541cc8e3a9e84f7349/bin/python3. No interpreters could be found on the system. ``` **Pants version** 2.20 **OS** Linux host and linux container **Additional info**
2023-12-26T21:03:16
pantsbuild/pants
20,345
pantsbuild__pants-20345
[ "20344" ]
550cc244505953459337504aa5a4cf85f8fff66c
diff --git a/build-support/bin/generate_docs.py b/build-support/bin/generate_docs.py --- a/build-support/bin/generate_docs.py +++ b/build-support/bin/generate_docs.py @@ -35,6 +35,7 @@ from pants.base.build_environment import get_buildroot, get_pants_cachedir from pants.help.help_info_extracter import to_help_str +from pants.option.scope import GLOBAL_SCOPE, GLOBAL_SCOPE_CONFIG_SECTION from pants.util.strutil import softwrap from pants.version import MAJOR_MINOR @@ -333,6 +334,10 @@ def _generate_toml_snippet(option_data, scope) -> str: # This option is not configurable. return "" + if scope == GLOBAL_SCOPE: + # make sure we're rendering with the section name as appears in pants.toml + scope = GLOBAL_SCOPE_CONFIG_SECTION + toml_lines = [] example_cli = option_data["display_args"][0] config_key = option_data["config_key"]
Empty TOML section `[]` in GLOBAL options docs **Describe the bug** The toml suggestion for options in the GLOBAL section end up with `[]` as their TOML section, e.g. https://www.pantsbuild.org/v2.19/docs/reference-global#level <img width="224" alt="image" src="https://github.com/pantsbuild/pants/assets/1203825/97654b4c-eefe-479a-a20b-7f4c664d5c7e"> That should show: ```toml [GLOBAL] level = <LogLevel> ``` **Pants version** 2.19 **OS** N/A **Additional info** #19718
2023-12-28T10:59:52
pantsbuild/pants
20,349
pantsbuild__pants-20349
[ "20313" ]
3f04532c370bf7e437072630ae256d0ff336d94b
diff --git a/src/python/pants/core/util_rules/adhoc_binaries.py b/src/python/pants/core/util_rules/adhoc_binaries.py --- a/src/python/pants/core/util_rules/adhoc_binaries.py +++ b/src/python/pants/core/util_rules/adhoc_binaries.py @@ -104,11 +104,12 @@ async def download_python_binary( cp -r python "{installation_root}" touch "{installation_root}/DONE" fi + echo "$(realpath "{installation_root}")/bin/python3" """ ) env_vars = await Get(EnvironmentVars, EnvironmentVarsRequest(["PATH"])) - await Get( + result = await Get( ProcessResult, Process( [bash.path, "-c", installation_script], @@ -124,7 +125,7 @@ async def download_python_binary( ), ) - return _PythonBuildStandaloneBinary(f"{installation_root}/bin/python3") + return _PythonBuildStandaloneBinary(result.stdout.decode().splitlines()[-1].strip()) @dataclass(frozen=True)
diff --git a/src/python/pants/core/util_rules/adhoc_binaries_test.py b/src/python/pants/core/util_rules/adhoc_binaries_test.py --- a/src/python/pants/core/util_rules/adhoc_binaries_test.py +++ b/src/python/pants/core/util_rules/adhoc_binaries_test.py @@ -6,14 +6,17 @@ import pytest from pants.build_graph.address import Address -from pants.core.target_types import FileTarget from pants.core.util_rules import adhoc_binaries from pants.core.util_rules.adhoc_binaries import ( - PythonBuildStandaloneBinary, _DownloadPythonBuildStandaloneBinaryRequest, _PythonBuildStandaloneBinary, ) -from pants.core.util_rules.environments import EnvironmentTarget, LocalEnvironmentTarget +from pants.core.util_rules.environments import ( + DockerEnvironmentTarget, + EnvironmentTarget, + LocalEnvironmentTarget, +) +from pants.engine.environment import EnvironmentName from pants.testutil.rule_runner import MockGet, QueryRule, RuleRunner, run_rule_with_mocks @@ -27,7 +30,7 @@ def rule_runner() -> RuleRunner: [_DownloadPythonBuildStandaloneBinaryRequest], ), ], - target_types=[LocalEnvironmentTarget, FileTarget], + target_types=[LocalEnvironmentTarget, DockerEnvironmentTarget], ) @@ -47,32 +50,29 @@ def test_local(env_tgt) -> None: assert result == adhoc_binaries.PythonBuildStandaloneBinary(sys.executable) -def test_docker_uses_helper() -> None: - result = run_rule_with_mocks( - adhoc_binaries.get_python_for_scripts, - rule_args=[EnvironmentTarget("docker", FileTarget({"source": ""}, address=Address("")))], - mock_gets=[ - MockGet( - output_type=_PythonBuildStandaloneBinary, - input_types=(_DownloadPythonBuildStandaloneBinaryRequest,), - mock=lambda _: _PythonBuildStandaloneBinary(""), - ) +def test_docker_uses_helper(rule_runner: RuleRunner) -> None: + rule_runner = RuleRunner( + rules=[ + *adhoc_binaries.rules(), + QueryRule( + _PythonBuildStandaloneBinary, + [_DownloadPythonBuildStandaloneBinaryRequest], + ), ], + target_types=[DockerEnvironmentTarget], + inherent_environment=EnvironmentName("docker"), ) - assert result == PythonBuildStandaloneBinary("") - - -def test_docker_helper(rule_runner: RuleRunner): rule_runner.write_files( { - "BUILD": "local_environment(name='local')", + "BUILD": "docker_environment(name='docker', image='ubuntu:latest')", } ) rule_runner.set_options( - ["--environments-preview-names={'local': '//:local'}"], env_inherit={"PATH"} + ["--environments-preview-names={'docker': '//:docker'}"], env_inherit={"PATH"} ) pbs = rule_runner.request( _PythonBuildStandaloneBinary, [_DownloadPythonBuildStandaloneBinaryRequest()], ) - assert not pbs.path.startswith("/") + assert pbs.path.startswith("/pants-named-caches") + assert pbs.path.endswith("/bin/python3")
Pants-provided-Python for Pex CLI doesn't work in docker environments **Describe the bug** Trying to use docker_environment to run a test on a machine without Python installed will result in an error: ``` Failed to find a compatible PEX_PYTHON=.python-build-standalone/c12164f0e9228ec20704c1aba97eb31b8e2a482d41943d541cc8e3a9e84f7349/bin/python3. No interpreters could be found on the system. ``` **Pants version** 2.20 **OS** Linux host and linux container **Additional info**
2023-12-30T12:38:34