### Install and Configure GitHub Actions Runner Service Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/contributions/releases/github-actions-macos-arm64-runners This snippet installs the GitHub Actions runner as a service, ensuring it starts on machine boot. It also sets up required environment variables for the runner, such as the operating system image and Xcode developer directory. ```shell % cd actions-runner # Ensure that the runner starts when the machine starts. % ./svc.sh install # Set up some env vars the runner requires. % echo 'ImageOS=macos11' >> .env % echo "XCODE_11_DEVELOPER_DIR=$(xcode-select -p)" >> .env ``` -------------------------------- ### Example BUILD file with custom source field Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/tutorials/advanced-plugin-concepts Demonstrates how to use a custom 'source' field in a BUILD file, including an example of a non-existing file to trigger error handling. ```python version_file( name="main-project-version", source="non-existing-file", ) ``` -------------------------------- ### Project Structure Example Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/source-roots Demonstrates a typical project directory structure for a Pants build, including source files, tests, and third-party dependencies for Java and Python. ```tree .\n├── 3rdparty\n│ ├── java\n│ │ └── ivy.xml\n│ └── python\n│ └── requirements.txt\n├── src\n│ ├── java\n│ │ └── org\n│ │ └── pantsbuild\n│ │ └── project\n│ │ ├── App.java\n│ │ └── util\n│ │ └── Math.java\n│ └── python\n│ └── project\n│ ├── __init__.py\n│ ├── app.py\n│ ├── config\n│ │ ├── __init__.py\n│ │ └── prod.json\n│ └── util\n│ ├── __init__.py\n│ └── math.py\n└── test\n └── python\n └── project\n ├── __init__.py\n └── util\n ├── __init__.py\n └── test_math.py ``` -------------------------------- ### Install Pants using curl script Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/getting-started/installing-pants This command downloads and executes a script to install the Pants binary. The script installs 'pants' into '~/.local/bin', which should be on your system's PATH. It is recommended to check this script into your repository for CI runs rather than curling it directly on every execution for security reasons. ```bash curl --proto '=https' --tlsv1.2 -fsSL https://static.pantsbuild.org/setup/get-pants.sh | bash ``` -------------------------------- ### Example Project Structure with Marker Files Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/source-roots Demonstrates a project structure where distinct sub-projects ('server' and 'utils') are marked by `setup.py` files. Configuring Pants to use `setup.py` as a marker file will identify these directories as source roots. ```text . ├── server │ ├── server │ │ ├── __init__.py │ │ └── app.py │ └── setup.py └── utils ├── setup.py └── utils ├── __init__.py ├── math.py └── strutil.py ``` -------------------------------- ### Load all code into Pants REPL with IPython and arguments Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/goals/repl This example demonstrates how to start an IPython REPL session using Pants, load all project code, and pass arguments to the REPL program. It uses the `--` separator to distinguish Pants arguments from REPL arguments. ```shell $ pants repl --shell=ipython -- -i helloworld/main.py ``` -------------------------------- ### Run golangci-lint with Pants Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/go Demonstrates how to execute the `pants lint` command to run golangci-lint on a Go file. It shows an example of the output when linting fails, indicating unused code. ```bash $ pants lint main.go 20:39:43.10 [ERROR] Completed: Lint with golangci-lint - golangci-lint failed (exit code 1). main.go:5:6: func `bad` is unused (unused) func bad() { ^ ✗ golangci-lint failed. ``` -------------------------------- ### Bootstrap and Verify Pants Installation (Shell) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/getting-started/manual-installation This command executes the downloaded `./pants` script to bootstrap the Pants installation and verify the installed version. It ensures that Pants is set up correctly according to the version specified in `pants.toml`. ```shell ./pants --version ``` -------------------------------- ### Simplifying Get Syntax in Pants Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/plugin-upgrade-guide Shows the updated syntax for `Get` in Pants, where it now accepts only a single type parameter for the output type. The second type parameter for the input type has been removed as it was unused. This simplifies the `Get` construct. ```python Get[_Output] ``` -------------------------------- ### PyOxidizer Template Usage Example Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/integrations/pyoxidizer Illustrates how to use parameters within a custom PyOxidizer `.bzlt` template file. It shows examples of accessing the target's name and consuming wheel dependencies. ```bzlt exe = dist.to_python_executable( name="$NAME", packaging_policy=policy, config=python_config, ) exe.add_python_resources(exe.pip_install($WHEELS)) ``` -------------------------------- ### Install Pants using the 'bin' tool Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/getting-started/installing-pants This command uses the 'bin' tool to install Pants. It downloads the Pants launcher from a GitHub repository and places it in the specified local bin directory. The Pants launcher manages different versions of Pants per repository. ```bash bin i github.com/pantsbuild/scie-pants ~/.local/bin/pants ``` -------------------------------- ### Install Rustup Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/contributions/releases/github-actions-macos-arm64-runners This command downloads and installs Rustup, the toolchain installer for Rust, with non-interactive mode enabled. ```shell % curl https://sh.rustup.rs -sSf | sh -s -- -y ``` -------------------------------- ### Illustrate Get() Request and Rule Signature Matching Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/tutorials/create-a-new-goal Demonstrates how a Get() request for a specific output type and input type corresponds to a @rule function signature. This highlights the mechanism Pants uses to match requests to rules. ```python # requesting an object of type "ProjectVersionFileView", # passing an object of type "ProjectVersionTarget" in the variable "target" Get(ProjectVersionFileView, ProjectVersionTarget, target) # it requires an object of type "ProjectVersionTarget" and # will return an object of type "ProjectVersionFileView" @rule async def get_project_version_file_view(target: ProjectVersionTarget) -> ProjectVersionFileView: ... ``` -------------------------------- ### Example Requirements.txt Lockfile Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/overview/lockfiles An example of a manually generated lockfile in pip's requirements.txt format. It includes package versions and SHA256 hash entries for improved supply chain security, ensuring the integrity of the installed dependencies. ```text freezegun==1.2.0 \ --hash=sha256:93e90676da3... \ --hash=sha256:e19563d0b05... ``` -------------------------------- ### Run Python REPL with IPython shell in Pants Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/goals/repl This example shows how to start an interactive Python REPL session using Pants with the IPython shell. It highlights that this specific command might not load user code by default and provides a simple arithmetic example within IPython. ```shell ❯ pants repl --shell=ipython Python 3.9.12 (main, Mar 26 2022, 15:45:34) Type 'copyright', 'credits' or 'license' for more information IPython 7.34.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: 21 * 4 Out[1]: 84 ``` -------------------------------- ### Snapshot Example with Digest Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/file-system Demonstrates how to create a Snapshot object from a Digest, enriching it with file and directory information. This is useful for understanding the contents of a Digest, such as when preparing inputs for a process. ```python from pants.engine.fs import Digest, Snapshot from pants.engine.rules import Get, rule @rule async def demo(...) -> Foo: ... snapshot = await Get(Snapshot, Digest, my_digest) ``` -------------------------------- ### Run Go Binary with Arguments Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/go Shows the command `pants run path/to/main_pkg:` for executing a Go binary. It includes an example of passing arguments to the binary using the `--` separator, demonstrating how to invoke the binary with specific flags like `--help`. ```shell ❯ pants run cmd/deploy: -- --help Usage of /Users/pantsbuild/example/.pants.d/workdir/tmpzfh33ggu/cmd.deploy/bin: --allow-insecure-auth allow credentials to be passed unencrypted (i.e., no TLS) -A, --auth-token-env string name of environment variable with auth bearer token ... pflag: help requested ``` -------------------------------- ### Format and Lint Go Code with Pants Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/go Provides examples of using Pants commands to format and lint Go code. It covers formatting specific directories, entire projects, and checking formatting status. ```shell # Format a single directory ❯ pants fmt cmd/deploy: # Format this directory and all subdirectories ❯ pants fmt cmd:: # Check that the whole project is formatted ❯ pants lint :: # Format all changed files ❯ pants --changed-since=HEAD fmt ``` -------------------------------- ### Install Pre-push Git Hook Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/contributions/development/setting-up-pants This script installs the pre-push Git hook, which runs checks and linters before allowing a Git push. This helps catch common issues early and prevent CI failures. ```bash build-support/bin/setup.sh ``` -------------------------------- ### Example Imports in Python and Java Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/source-roots Illustrates how to import modules and functions in Python and Java within a Pants project. This shows the standard import syntax for each language. ```python from project.app import App from project.util.test_math import test_add_2 ``` ```java import org.pantsbuild.project.App import org.pantsbuild.project.util.Math ``` -------------------------------- ### Create Pants Configuration File (Shell) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/getting-started/manual-installation This command creates a minimal `pants.toml` configuration file. It sets the global `pants_version` to a specified release version (X.Y.Z). This file is essential for Pants to know which version to install and use. ```shell printf '[GLOBAL]\npants_version = "X.Y.Z"\n' > pants.toml ``` -------------------------------- ### CreateDigest Example Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/file-system Shows how to use the CreateDigest rule to generate a new Digest containing specified file content. This allows for the creation of virtual files that do not need to exist on the actual filesystem. ```python from pants.engine.fs import CreateDigest, Digest, FileContent from pants.engine.rules import Get, rule @rule async def demo(...) -> Foo: ... digest = await Get(Digest, CreateDigest([FileContent("f1.txt", b"hello world")])) ``` -------------------------------- ### Run Python REPL with specific file in Pants Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/goals/repl This example demonstrates how to start an interactive Python REPL session using Pants and load a specific Python file. It shows how to import and use classes from the loaded file, and also demonstrates using an external Python package (`translate`). ```shell $ pants repl helloworld/greet/greeting.py Python 3.7.6 (default, Feb 26 2020, 08:28:08) [Clang 11.0.0 (clang-1100.0.33.8)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from helloworld.greet.greeting import Greeter >>> Greeter().greet("Pants") 'buenas tardes, Pants!' >>> from translate import Translator >>> Translator(to_lang="fr").translate("Good morning.") 'Salut.' ``` -------------------------------- ### Install Software via SSH Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/contributions/releases/github-actions-macos-arm64-runners Installs essential software including Rosetta 2, Xcode command-line tools, Homebrew, pyenv, and AWS CLI. Some installations may require user interaction or VNC for license agreements. ```Shell # Install Rosetta 2, will prompt to accept a license agreement % softwareupdate --install-rosetta # Install XCode command-line tools # IMPORTANT: This pops up a license agreement window on the desktop, # so you must use VNC to accept the license and complete the installation. % xcode-select --install # Install Homebrew % /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" % echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> /Users/administrator/.zshenv % eval "$(/opt/homebrew/bin/brew shellenv)" # Install pyenv % brew install pyenv # Set up pyenv % echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshenv % echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshenv % echo 'eval "$(pyenv init -)"' >> ~/.zshenv % source ~/.zshenv # Install the AWS CLI % brew install awscli ``` -------------------------------- ### Configure Pants Cache Directories Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/troubleshooting-common-issues This example demonstrates how to configure various cache directories for Pants by modifying the `pants.toml` file. It shows how to set `local_store_dir`, `named_caches_dir`, `pants_workdir`, and `pants_distdir`. Relative paths and the `%(homedir)s` special string are supported. ```ini [GLOBAL] local_store_dir = "~/.cache/pants/lmdb_store" named_caches_dir = "~/.cache/pants/named_caches" pants_workdir = ".pants.d/workdir" pants_distdir = "dist/" ``` -------------------------------- ### Example Imports with Marker File Source Roots Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/source-roots Shows valid Python imports for a project configured with marker files (e.g., `setup.py`). Imports are made relative to the identified source roots ('server' and 'utils'), avoiding deeper, invalid paths. ```python import server.app from utils.strutil import capitalize ``` -------------------------------- ### Minimal makeself_archive example Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/shell/self-extractable-archives This example demonstrates how to create a minimal self-extractable archive using the makeself_archive target. The 'startup_script' defines the commands to run when the archive is executed. The archive is built using the 'package' goal. ```python makeself_archive( name="arc", startup_script=["echo", "hello pants"], ) ``` -------------------------------- ### Example Python Constraints File Content Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/overview/third-party-dependencies An example of the content within a pip-compatible constraints file, specifying exact versions for Python packages. ```text requests==22.1.0 urllib3==4.2 ``` -------------------------------- ### Download and Make Pants Launch Script Executable (Shell) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/getting-started/manual-installation This command downloads the Pants launch script from a static URL and makes it executable. The script is responsible for installing Pants and managing upgrades. It should be placed at the root of the repository and added to version control. ```shell curl -L -O https://static.pantsbuild.org/setup/pants && chmod +x ./pants ``` -------------------------------- ### Example shUnit2 Test File Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/shell A simple example of a shell script (`tests.sh`) written using the shUnit2 testing framework. It includes a basic test function `testEquality` that asserts the equality of two values. ```bash #!/usr/bin/env bash testEquality() { assertEquals 1 1 } ``` -------------------------------- ### Shorthand `Get` Constructor for Process Execution (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/concepts Shows the concise syntax for constructing a `Get` object when the input type can be inferred from the input instance. This simplifies the call to `await Get` by omitting the explicit `InputType` parameter. Requires `pants.engine.rules`. ```python from pants.engine.rules import Get, rule # Verbose constructor: # Get(ProcessResult, Process, Process(["/bin/echo"])) # Shorthand constructor: Get(ProcessResult, Process(["/bin/echo"])). ``` -------------------------------- ### Create Example Test Field Set (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/run-tests Creates a `TestFieldSet` subclass to collect fields required for running example tests. It marks the sources field as required and includes logic for opting out of tests if the skip field is set. ```python from pants.core.goals.test import TestFieldSet @dataclass(frozen=True) class ExampleTestFieldSet(TestFieldSet): required_fields = (ExamleTestSourceField,) sources: ExampleTestSourceField timeout: ExampleTestTimeoutField @classmethod def opt_out(cls, tgt: Target) -> bool: return tgt.get(SkipExampleTestsField).value ``` -------------------------------- ### Cross-Project Imports Example Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/source-roots Illustrates importing modules across different top-level project directories. This highlights Pants' ability to manage dependencies between distinct project components. ```python import ads.billing.calculate_bill from base.models.user import User from base.util.math import add_two ``` -------------------------------- ### Run Pants with Backend Packages and File Dependencies (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/testing-plugins This example shows how to run Pants with specific backend packages enabled and query for file dependencies. It utilizes `setup_tmpdir` for setting up test files and `run_pants` to execute the `filedeps` goal. The output is then asserted to contain the expected file paths, demonstrating how to test file discovery mechanisms. ```python from pants.testutil.pants_integration_test import run_pants, setup_tmpdir def test_getting_list_of_files_from_a_target() -> None: sources = { "dir/BUILD": "files(sources=['subdir/*.txt'])", "dir/subdir/file1.txt": "", "dir/subdir/file2.txt": "", } with setup_tmpdir(sources) as tmpdir: result = run_pants( [ "--backend-packages=['pants.backend.python']", "filedeps", f"{tmpdir}/dir:", ], ) result.assert_success() assert all( filepath in result.stdout for filepath in ( f"{tmpdir}/dir/subdir/file1.txt", f"{tmpdir}/dir/subdir/file2.txt", ) ) ``` -------------------------------- ### Pants Build: Targeting Non-Source Files with Dependencies Rules Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/validating-dependencies Illustrates how to use `__dependencies_rules__` to restrict which libraries can be imported by source files. This example shows how to allow specific libraries while denying others using glob patterns and negation. ```python # example/BUILD # Limit which libraries may be depended upon __dependencies_rules__( ( "*", # These rules applies to all targets # May only import setuptools and ansicolors, but no other libraries from the example/reqs target "//example/reqs#setuptools", "reqs#ansicolors", "!//example/reqs#*", # Any other dependency allowed "*", ), ) ``` -------------------------------- ### Enable Pants Backends Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/getting-started/initial-configuration Activates specific Pants functionality by adding backend packages to the GLOBAL configuration. This is essential for enabling support for various languages and tools within Pants. ```toml [GLOBAL] ... backend_packages = [ "pants.backend.experimental.go", "pants.backend.python", "pants.backend.python.lint.black", ] ``` -------------------------------- ### Django settings example (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/goals/check A minimal Django settings file used for MyPy plugin configuration. It includes necessary imports and basic settings. ```python from django.urls import URLPattern DEBUG = True DEFAULT_FROM_EMAIL = "[email protected]" SECRET_KEY = "not so secret" MY_SETTING = URLPattern(pattern="foo", callback=lambda: None) ``` -------------------------------- ### Configure Go Backend in pants.toml Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/go This snippet shows how to activate the Go backend by adding the necessary package to the `backend_packages` list in `pants.toml`. It also mentions optional configurations for `minimum_expected_version` and `go_search_paths` to manage Go distribution discovery. ```toml [GLOBAL] backend_packages = ["pants.backend.experimental.go"] ``` -------------------------------- ### Use TransitiveTargetsRequest for resolving TransitiveTargets Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/plugin-upgrade-guide Updates the method for resolving `TransitiveTargets`. Instead of `await Get(TransitiveTargets, Addresses([addr1]))`, use `await Get(TransitiveTargets, TransitiveTargetsRequest([addr1]))`. This change affects how the transitive closure of targets is obtained. ```python from pants.engine.target import Addresses, TransitiveTargets, TransitiveTargetsRequest from pants.engine.rules import Get, rule @rule def get_transitive_targets(request: TransitiveTargetsRequest) -> TransitiveTargets: # Implementation details to resolve transitive targets pass # Example usage: async def resolve_targets(addresses): transitive_targets = await Get(TransitiveTargets, TransitiveTargetsRequest(addresses)) return transitive_targets # In a rule signature: # @rule # def my_rule(addresses: Addresses): # transitive_targets = await Get(TransitiveTargets, TransitiveTargetsRequest(addresses)) # ... ``` -------------------------------- ### Write Files and Get Python Target by Address Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/testing-plugins Shows how to write a BUILD file with a `python_source` target and then retrieve that target using its `Address`. This is essential for testing target definitions. ```python from textwrap import dedent from pants.engine.addresses import Address from pants.testutil.rule_runner import RuleRunner def test_example() -> None: rule_runner = RuleRunner() rule_runner.write_files({ "project/BUILD": dedent( """ python_source( name="my_tgt", source="f.py", """ ) }) tgt = rule_runner.get_target(Address("project", target_name="my_tgt")) ``` -------------------------------- ### Deprecated ZipBinaryRequest in favor of Get(ZipBinary) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/plugin-upgrade-guide Illustrates the deprecation of explicit request types like ZipBinaryRequest in favor of directly using Get(OutputType). This change simplifies the Get syntax, allowing direct retrieval of an output type without specifying a separate request object. The lazy API is useful for conditional fetching of output types. ```python from pants.core.util_rules.system_binaries import ZipBinary, ZipBinaryRequest from pants.engine.rules import Get, rule class MyOutput: pass @rule def my_rule(zip_binary: ZipBinary) -> MyOutput: return MyOutput() @rule async def my_rule_lazy() -> MyOutput: zip_binary = await Get(ZipBinary, ZipBinaryRequest()) return MyOutput() ``` -------------------------------- ### Compute Fibonacci Number Recursively with `await Get` (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/concepts Illustrates a recursive rule implementation using `await Get` to compute Fibonacci numbers. This example shows how to request intermediate Fibonacci values dynamically. It relies on the `dataclasses` module and `pants.engine.rules`. ```python from dataclasses import dataclass from pants.engine.rules import Get, rule @dataclass(frozen=True) class Fibonacci: val: int @rule async def compute_fibonacci(n: int) -> Fibonacci: if n < 2: return Fibonacci(n) x = await Get(Fibonacci, int, n - 2) y = await Get(Fibonacci, int, n - 1) return Fibonacci(x.val + y.val) ``` -------------------------------- ### Manage In-Repo Plugin Dependencies with requirements.txt Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/overview This example demonstrates how to declare third-party dependencies for an in-repo plugin. By placing a `requirements.txt` file alongside your plugin's `register.py`, you can specify external libraries that your plugin needs. ```text ansicolors==1.18.0 ``` -------------------------------- ### Python Build File: Dependency Example Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/validating-dependencies Demonstrates a basic dependency relationship between two Python source files using `python_sources` in BUILD files. Shows how `src/a/main.py` depends on `src/b/lib.py` and how this dependency is declared within the BUILD files. ```python # src/a/BUILD python_sources(dependencies=["src/b/lib.py"], tags=["apps"]) # src/b/BUILD python_sources(tags=["libs"]) ``` -------------------------------- ### Update Test Execution Rule (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/plugin-upgrade-guide Demonstrates the transition from the old test execution API to the new two-rule system. The 'Before' example shows the original function signature, while the 'After' example illustrates the updated signature accepting a batch of test requests. ```python Before: ```python @rule async def run_test(field_set: CustomTestFieldSet) -> TestResult: ... ``` After: ```python @rule async def run_tests(batch: CustomTestRequest.Batch) -> TestResult: field_set = batch.single_element ... ``` ``` -------------------------------- ### Environment Matching with Fallbacks (BUILD) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/environments This example illustrates environment matching and fallback configurations. It defines a chain where 'remote' execution is preferred, falling back to 'local' if the platform matches, and then to 'docker'. It shows configurations for `remote_environment`, `local_environment`, and `docker_environment` targets, including `fallback_environment` and `compatible_platforms`. ```BUILD remote_environment( name="remote", fallback_environment="local", .. ) local_environment( name="local", compatible_platforms=["linux_x86_64"], fallback_environment="docker", ) docker_environment( name="docker", .. ) ``` -------------------------------- ### Generate JVM Lockfile Directly with GenerateJvmLockfileFromTool Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/plugin-upgrade-guide Demonstrates how to invoke GenerateJvmLockfileFromTool directly on a tool for lockfile generation, bypassing the need for a Get request. This is part of the deprecation of the older Get(GenerateJvmLockfileFromTool, GenerateToolLockfileSentinel) pattern. It shows how to obtain a tool_classpath using the generated lockfile request. ```python from pants.core.util_rules.toolroots import GenerateJvmLockfileFromTool from pants.engine.engine import Get from pants.engine.rules import rule from pants.jvm.compile import JarJarGeneratorLockfileSentinel from pants.jvm.jdk_rules import InternalJdk from pants.jvm.nailgun.nailgun_protocol import JarJar from pants.jvm.nailgun.nailgun_rules import ShadeJar, ShadeJarRequest from pants.core.util_rules.tool_classpath import ToolClasspath, ToolClasspathRequest @rule async def shade_jar(request: ShadeJarRequest, jdk: InternalJdk, jarjar: JarJar) -> ShadedJar: ... lockfile_request = await Get(GenerateJvmLockfileFromTool, JarJarGeneratorLockfileSentinel()) tool_classpath = await Get(ToolClasspath, ToolClasspathRequest(lockfile=lockfile_request)) ``` ```python from pants.core.util_rules.toolroots import GenerateJvmLockfileFromTool from pants.engine.engine import Get from pants.engine.rules import rule from pants.jvm.compile import JarJarGeneratorLockfileSentinel from pants.jvm.jdk_rules import InternalJdk from pants.jvm.nailgun.nailgun_protocol import JarJar from pants.jvm.nailgun.nailgun_rules import ShadeJar, ShadeJarRequest from pants.core.util_rules.tool_classpath import ToolClasspath, ToolClasspathRequest @rule async def shade_jar(request: ShadeJarRequest, jdk: InternalJdk, jarjar: JarJar) -> ShadedJar: ... await Get( ToolClasspath, ToolClasspathRequest(lockfile=GenerateJvmLockfileFromTool.create(jarjar)) ) ``` -------------------------------- ### Mocking Subsystems and GoalSubsystems (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/testing-plugins Demonstrates how to mock Subsystem and GoalSubsystem instances for use in rule testing. This requires explicitly providing all options read by the rule, as default values are not used. Dependencies include PythonSetup, FmtSubsystem, create_subsystem, and create_goal_subsystem. ```python from pants.backend.python.subsystems.setup import PythonSetup from pants.core.goals.fmt import FmtSubsystem from pants.testutil.option_util import create_goal_subsystem, create_subsystem mock_subsystem = create_subsystem(PythonSetup, interpreter_constraints=["CPython==3.8.*"]) # type: ignore[call-arg] mock_goal_subsystem = create_goal_subsystem(FmtSubsystem, sep="\n") # type: ignore[call-arg] ``` -------------------------------- ### Define Example Test Subsystem (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/run-tests Defines a `Subsystem` for the example test runner, providing configuration options and a skip option. This allows users to configure the test runner's behavior globally. ```python from pants.option.option_types import SkipOption from pants.option.subsystem import Subsystem class ExampleTestSubsystem(Subsystem): name = "Example" options_scope = "example-test" help = "Some tool to run tests" skip = SkipOption("test") ``` -------------------------------- ### Package Go Binaries with Pants Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/go Demonstrates the `pants package` command for building Go binaries. It shows how to package all binaries in the project (`package ::`) or a specific binary (`package path/to/main_pkg:`), with output typically found in the `dist` directory. ```shell ❯ pants package :: [INFO] Wrote dist/cmd.deploy/bin [INFO] Wrote dist/cmd.runner/bin ``` -------------------------------- ### Updating MockGet for Multiple Input Types in Pants Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/plugin-upgrade-guide Illustrates the change in `MockGet` usage within Pants 2.15. Previously, `MockGet` expected a single `input_type`. Now, it requires `input_types` as a tuple to support zero or multiple arguments in `Get` calls. This change ensures compatibility with new `Get` syntax. ```python MockGet( output_type=LintResult, input_types=(LintTargetsRequest,), mock=lambda _: LintResult(...), ) ``` -------------------------------- ### Execute Pants Project Version Goal Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/tutorials/create-a-new-goal A command-line example showing how to invoke the 'project-version' goal in Pants for a specific target ('myapp'). The output displays the ProjectVersionFileView with the path and version. ```bash $ pants project-version myapp ProjectVersionFileView(path='myapp:main-project-version', version='1.2.3') ``` -------------------------------- ### Simulate Project Structure and Run Pants Command (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/testing-plugins This snippet demonstrates how to use `setup_tmpdir` to create a temporary project structure and `run_pants` to execute a Pants command within that environment. It's useful for testing Pants' behavior with specific configurations and file dependencies. The `PantsResult` object is used to assert success or failure and inspect output. ```python from pants.testutil.pants_integration_test import run_pants, setup_tmpdir def test_build_ignore_dependency() -> None: sources = { "dir1/BUILD": "files(sources=[])", "dir2/BUILD": "files(sources=[], dependencies=['{tmpdir}/dir1'])", } with setup_tmpdir(sources) as tmpdir: ignore_result = run_pants( [f"--build-ignore={tmpdir}/dir1", "dependencies", f"{tmpdir}/dir2"] ) no_ignore_result = run_pants(["dependencies", f"{tmpdir}/dir2"]) ignore_result.assert_failure() assert f"{tmpdir}/dir1" not in ignore_result.stderr no_ignore_result.assert_success() assert f"{tmpdir}/dir1" in no_ignore_result.stdout ``` -------------------------------- ### Dockerfile for a Simple Application Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/helm/deployments A basic Dockerfile that uses the busybox image as its base. This serves as a minimal example for building a Docker image. ```dockerfile FROM busybox:1.28 ``` -------------------------------- ### Create a Rule to Get Project Version Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/tutorials/create-a-new-goal An example of a Pants @rule function that returns a ProjectVersionFileView data structure. It takes a ProjectVersionTarget as input and returns a hardcoded version for demonstration. ```python @rule async def get_project_version_file_view( target: ProjectVersionTarget, ) -> ProjectVersionFileView: return ProjectVersionFileView( path="path", version="1.2.3" ) ``` -------------------------------- ### Write File and Read Content Using Build Root Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/testing-plugins Illustrates writing a file and then reading its content using `rule_runner.build_root` to construct the correct file path. This verifies file creation and content. ```python from pants.testutil.rule_runner import RuleRunner from pathlib import Path def test_example() -> None: rule_runner = RuleRunner() rule_runner.write_files({"project/app.py": "print('hello world!')\n"}) assert Path(rule_runner.build_root, "project/app.py").read_text() == "print('hello world!')\n" ``` -------------------------------- ### Example Polyglot Repository Structure Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/source-roots Presents a common project structure for polyglot repositories, where different languages reside in subdirectories under a common 'src' directory (e.g., 'src/python', 'src/java'). Pants can identify these as source roots. ```text src ├── python ├── java ├── assets └── rust ``` -------------------------------- ### Set Default Environment Variables (.pants.bootstrap) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/options Demonstrates how to define default environment variables within the `.pants.bootstrap` Bash script. These variables are exported and available to the Pants launcher and any processes it starts, facilitating local development setup and CI environments. ```bash # these variables are defined in our CI agents, # but this is set to support local development export DOCKER_DEFAULT_REPO="https://hub.docker.com/" export GIT_COMMIT="$(git rev-parse HEAD)" ``` -------------------------------- ### Configure Python Tools with Pants.toml Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/overview/linters-and-formatters Example configuration in pants.toml for Python tools like docformatter and flake8. It demonstrates setting command-line arguments, specifying custom resolves for tool versions and plugins, and pointing to non-standard configuration files. ```toml [docformatter] args = ["--wrap-summaries=100", "--wrap-descriptions=100"] [python.resolves] # A custom resolve that updates the version and adds a custom plugin. flake8 = "3rdparty/python/flake8.lock" [flake8] # Load a config file in a non-standard location. config = "build-support/flake8" install_from_resolve = "flake8" ``` -------------------------------- ### Run Pants Package Goal Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/integrations/pyoxidizer Demonstrates how to use the `pants package` goal to create a directory containing the PyOxidizer binary. The output path can be customized using the `output_path` field. ```bash pants package src/py/project:bin ``` -------------------------------- ### Example of user-defined __hash__ method for performance Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/contributions/development/style-guide This Python code snippet demonstrates overriding the `__hash__` method to improve performance by increasing cache hits. It is a specific optimization for the `pants list ::` command, achieving a 10% speedup for a large number of targets. ```python def __hash__(self): # By overriding __hash__ here, rather than using the default implementation, # we get a 10% speedup to `pants list ::` (1000 targets) thanks to more # cache hits. This is safe to do because ... ... ``` -------------------------------- ### User Data Script for EC2 Instance Setup Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/contributions/releases/github-actions-linux-aarch64-runners This script is used as User Data when launching a temporary EC2 instance to ensure the SSH daemon starts on boot. It's a simple bash script that enables the SSH service. ```bash #!/bin/bash systemctl start ssh ``` -------------------------------- ### Deny and Allow Rules with Dictionary Syntax (Pants BUILD) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/validating-dependencies This example shows how to define deny and allow rules within a Pants BUILD file using the dictionary syntax. It specifies paths to exclude and include, demonstrating granular control over target visibility and dependencies. ```python ( ( {"path": "tests/**", "action": "deny"}, {"path": "src/*/*/**", "action": "deny"}, ), ( {"path": "*"}, ) ) ``` -------------------------------- ### Example Python Project Structure Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/source-roots Illustrates a typical Python project layout where 'src/python' is designated as a source root, enabling imports like 'from project.app import App'. This structure is common when top-level folders are used for namespacing. ```text src └── python └── project ├── __init__.py ├── app.py ├── config │ ├── __init__.py │ └── prod.json └── util ├── __init__.py └── math.py ``` -------------------------------- ### Pants Rule Graph Execution Example Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/tutorials/create-a-new-goal Shows a scenario with multiple @rule functions where Pants automatically resolves dependencies. A Get(C, A, obj) request triggers a chain of rule executions (rule1 then rule2) to produce the desired output. ```python @rule async def rule1(A) -> B: ... @rule async def rule2(B) -> C: ... @goal_rule async def main(...): result = await Get(C, A, obj) ``` -------------------------------- ### Nested Project Structure Example Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/source-roots Presents a more complex, nested project layout with multiple top-level directories for different components (ads, base, news). This demonstrates flexibility in organizing larger codebases. ```tree .\n├── ads\n│ └── py\n│ └── ads\n│ ├── __init__.py\n│ ├── billing\n│ │ ├── __init__.py\n│ │ └── calculate_bill.py\n│ └── targeting\n│ ├── __init__.py\n│ └── validation.py\n├── base\n│ └── py\n│ └── base\n│ ├── __init__.py\n│ ├── models\n│ │ ├── __init__.py\n│ │ ├── org.py\n│ │ └── user.py\n│ └── util\n│ ├── __init__.py\n│ └── math.py\n└── news\n └── js\n └── spa.js ``` -------------------------------- ### Python Distribution Dependencies with PyOxidizer Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/integrations/pyoxidizer Demonstrates how Pants manages implicit dependencies between python_distribution targets. It shows how to correctly include all relevant distributions in the pyoxidizer_binary dependencies to avoid PyPI installation issues. ```python python_sources(name="lib") python_distribution( name="dist", # Note that this python_distribution does not # explicitly include project/utils:dist in its # `dependencies` field, but Pants still # detects an implicit dependency and will add # it to this dist's `install_requires`. dependencies=[ ":lib"], provides=setup_py(name="main-dist", version="0.0.1"), ) pyoxidizer_binary( name="bin", entry_point="hellotest.main", dependencies=[ ":dist", "project/utils:dist"], ) ``` -------------------------------- ### Python Dataclass Definition vs. Traditional Class Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/contributions/development/style-guide Illustrates the preference for Python dataclasses for defining data-holding classes due to their declarative nature and integration with type checkers like MyPy. It shows both a good dataclass example and a less preferred traditional class. ```python from dataclasses import dataclass # Good @dataclass(frozen=True) class Example: name: str age: int = 33 # Bad class Example: def __init__(self, name: str, age: int = 33) -> None: self.name = name self.age = age ``` -------------------------------- ### Run Go Tests with Pants Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/go Shows the `pants test` command for executing Go tests within a project. Examples cover running tests for a specific package, a directory recursively, or the entire project, similar to the `check` command's scope. ```shell # Test this package ❯ pants test pkg/deploy: # Test this directory and all subdirectories ❯ pants check pkg:: ``` -------------------------------- ### Configure PyOxidizer with Filesystem Resources (Starlark) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/integrations/pyoxidizer This snippet demonstrates how to configure a `pyoxidizer_binary` target in Pants Build using the `filesystem_resources` field. This field allows you to specify dependencies that must be installed directly onto the filesystem. It requires the `name`, `dependencies`, `entry_point`, and `filesystem_resources` arguments. ```starlark pyoxidizer_binary( name="bin", dependencies=[":dist"], entry_point="myproject.myapp", filesystem_resources=["numpy==1.17"], ) ``` -------------------------------- ### Requesting Environment Names in Pants Goals Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/plugin-upgrade-guide Demonstrates how to request and use `EnvironmentName` within Pants goals. This is crucial for goals that need to respect specific environment configurations when running underlying rules. It shows the use of `EnvironmentNameRequest` and how to pass `EnvironmentName` to `Get` calls. ```python Get( EnvironmentName, EnvironmentNameRequest, EnvironmentNameRequest.from_field_set(field_set), ) Get(TestResult, {"field_set": TestFieldSet, "environment_name": EnvironmentName}) ``` -------------------------------- ### Glob Syntax for File Matching (Pants BUILD) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/validating-dependencies Demonstrates the use of glob syntax in Pants BUILD files for matching files. It explains the `*` and `**` wildcards for non-recursive and recursive matching, respectively, and how globs are applied to paths. ```plaintext .py my_source.py my_*.py *.py */my_source.py **/my_*.py some/directory/* ``` -------------------------------- ### Install Pants using Homebrew Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/getting-started/installing-pants This command installs Pants on macOS using the Homebrew package manager. It adds the Pantsbuild tap and then installs the 'pants' formula. ```bash brew install pantsbuild/tap/pants ``` -------------------------------- ### Download File with Digest using Python Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/file-system Demonstrates how to download a file using a GET request with a specified URL and expected file digest. This ensures the integrity of the downloaded asset. It requires the `pants.engine.fs` and `pants.engine.rules` modules. ```python from pants.engine.fs import DownloadFile, FileDigest from pants.engine.rules import Get, rule @rule async def demo(...) -> Foo: ... url = "https://github.com/pex-tool/pex/releases/download/v2.1.14/pex" file_digest = FileDigest( "12937da9ad5ad2c60564aa35cb4b3992ba3cc5ef7efedd44159332873da6fe46", 2637138 ) downloaded = await Get(Digest, DownloadFile(url, file_digest)) ``` -------------------------------- ### Load Resources in Kotlin Code Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/jvm/kotlin Example of loading a resource file (`hello.txt`) within Kotlin code using `com.google.common.io.Resources.getResource`. This demonstrates how to access files declared as `resource` targets. ```KOTLIN package org.pantsbuild.example.lib import com.google.common.io.Resources fun load() { ... = Resources.getResource(Loader.class, "hello.txt") } ``` -------------------------------- ### Activate SQL Backend in pants.toml Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/sql This snippet shows how to enable the experimental SQL backend in your Pants build configuration file (`pants.toml`). Activating this backend is the first step to using Pants with SQL files, introducing new target types for SQL sources. ```toml [GLOBAL] backend_packages = [ ... "pants.backend.experimental.sql", ... ] ``` -------------------------------- ### Configure Interpreter Constraints (.pants.rc) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/options This example shows how to set interpreter constraints in a personal Pants configuration file (`.pants.rc`). This allows users to override repository-wide settings for specific Python versions, useful for managing different development environments. ```toml [python] interpreter_constraints = ["==3.9.*"] ``` -------------------------------- ### Configure List Options via Command-Line Flags Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/key-concepts/options Demonstrates how to set list options using command-line flags. Values can be provided as a JSON-like array or appended individually. Appending adds to existing values, while using `[]` overrides them. ```shell pants --scope-listopt="['foo','bar']" pants --scope-listopt=foo --scope-listopt=bar ``` -------------------------------- ### Write Files and Create Python Library Target Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/testing-plugins Demonstrates writing a Python file and a BUILD file to define a `python_library` target. This is useful for setting up test environments. ```python from pants.testutil.rule_runner import RuleRunner def test_example() -> None: rule_runner = RuleRunner() rule_runner.write_files( { "project/app.py": "print('hello world!')\n", "project/BUILD": "python_library()", } ) ``` -------------------------------- ### Install Jupyter and Pants Jupyter Plugin (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/integrations/jupyter Installs the necessary Jupyter components and the pants-jupyter-plugin using pip. It is recommended to perform this installation within a virtual environment. The command also includes launching JupyterLab. ```python # Install jupyter and the plugin (NB: please use a virtualenv!) pip install jupyterlab pants-jupyter-plugin # Launch JupyterLab, which will open a browser window for notebook editing. jupyter lab ``` -------------------------------- ### Define Example Test Target Type (Python) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/common-plugin-tasks/run-tests Defines a new target type for example tests, including fields for source files, timeouts, and skipping tests. This allows Pants to recognize and manage example test files. ```python from pants.engine.target import ( COMMON_TARGET_FIELDS, Dependencies, BoolField, IntField, SingleSourceField, Target, ) class ExampleTestSourceField(SingleSourceField): expected_file_extensions = (".example",) class ExampleTestTimeoutField(IntField): alias = "timeout" help = "Whether to time out after a certain period of time" class SkipExampleTestsField(BoolField): alias = "skip_example_tests" default = False help = "If set, don't run tests on this source" class ExampleTestTarget(Target): alias = "example_tests" help = "Example tests run by some tool" core_fields = ( *COMMON_TARGET_FIELDS, Dependencies, ExampleTestSourceField, ExampleTestTimeoutField, SkipExampleTestsField, ) ``` -------------------------------- ### Create Target Address Object Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/rules-and-the-target-api Shows how to construct an `Address` object from `pants.engine.addresses`, which uniquely identifies a target. Examples cover various formats, including project/target names, relative file paths, and generated names, useful for testing and process descriptions. ```python # project:tgt -> Address("project", target_name="tgt") # project/ -> Address("project") # //:top-level -> Address("", target_name="top_level") # project/app.py:tgt -> Address("project", target_name="tgt", relative_file_name="app.py") # project:tgt#generated -> Address("project", target_name="tgt", generated_name="generated") # project:tgt@shell=zsh -> Address("project", target_name="tgt", parameters={"shell": "zsh"}) ``` -------------------------------- ### Run a Basic Process with Pants Engine Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/writing-plugins/the-rules-api/processes Demonstrates how to execute a simple command using the `Process` primitive within a Pants rule. It captures the standard output and standard error from the executed process. ```python from pants.engine.process import Process, ProcessResult from pants.engine.rules import Get, rule @rule async def demo(...) -> Foo: result = await Get( ProcessResult, Process( argv=["/bin/echo", "hello world"], description="Demonstrate processes.", ) ) logger.info(result.stdout.decode()) logger.info(result.stderr.decode()) ``` -------------------------------- ### Parametrize Target for Multiple Environments (BUILD) Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/using-pants/environments This code shows how to configure a single target, like a `pex_binary`, to run in multiple specified environments. It uses the `parametrize` builtin for the `environment` field, allowing the target to be built for environments named 'linux' and 'macos'. ```BUILD pex_binary( name="bin", environment=parametrize("linux", "macos"), ) ``` -------------------------------- ### Using `pex_binaries` Target Generator Source: https://www.pantsbuild.org/stable/docs/introduction/welcome-to-pants/python/goals/package Illustrates the use of the `pex_binaries` target generator for conveniently creating multiple `pex_binary` targets from a list of entry points within the same directory. This is useful when managing several scripts. The example shows how to define entry points and apply overrides for specific binaries, such as setting the execution mode. ```python # The default `sources` will include all our source files. python_sources(name="lib") pex_binaries( name="binaries", entry_points=[ "app1.py", "app2.py", "app3.py:my_func", ], overrides={ "app2.py:my_func": {"execution_mode": "venv"}, }, ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.