### Start REPL with Specific Files Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/goals/repl.mdx This example demonstrates starting the Pants REPL and loading a specific Python file, allowing you to import and interact with its contents. ```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 Pants with a Script Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/getting-started/installing-pants.mdx Download and run the official installer script to install the `pants` binary. This script determines your OS and architecture, downloads the correct binary, and installs it to `~/.local/bin`, warning if this location is not on your PATH. ```bash curl --proto '=https' --tlsv1.2 -fsSL https://static.pantsbuild.org/setup/get-pants.sh | bash ``` -------------------------------- ### Install Pre-push Git Hook Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/development/setting-up-pants.mdx Run the provided setup script to install the pre-push Git hook. This hook runs checks and lints before allowing a Git push, helping to prevent CI failures. ```bash build-support/bin/setup.sh ``` -------------------------------- ### Start Scala REPL Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/jvm/java-and-scala.mdx Launch the Scala REPL using the `--repl-shell=scala` flag. This example demonstrates importing a class and calling a main method. ```shell ❯ pants repl --repl-shell=scala src/jvm/org/pantsbuild/example/app/ExampleApp.scala Welcome to Scala 2.13.8 (OpenJDK 64-Bit Server VM, Java 11.0.21). Type in expressions for evaluation. Or try :help. scala> import org.pantsbuild.example.app.ExampleApp scala> ExampleApp.main(Array()) Hello World! scala> ``` -------------------------------- ### Install Pants with `bin` Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/getting-started/installing-pants.mdx Utilize the `bin` tool to install the Pants binary from its GitHub repository. ```bash bin i github.com/pantsbuild/scie-pants ~/.local/bin/pants ``` -------------------------------- ### Dockerfile Example Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/helm/deployments.mdx A minimal Dockerfile using busybox as the base image. ```text FROM busybox:1.28 ``` -------------------------------- ### Install Pants Launcher Source: https://context7.com/pantsbuild/pants/llms.txt Installs the Pants launcher binary, which then handles auto-installation of the repository-specific Pants version. ```bash curl --proto '=https' --tlsv1.2 -fsSL https://static.pantsbuild.org/setup/get-pants.sh | bash ``` ```bash brew install pantsbuild/tap/pants ``` ```bash SCIE_BOOT=update pants ``` ```bash pants --version ``` -------------------------------- ### Dockerfile with Build Arguments Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/docker/index.mdx Example Dockerfile demonstrating the use of `ARG` instructions to accept build-time variables. ```dockerfile FROM python:3.8 ARG VAR1 ARG VAR2 ARG VAR3=default ... ``` -------------------------------- ### Configure Resource Loading Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/jvm/kotlin.mdx Example of configuring resource loading in `pants.toml`. This setup ensures that files are correctly identified and can be loaded as resources by your JVM code, aligning with package structure. ```toml [source] # In order for the resource to be loadable as `org/pantsbuild/example/lib/hello.txt`, ``` -------------------------------- ### Install and Configure GitHub Actions Runner Service Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/releases/github-actions-macos-arm64-runners.mdx Installs the GitHub Actions runner as a service and sets up necessary environment variables. This ensures the runner starts automatically and has the required configurations. ```shell % cd actions-runner # Ensure that the runner starts when the machine starts. % ./svc.sh install ``` -------------------------------- ### Example Constraints File Content Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/overview/third-party-dependencies.mdx An example of a pip-compatible constraints file, used to pin specific versions of dependencies and their transitive dependencies. ```text requests==22.1.0 urllib3==4.2 ``` -------------------------------- ### List Available Goals Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/goals.mdx Run this command to see all the goals that are currently available in your Pants setup. ```bash ❯ pants help goals ``` -------------------------------- ### Install Rust with Rustup Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/development/setting-up-pants.mdx Install Rustup from the official website and ensure it is added to your system's PATH. This is a prerequisite for building the Pants engine. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Config File Interpolation Example Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/options.mdx Demonstrates using placeholders like %(key)s, %(env.ENV_VAR)s, %(buildroot)s, and %(homedir)s in `pants.toml` values. ```toml [DEFAULT] domain = "my.domain" [python-repos] repo_host = "repo.%(domain)s" indexes.add = ["https://%(env.PY_REPO)s@%(repo_host)s/index"] ``` -------------------------------- ### Example Tool Requirements File Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/overview/lockfiles.mdx A sample requirements file for a tool, specifying package versions and constraints. ```text # The default requirements (possibly with custom versions). pytest==7.1.1 pytest-cov>=2.12,!=2.12.1,<3.1 pytest-xdist>=2.5,<3 ipdb ``` -------------------------------- ### Add hardcoded kwarg to setup() Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/common-plugin-tasks/custom-python-artifact-kwargs.mdx Create a rule that returns `SetupKwargs` to add a hardcoded kwarg, such as `plugin_demo`, to the `setup()` call. This demonstrates basic kwarg manipulation. ```python from pants.backend.python.util_rules.package_dists import SetupKwargs from pants.engine.rules import rule @rule async def setup_kwargs_plugin(request: CustomSetupKwargsRequest) -> SetupKwargs: return SetupKwargs( {**request.explicit_kwargs, "plugin_demo": "hello world"}, address=request.target.address ) ``` -------------------------------- ### Example Java Imports Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/source-roots.mdx Shows how to import Java classes from your project when source roots are configured. ```java import org.pantsbuild.project.App import org.pantsbuild.project.util.Math ``` -------------------------------- ### Install Protobuf and LLVM Clang on Debian Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/development/setting-up-pants.mdx On Debian-based systems, install the protobuf compiler and LLVM clang using the apt package manager. These are required dependencies for building Pants. ```bash apt install clang protobuf-compiler ``` -------------------------------- ### Install Xcode Command Line Tools via SSH Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/releases/github-actions-macos-arm64-runners.mdx Install the Xcode command-line tools. Note: This action requires VNC to accept a license agreement that pops up on the desktop. ```shell # 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 ``` -------------------------------- ### Run Multiple Goals Sequentially Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/goals.mdx Execute multiple goals in order. In this example, code is formatted first, then tested. ```bash # Format all code, and then test it: ❯ pants fmt test :: ``` -------------------------------- ### Example Python Imports Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/source-roots.mdx Demonstrates how to import Python modules from different parts of your project when using source roots. ```python from project.app import App from project.util.test_math import test_add_2 ``` -------------------------------- ### Example BUILD file for Terraform Module Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/terraform/index.mdx A BUILD file defining a `terraform_module` target, which is referenced by a `terraform_deployment`. ```python terraform_module(name="infrastructure") ``` -------------------------------- ### Build and Package Go Sample Project Source: https://github.com/pantsbuild/pants/blob/main/src/python/pants/backend/go/README.md Use this command to build and package the sample Go project. Ensure the backend packages are correctly specified and build ignores are set if necessary. The output shows the executable path and arguments. ```shell #!/bin/bash ./pants \ --backend-packages='pants.backend.experimental.go' \ --build-ignore='-["/testprojects/src/go/**"]' \ package \ testprojects/src/go/pants_test:: ./dist/testprojects.src.go.pants_test/bin foo bar ``` ```text arg[0] = >> ./dist/testprojects.src.go.pants_test/bin << arg[1] = >> foo << arg[2] = >> bar << ``` -------------------------------- ### Install Jupyter and Pants Plugin Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/integrations/jupyter.mdx Install JupyterLab and the pants-jupyter-plugin using pip within a virtual environment. Then, launch JupyterLab to start using the plugin. ```shell # 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 ``` -------------------------------- ### Get General Pants Help Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/command-line-help.mdx Run `pants help` to display the main usage message and a list of available help commands. ```text ❯ pants help Pants 2.14.0 Usage: pants [options] [goals] [inputs] Attempt the specified goals on the specified inputs. pants help Display this usage message. pants help goals List all installed goals. pants help targets List all installed target types. pants help subsystems List all configurable subsystems. pants help tools List all external tools. pants help api-types List all plugin API types. pants help global Help for global options. pants help-advanced global Help for global advanced options. pants help [name] Help for a target type, goal, subsystem, plugin API type or rule. pants help-advanced [goal/subsystem] Help for a goal or subsystem's advanced options. pants help-all Print a JSON object containing all help info. [inputs] can be: A file, e.g. path/to/file.ext A path glob, e.g. '**/*.ext' (in quotes to prevent premature shell expansion) A directory, e.g. path/to/dir A directory ending in `::` to include all subdirectories, e.g. path/to/dir:: A target address, e.g. path/to/dir:target_name. Any of the above with a `-` prefix to ignore the value, e.g. -path/to/ignore_me:: Documentation at https://www.pantsbuild.org Download at https://pypi.org/pypi/pantsbuild.pants/2.14.0 ``` -------------------------------- ### Run a Single Goal with Output Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/goals.mdx Example of running the `count-loc` goal, which counts lines of code, and its typical output format. ```bash ❯ pants count-loc project/app_test.py ``` -------------------------------- ### Run the Project Version Goal Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/tutorials/create-a-new-goal.mdx Example of how to execute the custom 'project-version' goal from the command line. This demonstrates invoking the goal with a specific target, 'myapp', and shows the expected output. ```bash $ pants project-version myapp ProjectVersionFileView(path='myapp/VERSION', version='0.0.1') ``` -------------------------------- ### Pytest Fixture for RuleRunner Setup Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/the-rules-api/testing-plugins.mdx Define a Pytest fixture to provide a shared `RuleRunner` setup for multiple tests. This ensures each test gets a fresh `RuleRunner` instance for isolation. ```python import pytest from pants.testutil.rule_runner import RuleRunner @pytest.fixture def rule_runner() -> RuleRunner: return RuleRunner(target_types=[PythonSourceTarget], rules=[rule1, rule2]) def test_example1(rule_runner: RuleRunner) -> None: rule_runner.write_files(...) ... def test_example2(rule_runner: RuleRunner) -> None: rule_runner.write_files(...) ... ``` -------------------------------- ### Requirements.txt Example Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/overview/third-party-dependencies.mdx A sample `requirements.txt` file listing dependencies. This is often used in conjunction with `python_requirements` target generators. ```text setuptools mongomock ``` -------------------------------- ### Bad Comment Style Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/development/style-guide.mdx Shows an example of a comment that does not follow the recommended style guide. ```python #Not This ``` -------------------------------- ### Build File Example with Non-Existing Source Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/tutorials/advanced-plugin-concepts.mdx Demonstrates a `version_file` target in a BUILD file referencing a non-existent source file, which triggers an error. ```python version_file( name="main-project-version", source="non-existing-file", ) ``` -------------------------------- ### Initial Pants Configuration (`pants.toml`) Source: https://context7.com/pantsbuild/pants/llms.txt Sets up the `pants.toml` file at the repository root to pin the Pants version and enable necessary language backends and features. ```toml # pants.toml — root of repository [GLOBAL] pants_version = "2.32.0" backend_packages = [ "pants.backend.python", "pants.backend.python.lint.ruff.check", "pants.backend.python.lint.ruff.format", "pants.backend.python.typecheck.mypy", "pants.backend.experimental.go", "pants.backend.docker", "pants.backend.shell", ] [source] # Directories that are roots for import paths root_patterns = ["/src/python", "/src/go"] [python] interpreter_constraints = ["==3.12.*"] enable_resolves = true [python.resolves] python-default = "3rdparty/python/default.lock" [test] attempts_default = 2 [coverage-py] report = ["xml", "html"] ``` -------------------------------- ### Multi-threaded Profiling with Yappi Source: https://github.com/pantsbuild/pants/wiki/Debugging-Tips Use yappi to profile multi-threaded Python code. Ensure yappi is installed and import it to start profiling. This is useful for identifying performance bottlenecks in concurrent operations. ```python import yappi yappi.start() # Your code here yappi.stop() yappi.get_func_stats().print_all() yappi.get_thread_stats().print_all() ``` -------------------------------- ### Docker Authentication Configuration Example Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/docker/index.mdx Illustrates how to configure Docker authentication using a config file and specifying necessary tools in Pants configuration. ```toml { "credHelpers": { "europe-north1-docker.pkg.dev": "gcloud" } } [docker] env_vars = ["DOCKER_CONFIG=%(homedir)s/.docker"] ``` -------------------------------- ### Use Get(OutputType) instead of OutputTypeRequest Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/common-plugin-tasks/plugin-upgrade-guide.mdx Simplify Get requests for system binaries by using `Get(OutputType)` directly, deprecating the older `Get(OutputType, OutputTypeRequest)` or `Get(OutputType, {})` syntax. ```python from pants.core.util_rules.system_binaries import ZipBinary, ZipBinaryRequest from pants.engine.rules import Get, rule class MyOutput: pass @rule async def my_rule(zip_binary: ZipBinary) -> MyOutput: return MyOutput() @rule async def my_rule_lazy() -> MyOutput: zip_binary = await Get(ZipBinary, ZipBinaryRequest()) return MyOutput() ``` -------------------------------- ### Example Imports with Marker Files Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/source-roots.mdx When using marker files like `setup.py` to denote source roots, imports should reference the top-level project directory (e.g., `server` or `utils`), not nested subdirectories. ```python import server.app from utils.strutil import capitalize ``` -------------------------------- ### Install system debug symbols Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/development/debugging-and-benchmarking.mdx Install debug symbols for your system's Python installation. This is required for gdb to provide meaningful backtraces for Python code. ```bash sudo apt install python3-dbg ``` -------------------------------- ### Install Homebrew via SSH Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/releases/github-actions-macos-arm64-runners.mdx Install Homebrew, a package manager for macOS. The command downloads and runs the official installation script. It also configures the shell environment for Homebrew. ```shell # 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)" ``` -------------------------------- ### Set up Example Test Subsystem Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/common-plugin-tasks/run-tests.mdx Define a `Subsystem` for your test runner, including a `skip` option. This subsystem will manage options related to your test runner. ```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") ``` -------------------------------- ### Snapshot object example Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/the-rules-api/file-system.mdx An example of a `Snapshot` object, which composes a `Digest` with lists of files and directories. ```python Snapshot( digest=Digest( fingerprint="21bcd9fcf01cc67e9547b7d931050c1c44d668e7c0eda3b5856aa74ad640098b", serialized_bytes_length=162, ), files=("f.txt", "grandparent/parent/c.txt"), dirs=("grandparent", "grandparent/parent"), ) ``` -------------------------------- ### Install Pants with `wget` Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/getting-started/installing-pants.mdx Download Pants using `wget`, specifying the release version and target OS/architecture. This method involves downloading both the binary and its SHA256 checksum, verifying the checksum, and then moving and making the binary executable. ```bash # os-arch: `linux-aarch64`, `linux-x86_64`, or `macos-aarch64` wget https://github.com/pantsbuild/scie-pants/releases/download/{release_version}/scie-pants-{os-arch} wget https://github.com/pantsbuild/scie-pants/releases/download/{release_version}/scie-pants-{os-arch}.sha256 # Verify SHA with `shasum -a 256` or `sha256sum` shasum -a 256 -c ./*.sha256 # Allow running pants mv scie-pants-{os-arch} ~/.local/bin/pants chmod +x ~/.local/bin/pants ``` -------------------------------- ### Example Terraform Module Structure Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/terraform/index.mdx A basic example of a Terraform module with a resource and its corresponding lockfile. ```hcl resource "null_resource" "dep" {} ``` ```hcl # This file is maintained automatically by "terraform init" ``` -------------------------------- ### Install Pants with Homebrew Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/getting-started/installing-pants.mdx Use Homebrew to install Pants on macOS systems, particularly for ARM architectures. ```bash brew install pantsbuild/tap/pants ``` -------------------------------- ### Create a PEX binary with a specific entry point Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/goals/package.mdx Use the `pex_binary` target to create a PEX file. You can specify the entry point for your application, which can be a module or a specific function within a module. ```python pex_binary( name="app_with_func", entry_point="helloworld.main:my_func", ) ``` ```python pex_binary( name="3rdparty_app", entry_point="bandit:main", ) ``` -------------------------------- ### Install pyenv via Homebrew Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/releases/github-actions-macos-arm64-runners.mdx Install pyenv, a tool for managing multiple Python versions, using Homebrew. ```shell # Install pyenv % brew install pyenv ``` -------------------------------- ### Example Usage of Project Version Goal Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/tutorials/advanced-plugin-concepts.mdx Demonstrates how to use the `project-version` goal to retrieve and display project version information. The output can be plain text or JSON, and can optionally validate against the Git tag. ```bash $ pants project-version myapp: [INFO] Initializing scheduler... [INFO] Scheduler initialized. {"path": "myapp/VERSION", "version": "0.0.1"} ``` -------------------------------- ### Bootstrap Rust Engine with Nix Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/development/setting-up-pants.mdx Use Nix to easily set up the Pants development environment, including all necessary dependencies. This command downloads dependencies and starts a shell with a configured PATH. ```bash nix-shell ``` -------------------------------- ### Install AWS CLI via Homebrew Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/releases/github-actions-macos-arm64-runners.mdx Install the AWS Command Line Interface using Homebrew, which is necessary for interacting with AWS services. ```shell # Install the AWS CLI % brew install awscli ``` -------------------------------- ### Activate Kubernetes Backend Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/kubernetes/index.mdx Enable the experimental Kubernetes backend by adding it to `pants.toml`. ```toml [GLOBAL] backend_packages = [ ... "pants.backend.experimental.k8s", ] ``` -------------------------------- ### Install Pants with GitHub CLI Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/getting-started/installing-pants.mdx Download the Pants binary using the GitHub CLI, specifying the desired operating system and architecture. Includes steps for verifying attestations and making the binary executable. ```bash # Using `macos-aarch64` here, other options are: `linux-aarch64`, `linux-x86_64` gh release download \ --repo pantsbuild/scie-pants \ --pattern "*macos-aarch64" \ --output ~/.local/bin/pants # Check attestations for "✓ Verification succeeded!" gh attestation verify ~/.local/bin/pants \ --repo pantsbuild/scie-pants \ --signer-repo pantsbuild/scie-pants # Allow running pants chmod +x ~/.local/bin/pants ``` -------------------------------- ### Get Help for a Specific Goal Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/command-line-help.mdx Use `pants help ` to get detailed information about a specific goal, including its options and related subsystems. ```text $ pants help test `test` goal options ------------------- Run tests. Config section: [test] --[no-]test-debug PANTS_TEST_DEBUG debug default: False current value: False Run tests sequentially in an interactive process. This is necessary, for example, when you add breakpoints to your code. --[no-]test-force PANTS_TEST_FORCE force default: False current value: False Force the tests to run, even if they could be satisfied from cache. ... Related subsystems: coverage-py, download-pex-bin, pants-releases, pex, pex-binary-defaults, pytest, python-infer, python-native-code, python-repos, python-setup, setup-py-generation, setuptools, source, subprocess-environment ``` -------------------------------- ### Plugin register.py Example Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/overview.mdx A `register.py` file defines the `rules` and `target_types` for a Pants plugin backend. This example shows how to register custom rules and target types. ```python from plugin1.lib import CustomTargetType, rule1, rule2 def rules(): return [rule1, rule2] def target_types(): return [CustomTargetType] ``` -------------------------------- ### Set up Homebrew, pyenv, and Rustup Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/releases/github-actions-macos-arm64-runners.mdx Configures the shell environment for the 'gha' user by adding Homebrew to the PATH and setting up pyenv for Python version management. Also installs Rust using rustup. ```shell # Set up Homebrew % echo 'export PATH=$PATH:/opt/homebrew/bin/' >> ~/.zshenv ... # 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 Python 3.9 % pyenv install 3.9.13 % pyenv global 3.9.13 ... # Install rustup % curl https://sh.rustup.rs -sSf | sh -s -- -y ``` -------------------------------- ### Activate Go Backend in pants.toml Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/go/index.mdx Activate the Go backend by adding `pants.backend.experimental.go` to the `backend_packages` in your `pants.toml` file. You may also want to set `[golang].minimum_expected_version` to ensure Pants finds a compatible Go distribution. ```toml [GLOBAL] backend_packages = ["pants.backend.experimental.go"] ``` -------------------------------- ### Get Help for a Specific Target Type Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/command-line-help.mdx Use `pants help ` to get information about a specific target type, including its valid fields and usage details. ```text ❯ pants help python_test `python_test` target -------------------- A single Python test file, written in either Pytest style or unittest style. All test util code, including `conftest.py`, should go into a dedicated `python_source` target and then be included in the `dependencies` field. (You can use the `python_test_utils` target to generate these `python_source` targets.) See [test](../python/goals/test.mdx) Valid fields: timeout type: int | None default: None A timeout (in seconds) used by each test file belonging to this target. This only applies if the option `--pytest-timeouts` is set to True. ... ``` -------------------------------- ### Start IPython REPL Without Loading Code Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/goals/repl.mdx This command starts an IPython REPL without loading any of your project's code. Useful for quick Python checks. ```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 ``` -------------------------------- ### Simulate a project with setup_tmpdir and run Pants with run_pants Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/the-rules-api/testing-plugins.mdx Use `setup_tmpdir` to create a temporary project structure and `run_pants` to execute Pants commands. This is useful for integration tests that mimic command-line usage. Assertions can be made on the `PantsResult`'s exit code, stdout, and stderr. ```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 ``` -------------------------------- ### Install Rosetta 2 via SSH Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/releases/github-actions-macos-arm64-runners.mdx Install Rosetta 2 to enable running x86_64 applications on ARM64 Macs. This command may prompt to accept a license agreement. ```shell # Install Rosetta 2, will prompt to accept a license agreement % softwareupdate --install-rosetta ``` -------------------------------- ### Enable Java and Scala Backends Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/jvm/java-and-scala.mdx Activate the experimental Java and Scala backends in your pants.toml file. Each backend can be used independently. ```toml [GLOBAL] backend_packages = [ # Each backend can be used independently, so there is no need to enable Scala if you # have a pure-Java repository (or vice versa). "pants.backend.experimental.java", "pants.backend.experimental.scala", ] ``` -------------------------------- ### Configure pyoxidizer_binary with Entry Point Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/integrations/pyoxidizer.mdx Set the `entry_point` field in the `pyoxidizer_binary` target to specify the Python module to execute when the binary is run. If omitted, it launches an interactive Python interpreter. ```python pyoxidizer_binary( name="bin", dependencies=[":dist"], entry_point="myproject.myapp", ) ``` -------------------------------- ### Migrate Get(GenerateJvmLockfileFromTool, GenerateToolLockfileSentinel) to direct invocation Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/common-plugin-tasks/plugin-upgrade-guide.mdx Update lockfile generation by invoking `GenerateJvmLockfileFromTool` directly on the tool, removing the need for `Get` with `GenerateToolLockfileSentinel`. You may need to request your `JvmToolBase`. ```python @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 @rule async def shade_jar(request: ShadeJarRequest, jdk: InternalJdk, jarjar: JarJar) -> ShadedJar: ... await Get( ToolClasspath, ToolClasspathRequest(lockfile=GenerateJvmLockfileFromTool.create(jarjar)) ) ``` -------------------------------- ### Get file paths using PathGlobs Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/the-rules-api/file-system.mdx Use `path_globs_to_paths` to get only the file and directory paths matching globs, avoiding digesting files for performance. The result has `files` and `dirs` properties. ```python from pants.engine.fs import PathGlobs, Paths from pants.engine.intrinsics import path_globs_to_paths from pants.engine.rules import rule @rule async def demo(...) -> Foo: ... paths: Paths = await path_globs_to_paths(["**/*.txt", "!ignore_me.txt"]) logger.info(paths.files) ``` -------------------------------- ### Configure Project Version Options in pants.toml Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/tutorials/advanced-plugin-concepts.mdx Demonstrates how to set plugin options, `as_json` and `match_git`, in the `pants.toml` file. This provides a persistent configuration for the project version goal. ```toml [project-version] as_json = true match_git = false ``` -------------------------------- ### Use EnvironmentName in Get Calls Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/common-plugin-tasks/plugin-upgrade-guide.mdx When running underlying rules that require an `EnvironmentName`, use the multi-parameter `Get` syntax to provide the environment transitively. This applies to rules that run processes or consume the platform. ```python Get(TestResult, {field_set: TestFieldSet, environment_name: EnvironmentName}) ``` -------------------------------- ### Enable Pants Backends Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/getting-started/initial-configuration.mdx Activate desired Pants functionality by adding backend packages to the `[GLOBAL].backend_packages` option in your `pants.toml`. This example shows how to enable Go, Python, and Black linting backends. ```toml ```toml title="pants.toml" [GLOBAL] ... backend_packages = [ "pants.backend.experimental.go", "pants.backend.python", "pants.backend.python.lint.black", ] ``` ``` -------------------------------- ### Export Editable Installs for First-Party Sources Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/setting-up-an-ide.mdx Export PEP-660 editable installs for first-party Python code within a resolve. This allows your IDE to understand and navigate your project's own source code. ```bash pants export --export-py-editable-in-resolve=python-default --resolve=python-default ``` -------------------------------- ### Enable Makeself Backend Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/shell/self-extractable-archives.mdx Activate the `makeself` backend in `pants.toml` to enable integration with the Makeself tool. ```toml [GLOBAL] backend_packages = [ ... "pants.backend.experimental.makeself", ] ``` -------------------------------- ### Install Pythons on EC2 Instance Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/releases/github-actions-linux-aarch64-runners.mdx Installs multiple Python versions (3.7-3.13) and their development headers on an Ubuntu 22.04 ARM64 instance using apt-get and a PPA. This is a prerequisite for building the custom AMI. ```bash #!/bin/bash systemctl start ssh ``` ```bash sudo apt-get install -y software-properties-common sudo add-apt-repository -y ppa:deadsnakes/ppa sudo apt-get update sudo apt-get install -y \ python3.7 python3.7-dev python3.7-venv \ python3.8 python3.8-dev python3.8-venv \ python3.9 python3.9-dev python3.9-venv \ python3.10 python3.10-dev python3.10-venv \ python3.11 python3.11-dev python3.11-venv \ python3.12 python3.12-dev python3.12-venv \ python3.13 python3.13-dev python3.13-venv ``` -------------------------------- ### Specify Goal Arguments with File Paths and Globs Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/goals.mdx Demonstrates how to provide arguments to goals using file paths, directory paths, and `::` globs for recursive selection. ```bash pants test project/tests.py ``` ```bash pants test project/utils ``` ```bash pants test project:: ``` ```bash pants package project:tests ``` ```bash pants fmt src/go:: src/py/app.py ``` ```bash pants package :: ``` ```bash pants package : ``` ```bash pants test :: -project/integration_tests ``` ```bash pants package project:: -project: ``` -------------------------------- ### Install Newer OpenSSL on macOS Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/contributions/development/setting-up-pants.mdx For macOS users, install a more modern OpenSSL version using Homebrew and update your shell configuration to ensure dependencies resolve correctly. If using Zsh, use `.zshrc` instead of `.bashrc`. ```bash brew install openssl echo 'export PATH="$(brew --prefix)/opt/openssl/bin:$PATH"' >> ~/.bashrc echo 'export LDFLAGS="-L$(brew --prefix)/opt/openssl/lib"' >> ~/.bashrc echo 'export CPPFLAGS="-I$(brew --prefix)/opt/openssl/include"' >> ~/.bashrc ``` -------------------------------- ### Use `pants help` for Built-in Documentation Source: https://context7.com/pantsbuild/pants/llms.txt Access comprehensive help for Pants goals, target types, subsystems, and options. Use specific commands to list or get detailed information. ```bash # List all available goals pants help goals # Get help on a specific goal pants help test # Get advanced options for a goal or subsystem pants help-advanced pytest # List all target types pants help targets # Get help on a specific target type pants help python_tests # List all available backends pants backends --help # List all backends including experimental pants backends --help-advanced # Get global options reference pants help global pants help-advanced global ``` -------------------------------- ### Rule with Custom Types: Shellcheck Example Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/writing-plugins/the-rules-api/concepts.mdx An example of a rule that takes custom types like `Target` and `Shellcheck` as input and returns a `LintResult`. This illustrates how rules can interact with specific domain objects within the Pants build system. ```python @rule async def run_shellcheck(target: Target, shellcheck: Shellcheck) -> LintResult: # Your logic. return LintResult(stdout=..., stderr=..., exit_code=...) ``` -------------------------------- ### Example Dependency Rule Set for Python Sources Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/validating-dependencies.mdx This example demonstrates a rule set for `python_sources`. It allows dependencies within `src/a/` and on `src/b/lib.py`, while explicitly denying all other dependencies using `!*`. An additional generic rule set handles non-Python sources to prevent fall-through. ```python # src/a/BUILD (continued from previous example) __dependencies_rules__( ( {"type": python_sources}, # We can use the target type unquoted when we don't need glob syntax "src/a/**", # May depend on anything from src/a/ "src/b/lib.py", # May depend on specific file "!*", # May not depend on anything else. This is our "catch all" rule, ensuring there will never be any fall-through, which would've been an error ), # We need another rule set, in case we have non-python sources in here, to avoid fall-through. # Sticking in a generic catch-all allow-all rule. ("*", "*"), ) ``` -------------------------------- ### Configure Dependency Rules with Inheritance Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/validating-dependencies.mdx Demonstrates how to set default dependency rules and then extend them in a subdirectory BUILD file. ```python # src/BUILD # given some parent rules: __dependencies_rules__( , , ) ``` ```python # src/subdir/BUILD # The following rules: __dependencies_rules__( , , extend=True, ) # are equivalent to: __dependencies_rules__( , , , , ) # Due to the `extend=True` flag, which inherits the parent rules after those just declared. ``` -------------------------------- ### Create a tar archive with packages and files Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/assets-and-archives.mdx Use the `archive` target to bundle built packages and loose files into a compressed archive. Specify the packages and files to include, and choose the archive format. ```python archive( name="app_with_config", packages=[":app"], files=[":production_config"], format="tar.xz", ) ``` -------------------------------- ### Configure Goal Options via Command Line Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/key-concepts/goals.mdx Shows how to set goal-specific options directly on the command line. Options can be prefixed with the goal name or, in some cases, used as a shorthand. ```bash ❯ pants help test ``` ```bash pants --test-debug test project/app_test.py ``` ```bash pants test project/app_test.py --test-debug ``` ```bash pants test --debug project/app_test.py ``` -------------------------------- ### Message File Content Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/docker/index.mdx The content of the message file used in the Docker image example. ```text Hello, Docker! ``` -------------------------------- ### Define a Kubernetes ConfigMap Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/kubernetes/index.mdx Example of a Kubernetes ConfigMap resource defined in a YAML file. ```yaml --- apiVersion: v1 kind: ConfigMap metadata: name: webpages data: index.html: | Hello pants! Hello pants! ``` -------------------------------- ### Register Entry Points for Distributions Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/python/overview/building-distributions.mdx Configure setuptools-style entry points, such as `console_scripts`, using the `entry_points` field in `python_distribution`. Pants infers dependencies on these entry points. ```python python_distribution( name="my-dist", entry_points={ "console_scripts": {"some-command": "project.app:main"}, "flake8_entry_point": { "PB1": "my_flake8_plugin:Plugin", "PB2": "my_flake8_plugin:AnotherPlugin", }, }, provides=python_artifact(...), ) ``` -------------------------------- ### Declare Dependencies in BUILD File Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/using-pants/validating-dependencies.mdx Example of declaring dependencies for a `python_sources` target in a BUILD file. ```python # src/a/BUILD python_sources(dependencies=["src/b/lib.py"], tags=["apps"]) ``` ```python # src/b/BUILD python_sources(tags=["libs"]) ``` -------------------------------- ### Example ConfigMap Template Source: https://github.com/pantsbuild/pants/blob/main/docs/docs/helm/index.mdx A standard Helm ConfigMap template that uses values from a data map. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: example-configmap data: {{- range $key, $val := .Values.data }} {{ $key | upper }}: {{ $val | quote }} {{- end }} ```