### Basic types.requirements() Setup Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/types-extension.md Example of how to use the `types.requirements()` function in `MODULE.bazel` for basic setup. It specifies the repository name, pip requirements, and the requirements text file. ```starlark types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", pip_requirements = "@pip//:requirements.bzl", requirements_txt = "//:requirements.txt", ) use_repo(types, "pip_types") ``` -------------------------------- ### py_type_library.py CLI Example Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/py-type-library.md A concrete example of running the py_type_library.py script, showing the transformation of a 'types-cachetools' package from input to output directories. ```bash python py_type_library.py \ --input-dir /path/to/types-cachetools \ --output-dir /tmp/output ``` -------------------------------- ### Setup Type Stubs with Requirements Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/README.md Integrates type stub packages into your project using Bazel extensions. This example configures requirements from a pip requirements file and excludes specific packages. ```starlark types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", pip_requirements = "@pip//:requirements.bzl", requirements_txt = "//requirements.txt", exclude_requirements = ["types-setuptools"], ) use_repo(types, "pip_types") ``` -------------------------------- ### Example Usage of managed_cache_dir Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md Demonstrates how to use the `managed_cache_dir` context manager to set up a cache directory for running mypy. ```python with managed_cache_dir(".mypy_cache", ["/upstream/.mypy_cache"]) as cache: report, errors, status = run_mypy("mypy.ini", cache, ["src/main.py"]) ``` -------------------------------- ### Manual Mypy Test Setup and Execution Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Configure the Mypy environment by setting MYPYPATH and then run Mypy manually with a configuration file and cache directory. ```bash # Set up environment export MYPYPATH=".:$(python -c 'import site; print(site.getsitepackages()[0])')" # Run mypy manually mypy --config-file mypy.ini --cache-dir /tmp/mypy_cache src/ ``` -------------------------------- ### Example mypy.ini Configuration Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/configuration.md A basic mypy.ini configuration file for use with rules_mypy. This file allows for project-specific mypy settings. ```ini [mypy] ``` -------------------------------- ### Generated types.bzl Dictionary Example Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/types-extension.md An example of the content of the generated `types.bzl` file. It shows a dictionary mapping base package requirement labels to their corresponding type library target labels. ```starlark # Example generated types.bzl types = { requirement("cachetools"): "@@pip_types//:types-cachetools", requirement("click"): "@@pip_types//:types-click", } ``` -------------------------------- ### types.requirements() with requirements.in Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/types-extension.md Demonstrates using `types.requirements()` when a `requirements.in` file is used instead of `requirements.txt`. This setup is common in projects that use tools like `pip-tools`. ```starlark types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", pip_requirements = "@pip//:requirements.bzl", requirements_txt = "//:requirements.in", ) use_repo(types, "pip_types") ``` -------------------------------- ### Setup mypy Aspect with Custom Configuration Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-aspect.md Initializes the mypy aspect with a custom mypy configuration file and enables caching and colored output. This allows for fine-grained control over mypy's behavior. ```starlark load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy( mypy_ini = "@@//:mypy.ini", cache = True, color = True, ) ``` -------------------------------- ### Mypy Aspect Usage Example Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/types.md Example of how to load and use the Mypy aspect with a generated types dictionary. ```starlark load("@pip_types//:types.bzl", "types") load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy(types = types) ``` -------------------------------- ### Type Stub Setup Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/README.md Configures type stub requirements using `types.requirements()`, specifying the name, pip requirements source, requirements file, and any packages to exclude. ```APIDOC ## Type Stub Setup ### Description This function sets up the requirements for type stubs. It allows you to define the name for the type stub repository, specify the source of pip requirements, point to a requirements file, and exclude specific packages from being included as type stubs. ### Function Signature ```starlark types.requirements( name = "", pip_requirements = "", requirements_txt = None, exclude_requirements = [], ) ``` ### Parameters - **name** (string, required): The name for the generated type stub repository. - **pip_requirements** (string, required): The Bazel label pointing to the pip requirements file. - **requirements_txt** (string, optional): Path to the `requirements.txt` file. - **exclude_requirements** (list of strings, optional): A list of package names to exclude from type stub generation. ### Example ```starlark types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", pip_requirements = "@pip//:requirements.bzl", requirements_txt = "//requirements.txt", exclude_requirements = ["types-setuptools"], ) use_repo(types, "pip_types") ``` ``` -------------------------------- ### Basic py_type_library Usage Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/py-type-library.md Example of using py_type_library with a requirement for the 'types-cachetools' package. Ensure the necessary loads are present. ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:py_type_library.bzl", "py_type_library") py_type_library( name = "types-cachetools", typing = requirement("types-cachetools"), ) ``` -------------------------------- ### Generated Types Dictionary Example Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/types.md Example of a types dictionary mapping package requirements to type library labels. Used for generating type stubs. ```starlark types = { requirement("cachetools"): "@@pip_types//:types-cachetools", requirement("click"): "@@pip_types//:types-click", requirement("pydantic"): "@@pip_types//:types-pydantic", } ``` -------------------------------- ### Mypy Aspect Configuration Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/README.md Configure the mypy() aspect for Bazel targets. This example shows how to load the aspect, define its parameters like type stub mappings, cache sharing, and output color, and register it in the .bazelrc file. ```starlark load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy( types = types, # Type stub mappings cache = True, # Share cache between targets color = True, # Colored output opt_in_tags = [], # Empty = all targets ) ``` ```bash build --aspects //tools:aspects.bzl%mypy_aspect build --output_groups=+mypy ``` -------------------------------- ### Add rules_mypy to MODULE.bazel Source: https://github.com/bazel-contrib/rules_mypy/blob/main/readme.md Add the rules_mypy dependency to your Bazel project using bzlmod. This is the recommended setup. ```starlark bazel_dep(name = "rules_mypy", version = "0.0.0") ``` -------------------------------- ### Manage Mypy Cache Directory Lifecycle Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md A context manager for handling the mypy cache directory. It merges upstream caches or creates a temporary directory. Use this to ensure proper cache setup and cleanup. ```python with managed_cache_dir(".mypy_cache", ["/dep/.mypy_cache"]) as cache: # Cache is merged and ready run_mypy(None, cache, ["src.py"]) ``` -------------------------------- ### main() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md The main entry point for the mypy runner script. It parses command-line arguments and initiates the mypy execution process. ```APIDOC ## main() ### Description Entry point for the mypy runner script. Parses command-line arguments and delegates to `run()`. ### Command-Line Arguments | Argument | Short | Type | Required | Description | |----------|-------|------|----------|-------------| | --output | | string | No | Path to write mypy output (both errors and reports) to a file. If not provided, output goes to stderr only. | | --cache-dir | -c | string | No | Path to the mypy cache directory. If provided, caches are merged and preserved. If not provided, a temporary directory is used and discarded. | | --upstream-cache | | string (repeatable) | No | Path to upstream cache directory from a dependency. Can be specified multiple times. Each is merged into the output cache. | | --mypy-ini | | string | No | Path to mypy configuration file. If provided, passed to mypy via `--config-file`. | | src | | string (variadic) | Yes | Source files to check with mypy. Can be multiple files or empty list. | ### Example Usage ```bash # Basic mypy run python mypy_runner.py src/main.py src/lib.py # With output file python mypy_runner.py --output mypy.txt src/main.py # With cache python mypy_runner.py -c .mypy_cache --output mypy.txt src/main.py # With upstream caches and config python mypy_runner.py \ --output mypy.txt \ -c .mypy_cache \ --upstream-cache ../dep1/.mypy_cache \ --upstream-cache ../dep2/.mypy_cache \ --mypy-ini mypy.ini \ src/main.py ``` ### Exit Behavior - Exits with mypy's exit status code (0 for success, non-zero for errors) - Writes errors to stderr if mypy reports errors - Uses mypy's `hard_exit()` for faster shutdown without object cleanup ``` -------------------------------- ### Manual mypy Run for Testing Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/errors.md Run mypy directly to test your configuration. Ensure the MYPYPATH environment variable is set correctly and specify the configuration file and cache directory. ```bash export MYPYPATH=".:path/to/site-packages" mypy --config-file mypy.ini --cache-dir /tmp/cache src/ ``` -------------------------------- ### Suppress type-checking 3rd party modules in mypy.ini Source: https://github.com/bazel-contrib/rules_mypy/blob/main/readme.md Example mypy.ini configuration to suppress type-checking for third-party modules. This is often necessary for effective integration. ```ini follow_imports = silent follow_imports_for_stubs = True ``` -------------------------------- ### Apply Opt-in Tag to Target Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/configuration.md Shows how to apply an opt-in tag to a `py_library` target to enable mypy execution for it, while other targets without the tag are skipped. ```starlark py_library( name = "core", srcs = ["core.py"], tags = ["typecheck"], # Mypy runs ) py_library( name = "legacy", srcs = ["legacy.py"], # No "typecheck" tag - mypy skipped in opt-in mode ) ``` -------------------------------- ### Create mypy.ini for Custom Configuration Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Configure mypy behavior by creating a mypy.ini file with desired settings. ```ini [mypy] pretty = True show_error_codes = True warn_return_any = True follow_imports = silent follow_imports_for_stubs = True explicit_package_bases = True check_untyped_defs = True [mypy-external.*] ignore_errors = True ``` -------------------------------- ### mypy_runner.managed_cache_dir() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md A context manager for handling the lifecycle of the cache directory. It can either use a provided directory or create a temporary one, ensuring proper setup and cleanup. ```APIDOC ## mypy_runner.managed_cache_dir() ### Description Context manager for cache directory lifecycle. ### Signature ```python @contextlib.contextmanager def managed_cache_dir( cache_dir: Optional[str], upstream_caches: list[str], ) -> Generator[str, Any, Any]: ``` ### Type context manager ### Parameters: #### Parameters - **cache_dir** (str | None) - Target cache dir (or None for temporary) - **upstream_caches** (list[str]) - Upstream caches to merge ### Yields: `str` - Path to cache directory ### Behavior: - If `cache_dir` provided: merges upstream caches into it - If `cache_dir` is None: creates temporary directory - Cleanup depends on whether directory is permanent or temporary ### Example: ```python with managed_cache_dir(".mypy_cache", ["/dep/.mypy_cache"]) as cache: # Cache is merged and ready run_mypy(None, cache, ["src.py"]) ``` ``` -------------------------------- ### Basic Mypy Run Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md Executes mypy on specified source files. ```bash # Basic mypy run python mypy_runner.py src/main.py src/lib.py ``` -------------------------------- ### Usage of mypy.bzl Public API Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/module-structure.md Demonstrates how to load and use the public `mypy` and `mypy_cli` symbols from the `mypy/mypy.bzl` file. ```Starlark load("@rules_mypy//mypy:mypy.bzl", "mypy", "mypy_cli") ``` -------------------------------- ### py_type_library._clean Helper Function Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md Removes the '-stubs' suffix from a package name. Use this function when you need to get the original package name from a stub package name. ```python def _clean(package: str) -> str: """Removes -stubs suffix from package name.""" return package.removesuffix("-stubs") ``` ```python _clean("cachetools-stubs") # Returns "cachetools" _clean("click") # Returns "click" ``` -------------------------------- ### Run mypy build command Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Execute the Bazel build command to trigger mypy checks. ```bash bazel build //... ``` -------------------------------- ### Setup mypy Aspect for Opt-in Mode Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-aspect.md Configures the mypy aspect to only type check targets explicitly tagged with 'typecheck'. This is useful for selectively enabling type checking on specific parts of a project. ```starlark load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy( opt_in_tags = ["typecheck"], suppression_tags = [], ) ``` -------------------------------- ### py_type_library with Public Visibility Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/py-type-library.md Demonstrates using py_type_library with a direct requirement and setting public visibility. Includes necessary load statements. ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:py_type_library.bzl", "py_type_library") py_type_library( name = "types-click", typing = requirement("types-click"), visibility = ["//visibility:public"], ) ``` -------------------------------- ### Run Mypy Aspect and View Output Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Build a specific target with the Mypy aspect and then view the generated output file. ```bash # Run specific target bazel build //src:my_lib --aspects //tools:aspects.bzl%mypy_aspect --output_groups=+mypy # Find output file find bazel-bin -name "*.mypy_stdout" -type f # View results cat bazel-bin/src/my_lib.mypy_stdout ``` -------------------------------- ### Setup mypy Aspect with Custom Suppression Tags Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-aspect.md Configures the mypy aspect to skip type checking for targets tagged with 'no-mypy', 'no-checks', or 'experimental'. This allows selective exclusion of targets from type checking. ```starlark load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy( suppression_tags = ["no-mypy", "no-checks", "experimental"], ) ``` -------------------------------- ### PyTypeLibraryInfo Provider Definition Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/py-type-library.md Shows the definition of the PyTypeLibraryInfo provider, which includes the directory containing the transformed site-packages. ```starlark PyTypeLibraryInfo = provider( fields = { "directory": "Directory containing site-packages.", } ) ``` -------------------------------- ### Mypy Import Resolution Error: Cannot Find Module Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/errors.md This error occurs when a package import cannot be resolved via MYPYPATH. Ensure the package is installed, type stubs are available, or the package is correctly configured in your build dependencies. ```text error: Cannot find implementation or library stub for module named "X" ``` -------------------------------- ### Configure mypy_cli with Bazel Tags Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/configuration.md Apply Bazel tags to the produced py_binary target. Use tags like 'manual' to prevent automatic builds. ```starlark mypy_cli( name = "mypy_cli", tags = ["manual"], # Prevent automatic build ) ``` -------------------------------- ### Mypy Type Stub Issue: Missing Type Stubs Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/errors.md This error indicates that a required type package is not found in the types mapping. Add the package to your types dictionary, install the corresponding types package, or configure the types extension to include it. ```text error: Library stubs not installed for ... ``` -------------------------------- ### Mypy Run with Output File Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md Executes mypy and directs the output to a specified file. ```bash # With output file python mypy_runner.py --output mypy.txt src/main.py ``` -------------------------------- ### Run Mypy with Bazel-optimized flags Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md Executes mypy with specific flags optimized for Bazel builds. Requires a cache directory and source files. Returns the report, errors, and status code. ```python def run_mypy( mypy_ini: Optional[str], cache_dir: str, srcs: list[str], ) -> tuple[str, str, int]: """Executes mypy with standard Bazel-optimized configuration.""" # Mypy flags applied: # --skip-cache-mtime-checks # --incremental # --cache-dir {cache_dir} # --explicit-package-bases # --fast-module-lookup pass ``` -------------------------------- ### Enabling Verbose Bazel Output Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/errors.md Use the -s flag with bazel build to display all action command lines. This is useful for debugging and understanding the execution flow of mypy aspects. ```bash bazel build --aspects //tools:aspects.bzl%mypy_aspect \ -s \ --output_groups=+mypy \ //... ``` -------------------------------- ### Mypy Run with Cache Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md Executes mypy using a local cache directory and writes output to a file. ```bash # With cache python mypy_runner.py -c .mypy_cache --output mypy.txt src/main.py ``` -------------------------------- ### run() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md The core execution function that manages cache operations and invokes mypy. ```APIDOC ## run() ### Description Main execution function that coordinates cache management and mypy execution. ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | output | str or None | File path to write output to. If None, no file is written. | | cache_dir | str or None | Mypy cache directory. If None, a temporary directory is used. | | upstream_caches | list[str] | List of upstream cache paths to merge. Empty list if none provided. | | mypy_ini | str or None | Path to mypy configuration file. If None, no config file is used. | | srcs | list[str] | List of source files to check. If empty, skips mypy execution and exits with status 0. | ### Behavior 1. If srcs list is empty, skips mypy execution and writes empty output 2. Uses `managed_cache_dir()` context manager to handle cache directory setup 3. Calls `run_mypy()` to execute mypy 4. Writes output to file if specified 5. Exits with mypy's status code ``` -------------------------------- ### Mypy Run with Upstream Caches and Config Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md Executes mypy with a local cache, multiple upstream caches, and a mypy configuration file. ```bash # With upstream caches and config python mypy_runner.py \ --output mypy.txt \ -c .mypy_cache \ --upstream-cache ../dep1/.mypy_cache \ --upstream-cache ../dep2/.mypy_cache \ --mypy-ini mypy.ini \ src/main.py ``` -------------------------------- ### Check Multiple Targets with Bazel Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Builds multiple specified targets or packages. ```bash bazel build //src/core:... //src/utils:... ``` -------------------------------- ### mypy_cli() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-cli.md Creates a Python binary target that wraps the mypy command-line interface. This allows for customization of the mypy version, Python version, and inclusion of mypy plugins. ```APIDOC ## mypy_cli() ### Description Creates a Python binary target that wraps the mypy command-line interface. This allows for customization of the mypy version, Python version, and inclusion of mypy plugins. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (string) - Required - The name of the `py_binary` target to create. - **deps** (list[label], optional) - `[]` - Additional dependencies to include with mypy. Commonly used for mypy plugins referenced in mypy configuration. Must match the Python version of the binary. - **mypy_requirement** (label, optional) - `requirement("mypy")` from rules_mypy's pinned dependencies - The mypy requirement label to use. Override to use a different version or source. Typically obtained from rules_python's requirement macro. - **python_version** (string, optional) - `"3.12"` - The Python version to use for the binary. Pass `None` to use the default Python toolchain version. Must match the Python version of dependencies. - **tags** (list[string], optional) - `None` - Bazel tags to apply to the produced `py_binary` target. ### Returns No return value. Creates a `py_binary` target with the specified name. ### Example Usage #### Basic Custom CLI ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli", ) ``` #### With Custom mypy Version ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli", mypy_requirement = requirement("mypy-1.8.0"), ) ``` #### With mypy Plugins For a mypy configuration that uses plugins (e.g., pydantic plugin): ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli", mypy_requirement = requirement("mypy"), deps = [ requirement("pydantic"), ], ) ``` Then reference in aspect: ```starlark load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy( mypy_cli = ":mypy_cli", types = types, ) ``` #### With Custom Python Version ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli_py311", mypy_requirement = requirement("mypy"), python_version = "3.11", ) ``` ### Behavior - Creates a `py_binary` target that runs `@rules_mypy//mypy/private:mypy_runner.py` - Visibility is set to `public` for use as an `--aspects` executable - The produced binary is executable via Bazel and accepts mypy_runner.py command-line arguments - Compatible with the `mypy` aspect's `mypy_cli` parameter ### Related Functions - [`mypy()`](./mypy-aspect.md) - Use the `mypy_cli` parameter to reference the produced target ### Source Location `mypy/private/mypy.bzl` lines 301-328 ``` -------------------------------- ### MYPYPATH Construction Order Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/architecture.md Details the prioritized order in which directories are added to the MYPYPATH environment variable for mypy to resolve imports correctly. ```text 1. "." # Current directory (checked first) 2. types/site-packages # Type stubs (must be first for resolution) 3. external/site-packages # External dependencies 4. first_party_imports # First-party packages with custom imports 5. generated_dirs # Generated file directories 6. generated_imports_dirs # Generated import directories 7. pyi_dirs # .pyi stub directories ``` -------------------------------- ### Run Mypy Function Signature Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md Executes mypy with standard configurations optimized for Bazel. It takes parameters for mypy configuration, cache directory, and source files, returning the mypy output, errors, and exit status. ```python def run_mypy( mypy_ini: Optional[str], cache_dir: str, srcs: list[str] ) -> tuple[str, str, int]: ``` -------------------------------- ### Mypy Cache Performance With Cache Propagation Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/architecture.md Demonstrates the performance improvement achieved by propagating Mypy caches. Subsequent builds are significantly faster as they reuse previously computed cache data. ```text pkg_a: 10s (cache written) pkg_b → pkg_a: 7s (reuses cache) pkg_c → pkg_b → pkg_a: 5s (reuses merged cache) Total: 22s ``` -------------------------------- ### mypy_runner.main() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md Main entry point for the mypy runner. This function parses command-line arguments and delegates the actual execution to the `run()` function. It is designed to be called directly from the command line. ```APIDOC ## mypy_runner.main() ### Description Main entry point for the mypy runner. Parses arguments and delegates to `run()`. ### Signature ```python def main() -> None: ``` ### Type entry point function ### Command-line arguments: - `--output` (Path to output file) - `-c, --cache-dir` (Path to cache directory) - `--upstream-cache` (Path to upstream cache, repeatable) - `--mypy-ini` (Path to mypy config file) - `src` (variadic, Source files to check) ``` -------------------------------- ### Run Mypy with Verbose Output Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Execute a Bazel build with verbose flags and filter the output to show only Mypy-related messages. ```bash bazel build -s //... \ --aspects //tools:aspects.bzl%mypy_aspect \ --output_groups=+mypy 2>&1 | grep mypy ``` -------------------------------- ### Check Specific Package with Bazel Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Builds all targets within a specified package. ```bash bazel build //src/core/... ``` -------------------------------- ### Define Custom Mypy CLI and Aspect Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/configuration.md Loads requirements, defines a custom mypy CLI using a specific mypy version and dependencies, and then creates a mypy aspect using this custom CLI. ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy", "mypy_cli") mypy_cli( name = "mypy_cli", mypy_requirement = requirement("mypy-1.8.0"), deps = [requirement("pydantic")], ) mypy_aspect = mypy(mypy_cli = ":mypy_cli") ``` -------------------------------- ### Configure Custom Mypy CLI Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/README.md Sets up a custom mypy CLI tool within Bazel. This allows specifying the mypy requirement, additional dependencies, and the Python version to use. ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli", mypy_requirement = requirement("mypy"), deps = [requirement("pydantic")], python_version = "3.12", ) ``` -------------------------------- ### Configure mypy_cli with Dependencies Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/configuration.md Use this snippet to configure the mypy_cli aspect, specifying additional dependencies like mypy plugins. Ensure the Python version of dependencies matches the binary. ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli", deps = [ requirement("pydantic"), requirement("sqlalchemy"), ], ) ``` -------------------------------- ### Create BUILD file for custom mypy CLI Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Define a custom mypy CLI target in a BUILD file, specifying mypy and plugin requirements. ```starlark # tools/BUILD.bazel load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli", mypy_requirement = requirement("mypy"), deps = [ requirement("pydantic"), ], ) ``` -------------------------------- ### BuildKite Mypy Integration Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Sets up a BuildKite job to execute Mypy type checking using Bazel. ```yaml steps: - label: "Type Check" command: | bazel build \ --aspects //tools:aspects.bzl%mypy_aspect \ --output_groups=+mypy \ //... ``` -------------------------------- ### Usage of py_type_library.bzl Public API Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/module-structure.md Demonstrates how to load and use the `py_type_library` rule from `mypy/py_type_library.bzl` to create type libraries. ```Starlark load("@rules_mypy//mypy:py_type_library.bzl", "py_type_library") py_type_library( name = "types-cachetools", typing = requirement("types-cachetools"), ) ``` -------------------------------- ### Mypy Configuration Error: File Not Found Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/errors.md This error arises when the path specified for the mypy_ini parameter does not exist. Verify that the path is correct and absolute, using the '@@' prefix for the root repository if necessary. ```starlark mypy_aspect = mypy(mypy_ini = "@@//:mypy.ini") ``` -------------------------------- ### Access MypyCacheInfo Directory Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/types.md Demonstrates how to access the cache directory from a MypyCacheInfo provider. This is typically done in an aspect or rule implementation. ```starlark # In aspect or rule implementation if MypyCacheInfo in dep: cache_path = dep[MypyCacheInfo].directory.path ``` -------------------------------- ### run_mypy() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md Executes the mypy type checker with configurations optimized for Bazel environments. ```APIDOC ## run_mypy() ### Description Executes mypy with standard configurations optimized for Bazel. ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | mypy_ini | str or None | Path to mypy configuration file. | | cache_dir | str | Path to mypy cache directory. | | srcs | list[str] | List of source files to check. | ### Returns A tuple containing the mypy report (str), errors (str), and exit status code (int). ``` -------------------------------- ### py_type_library.main() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md CLI for transforming type stub packages. It reads packages from an input directory and outputs them to a specified directory with a transformed structure. ```APIDOC ## py_type_library.main() ### Description CLI for transforming type stub packages. It reads packages from an input directory and outputs them to a specified directory with a transformed structure. ### Method CLI Command ### Parameters #### Command Line Options - **--input-dir** (string) - Required - Input directory with site-packages - **--output-dir** (string) - Required - Output directory for transformed packages ### Behavior 1. Reads packages from `{input-dir}/site-packages` 2. For each package, copies to output with `-stubs` suffix removed 3. Creates output structure: `{output-dir}/site-packages/{cleaned-names}` ``` -------------------------------- ### py_type_library.py CLI Tool Usage Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/py-type-library.md Basic command-line usage for the py_type_library.py script, specifying input and output directories for package transformation. ```bash python py_type_library.py --input-dir --output-dir ``` -------------------------------- ### Mypy Aspect Execution Flow Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/architecture.md Illustrates the step-by-step process of the mypy aspect when applied to a Python target, from initial checks to the final execution of mypy. ```text Target (py_library) ↓ [mypy_impl: Aspect function called] ├─ Check: Target in root workspace? ├─ Check: Has PyInfo provider? ├─ Check: Not suppressed by tags? ├─ Check: Satisfies opt-in tags? ├─ Check: Has .py/.pyi sources? ↓ [Gather inputs] ├─ Collect source files (.py, .pyi) ├─ Collect dependencies ├─ Extract imports and paths ├─ Collect upstream caches ├─ Collect type stub packages ↓ [Build MYPYPATH] ├─ Type stub directories ├─ External site-packages ├─ First-party imports ├─ Generated file directories ↓ [Execute mypy] └─ Run mypy_runner.py with MYPYPATH ├─ Merge upstream caches ├─ Run mypy with incremental cache ├─ Write output └─ Return result ``` -------------------------------- ### Basic mypy_cli Macro Usage Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-cli.md Creates a basic mypy_cli target with default settings. This is the simplest way to generate a custom mypy executable. ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli", ) ``` -------------------------------- ### MyPy Configuration Settings Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/configuration.md This snippet shows common MyPy configuration options relevant to rules_mypy. These settings control output verbosity, import resolution, and type checking behavior. ```ini pretty = True show_error_codes = True warn_return_any = True warn_unused_configs = True # Import handling (required for rules_mypy) follow_imports = silent follow_imports_for_stubs = True # Module resolution explicit_package_bases = True # Type checking check_untyped_defs = True disallow_incomplete_defs = True disallow_untyped_defs = True # Exclude 3rd party packages [mypy-external.*] ignore_errors = True ``` -------------------------------- ### mypy_cli with Plugins and Aspect Reference Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-cli.md Configures a mypy_cli target to include mypy plugins and demonstrates how to reference this custom CLI within the mypy aspect. This is essential for projects using type checking plugins like pydantic. ```starlark load("@pip//:requirements.bzl", "requirement") load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy_cli", mypy_requirement = requirement("mypy"), deps = [ requirement("pydantic"), ], ) then reference in aspect: load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy( mypy_cli = ":mypy_cli", types = types, ) ``` -------------------------------- ### types.requirements() with Excluded Packages Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/types-extension.md Shows how to use the `exclude_requirements` parameter in `types.requirements()` to skip specific packages during type library generation. This is useful for packages that lack type stubs. ```starlark types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", pip_requirements = "@pip//:requirements.bzl", requirements_txt = "//:requirements.txt", exclude_requirements = [ "types-setuptools", "mypy-extensions", ], ) use_repo(types, "pip_types") ``` -------------------------------- ### Register Mypy Aspect in .bazelrc (Opt-in) Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/configuration.md Configure .bazelrc to opt-in to the mypy aspect using a build configuration flag. This allows running mypy only when explicitly requested. ```bash # Only run mypy when explicitly requested build:mypy --aspects //tools:aspects.bzl%mypy_aspect build:mypy --output_groups=+mypy ``` -------------------------------- ### Configure mypy with mypy.ini Source: https://github.com/bazel-contrib/rules_mypy/blob/main/readme.md Customize mypy's behavior by providing a label for a mypy configuration file to the mypy aspect factory. The label must be absolute. ```starlark load("@pip_types//:types.bzl", "types") load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy( mypy_ini = "@@//:mypy.ini", types = types, ) ``` -------------------------------- ### Mypy Runner Main Function Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/mypy-runner.md The main entry point for the mypy runner script. It parses command-line arguments and delegates execution to the run() function. Supports arguments for output, cache directory, upstream caches, mypy configuration, and source files. ```python def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--output", required=False) parser.add_argument("-c", "--cache-dir", required=False) parser.add_argument("--upstream-cache", required=False, action="append") parser.add_argument("--mypy-ini", required=False) parser.add_argument("src", nargs="*") args = parser.parse_args() ... ``` -------------------------------- ### mypy/mypy.bzl Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/module-structure.md Provides the public API for interacting with the mypy rule, including an aspect factory and a custom CLI macro. ```APIDOC ## mypy/mypy.bzl ### Description Provides the public API for interacting with the mypy rule, including an aspect factory and a custom CLI macro. ### Exports #### Functions - **mypy** (function) - Aspect factory that creates a mypy type-checking aspect. - **mypy_cli** (macro) - Creates a custom mypy CLI executable. ### Usage ```starlark load("@rules_mypy//mypy:mypy.bzl", "mypy", "mypy_cli") ``` ``` -------------------------------- ### Create Custom Mypy CLI Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md Use this function to create a custom mypy CLI executable. You can specify additional dependencies and the Python version for the CLI. ```starlark load("@rules_mypy//mypy:mypy.bzl", "mypy_cli") mypy_cli( name = "mypy", python_version = "3.12", ) ``` -------------------------------- ### Configure .bazelrc for mypy Aspect Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Register the mypy aspect and optionally enable mypy output by default in your .bazelrc file. ```bash build --aspects //tools:aspects.bzl%mypy_aspect # Enable mypy output by default (optional) build --output_groups=+mypy ``` -------------------------------- ### mypy_runner.run() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md Orchestrates the cache management and Mypy execution process. This function takes various configuration options and source files, manages the cache lifecycle, and invokes `run_mypy`. ```APIDOC ## mypy_runner.run() ### Description Main execution function that coordinates cache and mypy execution. ### Signature ```python def run( output: Optional[str], cache_dir: Optional[str], upstream_caches: list[str], mypy_ini: Optional[str], srcs: list[str], ) -> None: ``` ### Type orchestration function ### Parameters: #### Parameters - **output** (str | None) - Output file path - **cache_dir** (str | None) - Cache directory path - **upstream_caches** (list[str]) - Upstream cache paths - **mypy_ini** (str | None) - Config file path - **srcs** (list[str]) - Source files to check ### Behavior: 1. If `srcs` is empty, exit with status 0 2. Use `managed_cache_dir` to handle cache lifecycle 3. Call `run_mypy` to execute mypy 4. Write output to file if specified 5. Exit with mypy's status code ``` -------------------------------- ### Check Specific Target with Bazel Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Builds a single, specific target within the project. ```bash bazel build //src/core:main ``` -------------------------------- ### mypy_runner.run_mypy() Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/function-reference.md Executes Mypy with a standard Bazel-optimized configuration. This function is responsible for running the Mypy tool itself, applying specific flags for performance and integration. ```APIDOC ## mypy_runner.run_mypy() ### Description Executes mypy with standard Bazel-optimized configuration. ### Signature ```python def run_mypy( mypy_ini: Optional[str], cache_dir: str, srcs: list[str], ) -> tuple[str, str, int]: ``` ### Type execution function ### Parameters: #### Parameters - **mypy_ini** (str | None) - Config file path - **cache_dir** (str) - Cache directory path - **srcs** (list[str]) - Source files ### Returns: `tuple` of (report, errors, status_code) ### Mypy flags applied: - `--skip-cache-mtime-checks` - `--incremental` - `--cache-dir {cache_dir}` - `--explicit-package-bases` - `--fast-module-lookup` ``` -------------------------------- ### Run mypy in opt-in mode Source: https://github.com/bazel-contrib/rules_mypy/blob/main/readme.md Configure mypy to run only on targets explicitly tagged with specific opt-in tags. This allows for incremental addition of type checking to a codebase. ```starlark load("@rules_mypy//mypy:mypy.bzl", "mypy") mypy_aspect = mypy( opt_in_tags = ["typecheck"], types = types, ) ``` -------------------------------- ### Configure types repository with rules_python Source: https://github.com/bazel-contrib/rules_mypy/blob/main/readme.md Optionally configure a repository for third-party types/stubs packages using rules_python's pip integration. This helps improve mypy's type checking. ```starlark types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", # `@pip` in the next line corresponds to the `hub_name` when using # rules_python's `pip.parse(...)`. pip_requirements = "@pip//:requirements.bzl", # also legal to pass a `requirements.in` here requirements_txt = "//:requirements.txt", ) use_repo(types, "pip_types") ``` -------------------------------- ### Core Aspect Implementation in mypy/private/mypy.bzl Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/module-structure.md This snippet shows the core functions and providers within the private `mypy/private/mypy.bzl` file, including the aspect implementation and helper functions. This module is not intended for direct use. ```Starlark # Core aspect implementation mypy = _mypy # Aspect factory - creates the mypy aspect mypy_cli = _mypy_cli # Creates custom mypy CLI executable _mypy_impl = _mypy_impl # Aspect implementation _extract_import_dir = _extract_import_dir # Extract import path from target _imports = _imports # Get imports from PyInfo provider _extract_imports = _extract_imports # Extract import directories from target _should_ignore_import = _should_ignore_import # Check if import should be ignored _opt_out = _opt_out # Check suppression tags _opt_in = _opt_in # Check opt-in tags ``` -------------------------------- ### Configure types Extension Requirements Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/configuration.md Configure the `types.requirements` extension to generate py_type_library rules and types.bzl mappings. Specify the requirements file and exclude unnecessary packages. ```starlark types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", pip_requirements = "@pip//:requirements.bzl", requirements_txt = "//:requirements.txt", exclude_requirements = [ "types-setuptools", "mypy-extensions", ], ) use_repo(types, "pip_types") ``` -------------------------------- ### Update MODULE.bazel for Type Stubs Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/integration-guide.md Integrate rules_mypy and rules_python, configure Python toolchain, and set up pip and types extensions for type stub management. ```starlark bazel_dep(name = "rules_mypy", version = "0.0.0") bazel_dep(name = "rules_python", version = "1.1.0") python = use_extension("@rules_python//python/extensions:python.bzl", "python") python.toolchain( is_default = True, python_version = "3.12", ) pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip") pip.parse( hub_name = "pip", python_version = "3.12", requirements_by_platform = { "//requirements:requirements.txt": "*", }, ) use_repo(pip, "pip") # Add types extension types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", pip_requirements = "@pip//:requirements.bzl", requirements_txt = "//requirements:requirements.txt", ) use_repo(types, "pip_types") ``` -------------------------------- ### Customize mypy version and include plugins Source: https://github.com/bazel-contrib/rules_mypy/blob/main/readme.md Customize the mypy version and include plugins by constructing a custom mypy CLI using rules_python's requirements resolution. This is done in a BUILD file. ```starlark # in a BUILD file load("@pip//:requirements.bzl", "requirements") # '@pip' must match configured pip hub_name load("@rules_mypy//mypy:mypy.bzl", "mypy", "mypy_cli") mypy_cli( name = "mypy_cli", mypy_requirement = requirement("mypy"), ) ``` -------------------------------- ### Usage of types.bzl Public API Source: https://github.com/bazel-contrib/rules_mypy/blob/main/_autodocs/api-reference/module-structure.md Illustrates how to load and use the `types` module extension from `mypy/types.bzl`, including configuring requirements for type stub generation. ```Starlark load("@rules_mypy//mypy:types.bzl", "types") types = use_extension("@rules_mypy//mypy:types.bzl", "types") types.requirements( name = "pip_types", pip_requirements = "@pip//:requirements.bzl", requirements_txt = "//:requirements.txt", ) use_repo(types, "pip_types") ```