### pre-commit init-templatedir example (Unix) Source: https://pre-commit.com/ Installs hook scripts in a directory for use with `git config init.templateDir`. This example is for Unix-like systems using '~'. ```bash git config --global init.templateDir ~/.git-template pre-commit init-templatedir ~/.git-template ``` -------------------------------- ### pre-commit init-templatedir example (Windows cmd.exe) Source: https://pre-commit.com/ Installs hook scripts in a directory for use with `git config init.templateDir`. This example is for Windows cmd.exe using '%HOMEPATH%'. ```bash pre-commit init-templatedir %HOMEPATH%\.git-template ``` -------------------------------- ### pre-commit init-templatedir example (Windows PowerShell) Source: https://pre-commit.com/ Installs hook scripts in a directory for use with `git config init.templateDir`. This example is for Windows PowerShell using '$HOME'. ```bash pre-commit init-templatedir $HOME\.git-template ``` -------------------------------- ### Generate Sample pre-commit Configuration Source: https://pre-commit.com/ Creates a sample `.pre-commit-config.yaml` file to help users get started with pre-commit configuration. ```bash pre-commit sample-config ``` -------------------------------- ### pre-commit autoupdate example config Source: https://pre-commit.com/ Example .pre-commit-config.yaml demonstrating how to specify repositories and hooks for pre-commit. ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.1.0 hooks: - id: trailing-whitespace - repo: https://github.com/asottile/pyupgrade rev: v1.25.0 hooks: - id: pyupgrade args: [--py36-plus] ``` -------------------------------- ### Verify default hook installation Source: https://pre-commit.com/ Running the install command after setting default_install_hook_types will install the specified hooks. ```bash $ pre-commit install pre-commit installed at .git/hooks/pre-commit pre-commit installed at .git/hooks/pre-push pre-commit installed at .git/hooks/commit-msg ``` -------------------------------- ### Install pre-commit using pip Source: https://pre-commit.com/ Install the pre-commit package manager using pip. This is the primary method for installation. ```bash pip install pre-commit ``` -------------------------------- ### Install and Run pre-commit Source: https://pre-commit.com/ Commands to initialize pre-commit in a repository and the resulting output when committing changes. ```bash $ pre-commit install pre-commit installed at /home/asottile/workspace/pytest/.git/hooks/pre-commit $ git commit -m "Add super awesome feature" black....................................................................Passed blacken-docs.........................................(no files to check)Skipped Trim Trailing Whitespace.................................................Passed Fix End of Files.........................................................Passed Check Yaml...........................................(no files to check)Skipped Debug Statements (Python)................................................Passed Flake8...................................................................Passed Reorder python imports...................................................Passed pyupgrade................................................................Passed rst ``code`` is two backticks........................(no files to check)Skipped rst..................................................(no files to check)Skipped changelog filenames..................................(no files to check)Skipped [main 146c6c2c] Add super awesome feature 1 file changed, 1 insertion(+) ``` -------------------------------- ### pre-commit install Source: https://pre-commit.com/ Installs the pre-commit script into the local repository's git hooks. It can optionally overwrite existing hooks and install hook environments immediately. ```APIDOC ## pre-commit install [options] Install the pre-commit script. ### Options - `-f`, `--overwrite`: Replace any existing git hooks with the pre-commit script. - `--install-hooks`: Also install environments for all available hooks now (rather than when they are first executed). See `pre-commit install-hooks`. - `-t HOOK_TYPE`, `--hook-type HOOK_TYPE`: Specify which hook type to install. - `--allow-missing-config`: Hook scripts will permit a missing configuration file. ### Examples ```bash # Default invocation: Installs the hook scripts alongside any existing git hooks. pre-commit install # Idempotently replaces existing git hook scripts with pre-commit, and also installs hook environments. pre-commit install --install-hooks --overwrite ``` `pre-commit install` will install hooks from `default_install_hook_types` if `--hook-type` is not specified on the command line. ``` -------------------------------- ### Run pre-commit version check Source: https://pre-commit.com/ Verify the installed version of pre-commit. This command should be run after installation to confirm it's working. ```bash $ pre-commit --version pre-commit 4.5.1 ``` -------------------------------- ### Template Hook to Prompt for Pre-commit Install Source: https://pre-commit.com/ This bash script serves as a template hook (e.g., `~/.git-template/hooks/pre-commit`). It checks for the presence of `.pre-commit-config.yaml` and exits with an error if `pre-commit install` has not been run, enforcing explicit setup. ```bash #!/usr/bin/env bash if [ -f .pre-commit-config.yaml ]; then echo 'pre-commit configuration detected, but `pre-commit install` was never run' 1>&2 exit 1 fi ``` -------------------------------- ### pre-commit install with options Source: https://pre-commit.com/ Idempotently replaces existing git hook scripts with pre-commit and installs hook environments using --install-hooks and --overwrite flags. ```bash pre-commit install --install-hooks --overwrite ``` -------------------------------- ### pre-commit sample-config Source: https://pre-commit.com/ Generates a sample `.pre-commit-config.yaml` file to help users start their configuration. ```APIDOC ## pre-commit sample-config [options] ### Description Produce a sample `.pre-commit-config.yaml`. ### Options (no additional options) ``` -------------------------------- ### Install pre-commit Hooks Source: https://pre-commit.com/ Installs missing environments for available hooks. Environments are created on first hook call unless this command is used. ```bash pre-commit install --install-hooks ``` -------------------------------- ### Create a basic pre-commit configuration file Source: https://pre-commit.com/ Generate a sample `.pre-commit-config.yaml` file to define the hooks you want to use. This example includes hooks for YAML validation, end-of-file fixing, and trailing whitespace removal, along with the Black formatter for Python code. ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black ``` -------------------------------- ### Pre-commit Init-templatedir with Missing Config Handling Source: https://pre-commit.com/ The `init-templatedir` command uses `--allow-missing-config`, meaning repositories without a `.pre-commit-config.yaml` file will be skipped. This example demonstrates initializing a new repository and committing without a pre-commit configuration. ```bash $ git init sample Initialized empty Git repository in /tmp/sample/.git/ $ cd sample $ git commit --allow-empty -m 'Initial commit' `.pre-commit-config.yaml` config file not found. Skipping `pre-commit`. [main (root-commit) d1b39c1] Initial commit ``` -------------------------------- ### Install pre-commit with Overwrite Option Source: https://pre-commit.com/ Installs pre-commit hooks, overwriting existing hooks without entering migration mode. Use with caution. ```bash pre-commit install -f ``` -------------------------------- ### Install pre-commit git hook scripts Source: https://pre-commit.com/ Run this command in your project's root directory to install the git hook scripts. This enables pre-commit to run automatically before each commit. ```bash $ pre-commit install pre-commit installed at .git/hooks/pre-commit ``` -------------------------------- ### pre-commit install-hooks Source: https://pre-commit.com/ Installs missing environments for available hooks. Environments are created the first time a hook is called, or explicitly with this command. It does not install the pre-commit script itself. ```APIDOC ## pre-commit install-hooks [options] ### Description Install all missing environments for the available hooks. Unless this command or `install --install-hooks` is executed, each hook's environment is created the first time the hook is called. Each hook is initialized in a separate environment appropriate to the language the hook is written in. See supported languages. This command does not install the pre-commit script. To install the script along with the hook environments in one command, use `pre-commit install --install-hooks`. ### Options (no additional options) ``` -------------------------------- ### Install pre-commit for specific hook types Source: https://pre-commit.com/ Use the --hook-type flag to install pre-commit for multiple specific git hooks. ```bash $ pre-commit install --hook-type pre-commit --hook-type pre-push pre-commit installed at .git/hooks/pre-commit pre-commit installed at .git/hooks/pre-push ``` -------------------------------- ### pre-commit install default invocation Source: https://pre-commit.com/ Installs the pre-commit script alongside any existing git hooks. This is the default invocation. ```bash pre-commit install ``` -------------------------------- ### Define a complete hook configuration Source: https://pre-commit.com/ A minimal example of a complete configuration using a specific hook from a repository. ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v1.2.3 hooks: - id: trailing-whitespace ``` -------------------------------- ### Error on Commit with Forgotten Pre-commit Install Source: https://pre-commit.com/ When using the template hook that checks for `pre-commit install`, attempting to commit in a repository with a configuration but without running `pre-commit install` will result in an error message. ```bash $ git clone -q https://github.com/asottile/pyupgrade $ cd pyupgrade/ $ git commit -m 'foo' pre-commit configuration detected, but `pre-commit install` was never run ``` -------------------------------- ### Configure Git Init Template Directory for Automatic Pre-commit Source: https://pre-commit.com/ Set `git config --global init.templateDir` to a directory containing pre-commit hooks. This ensures that any newly cloned repository automatically has pre-commit hooks installed without needing `pre-commit install`. ```bash $ git config --global init.templateDir ~/.git-template $ pre-commit init-templatedir ~/.git-template pre-commit installed at /home/asottile/.git-template/hooks/pre-commit ``` -------------------------------- ### Cloning a Repo with Auto-Installed Pre-commit Hooks Source: https://pre-commit.com/ After setting up `init.templateDir`, cloning a repository automatically includes pre-commit hooks. This example shows a successful commit in a cloned repository where hooks are already active. ```bash $ git clone -q git@github.com:asottile/pyupgrade $ cd pyupgrade $ git commit --allow-empty -m 'Hello world!' Check docstring is first.............................(no files to check)Skipped Check Yaml...........................................(no files to check)Skipped Debug Statements (Python)............................(no files to check)Skipped ... ``` -------------------------------- ### pre-commit init-templatedir Source: https://pre-commit.com/ Installs hook scripts in a directory intended for use with `git config init.templateDir`, allowing hooks to be automatically set up in new repositories. ```APIDOC ## pre-commit init-templatedir DIRECTORY [options] Install hook script in a directory intended for use with `git config init.templateDir`. ### Options - `-t HOOK_TYPE`, `--hook-type HOOK_TYPE`: which hook type to install. ### Examples ```bash # Linux/macOS git config --global init.templateDir ~/.git-template pre-commit init-templatedir ~/.git-template # Windows cmd.exe pre-commit init-templatedir %HOMEPATH%\.git-template # Windows PowerShell pre-commit init-templatedir $HOME\.git-template ``` ``` -------------------------------- ### Run pre-commit hooks on all files Source: https://pre-commit.com/ Execute all configured pre-commit hooks against every file in the repository. This is useful for initial setup or when adding new hooks to ensure consistency across the entire project. ```bash $ pre-commit run --all-files [INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Initializing environment for https://github.com/psf/black. [INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/psf/black. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... Check Yaml...............................................................Passed Fix End of Files.........................................................Passed Trim Trailing Whitespace.................................................Failed - hook id: trailing-whitespace - exit code: 1 Files were modified by this hook. Additional output: Fixing sample.py black....................................................................Passed ``` -------------------------------- ### Configure default install hook types Source: https://pre-commit.com/ Set the default_install_hook_types property in the configuration to define which hooks are installed by default. ```yaml default_install_hook_types: [pre-commit, pre-push, commit-msg] ``` -------------------------------- ### Define a Hook in .pre-commit-hooks.yaml Source: https://pre-commit.com/ Example configuration for a hook that trims trailing whitespace using a Python-based fixer. ```yaml - id: trailing-whitespace name: Trim Trailing Whitespace description: This hook trims trailing whitespace. entry: trailing-whitespace-fixer language: python types: [text] ``` -------------------------------- ### pre-commit CLI Commands Source: https://pre-commit.com/ Commands for installing and executing pre-commit hooks within a git repository. ```APIDOC ## CLI Commands ### Description Commands to manage and execute pre-commit hooks. ### Commands - **pre-commit install**: Installs pre-commit into your git hooks. - **pre-commit run --all-files**: Manually runs all pre-commit hooks on a repository. - **pre-commit run **: Runs an individual hook by its ID. ``` -------------------------------- ### Advanced Features: Migration Mode and Skipping Hooks Source: https://pre-commit.com/ Details on advanced pre-commit features like migration mode during installation and temporarily disabling hooks using the SKIP environment variable. ```APIDOC ## Running in migration mode By default, if you have existing hooks `pre-commit install` will install in a migration mode which runs both your existing hooks and hooks for pre-commit. To disable this behavior, pass `-f` / `--overwrite` to the `install` command. If you decide not to use pre-commit, `pre-commit uninstall` will restore your hooks to the state prior to installation. ## Temporarily disabling hooks Not all hooks are perfect so sometimes you may need to skip execution of one or more hooks. pre-commit solves this by querying a `SKIP` environment variable. The `SKIP` environment variable is a comma separated list of hook ids. This allows you to skip a single hook instead of `--no-verify`ing the entire commit. ### Example ```bash $ SKIP=flake8 git commit -m "foo" ``` ``` -------------------------------- ### pre-commit uninstall Source: https://pre-commit.com/ Uninstalls the pre-commit script, restoring the repository's state prior to installation. ```APIDOC ## pre-commit uninstall [options] ### Description Uninstall the pre-commit script. ### Options - **-t HOOK_TYPE, --hook-type HOOK_TYPE** - Which hook type to uninstall. ``` -------------------------------- ### Define top-level configuration Source: https://pre-commit.com/ A sample structure for the top-level .pre-commit-config.yaml file. ```yaml exclude: '^$' fail_fast: false repos: - ... ``` -------------------------------- ### Try pre-commit Hooks in a Local Repository Source: https://pre-commit.com/ Tests hooks from a local repository path. This is useful for developing or testing hooks before committing changes. ```bash pre-commit try-repo ../path/to/repo ``` -------------------------------- ### Configure local hooks with direct entry arguments Source: https://pre-commit.com/ For local hooks, include arguments directly in the entry field instead of using the args property. ```yaml - repo: local hooks: - id: check-requirements name: check requirements files language: unsupported entry: python -m scripts.check_requirements --compare files: ^requirements.*\.txt$ ``` -------------------------------- ### Try Specific pre-commit Hook in Local Repository Source: https://pre-commit.com/ Runs a specific hook (e.g., `flake8`) from a local repository path for testing purposes. ```bash pre-commit try-repo ../pre-commit-hooks flake8 ``` -------------------------------- ### Run pre-commit Hooks on All Files Source: https://pre-commit.com/ Executes all pre-commit hooks against every file in the repository. This is particularly useful for CI environments. ```bash pre-commit run --all-files ``` -------------------------------- ### Configure julia hook with arguments Source: https://pre-commit.com/ Configure a julia hook where the entrypoint is a julia source file with arguments. ```yaml - id: bar-with-args name: ... language: julia entry: bin/bar.jl --arg1 --arg2 ``` -------------------------------- ### Try pre-commit Hooks in a Remote Repository Source: https://pre-commit.com/ Tests hooks from a specified remote repository (e.g., a GitHub URL) without adding it to the local configuration. It generates a temporary configuration and runs the hooks. ```bash pre-commit try-repo https://github.com/pre-commit/pre-commit-hooks ``` -------------------------------- ### pre-commit try-repo Source: https://pre-commit.com/ Allows testing hooks from a repository locally, useful for developing new hooks or testing external hook repositories before adding them to the main configuration. ```APIDOC ## pre-commit try-repo REPO [options] ### Description Try the hooks in a repository, useful for developing new hooks. `try-repo` can also be used for testing out a repository before adding it to your configuration. `try-repo` prints a configuration it generates based on the remote hook repository before running the hooks. ### Method `try-repo` ### Parameters #### Path Parameters - **REPO** (string) - Required - Clonable hooks repository. Can be a local path on disk. #### Query Parameters - **--ref REF** - Optional - Manually select a ref to run against, otherwise the `HEAD` revision will be used. * `pre-commit try-repo` also supports all available options for `pre-commit run`. ### Request Example ```bash pre-commit try-repo https://github.com/pre-commit/pre-commit-hooks pre-commit try-repo ../path/to/repo pre-commit try-repo ../pre-commit-hooks flake8 ``` ### Response (No specific response format defined, typically stdout/stderr output) ``` -------------------------------- ### Configure docker_image hook with ENTRYPOINT Source: https://pre-commit.com/ Use this configuration when the docker image has an ENTRYPOINT defined. The 'entry' field specifies the docker tag to use. ```yaml - id: dockerfile-provides-entrypoint name: ... language: docker_image entry: my.registry.example.com/docker-image-1:latest ``` -------------------------------- ### Configure repository-local hooks Source: https://pre-commit.com/ Use the local sentinel to define hooks that reside within the repository. ```yaml - repo: local hooks: - id: pylint name: pylint entry: pylint language: unsupported types: [python] require_serial: true - id: check-x name: Check X entry: ./bin/check-x.sh language: unsupported_script files: \.x$ - id: scss-lint name: scss-lint entry: scss-lint language: ruby language_version: 2.1.5 types: [scss] additional_dependencies: ['scss_lint:0.52.0'] ``` -------------------------------- ### Validate pre-commit Configuration File Source: https://pre-commit.com/ Checks the syntax and structure of `.pre-commit-config.yaml` files for validity. ```bash pre-commit validate-config ``` -------------------------------- ### Test hooks interactively with try-repo Source: https://pre-commit.com/ Use pre-commit try-repo to test a local hook repository without needing to commit changes. ```bash ~/work/hook-repo $ git checkout origin/main -b feature # ... make some changes # In another terminal or tab ~/work/other-repo $ pre-commit try-repo ../hook-repo foo --verbose --all-files =============================================================================== Using config: =============================================================================== repos: - repo: ../hook-repo rev: 84f01ac09fcd8610824f9626a590b83cfae9bcbd hooks: - id: foo =============================================================================== [INFO] Initializing environment for ../hook-repo. Foo......................................................................Passed - hook id: foo - duration: 0.02s Hello from foo hook! ``` -------------------------------- ### Run pre-commit Hooks on Specific Files Source: https://pre-commit.com/ Runs all pre-commit hooks against files matching a pattern (e.g., `*.py`). This requires piping file names to the command. ```bash git ls-files -- "*.py" | xargs pre-commit run --files ``` -------------------------------- ### Configure GitHub Actions cache Source: https://pre-commit.com/ Cache pre-commit environments using environment variables and hashFiles for cache keys. ```yaml - name: set PY run: echo "PY=$(python -VV | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV - uses: actions/cache@v3 with: path: ~/.cache/pre-commit key: pre-commit|${{ env.PY }}|${{ hashFiles('.pre-commit-config.yaml') }} ``` -------------------------------- ### Configure hook arguments in .pre-commit-config.yaml Source: https://pre-commit.com/ Pass static arguments to a hook using the args property. ```yaml - repo: https://github.com/PyCQA/flake8 rev: 4.0.1 hooks: - id: flake8 args: [--max-line-length=131] ``` -------------------------------- ### Migrate pre-commit Configuration Source: https://pre-commit.com/ Migrates a list-based configuration to the new map-based format for `.pre-commit-config.yaml`. ```bash pre-commit migrate-config ``` -------------------------------- ### pre-commit run Source: https://pre-commit.com/ Runs hooks against files. It can run a specific hook, all hooks, hooks on specified files, or hooks changed between two references. ```APIDOC ## pre-commit run [hook-id] [options] ### Description Run hooks. ### Method `run` ### Parameters #### Path Parameters - **hook-id** (string) - Optional - Specify a single hook-id to run only that hook. #### Query Parameters - **-a, --all-files** - Optional - Run on all the files in the repo. - **--files [FILES [FILES ...]]** - Optional - Specific filenames to run hooks on. - **--from-ref FROM_REF** - Optional - The starting reference for comparing file changes. - **--to-ref TO_REF** - Optional - The ending reference for comparing file changes. - **--hook-stage STAGE** - Optional - Select a `stage` to run. - **--show-diff-on-failure** - Optional - When hooks fail, run `git diff` directly afterward. - **-v, --verbose** - Optional - Produce hook output independent of success. Include hook ids in output. ### Request Example ```bash pre-commit run pre-commit run --all-files pre-commit run flake8 pre-commit run --files "*.py" pre-commit run --from-ref HEAD^^^ --to-ref HEAD ``` ### Response (No specific response format defined, typically stdout/stderr output) ``` -------------------------------- ### Configure Travis CI cache Source: https://pre-commit.com/ Define the cache directory for pre-commit in Travis CI. ```yaml cache: directories: - $HOME/.cache/pre-commit ``` -------------------------------- ### Configure julia hook without arguments Source: https://pre-commit.com/ Configure a julia hook where the entrypoint is a julia source file without any arguments. ```yaml - id: foo-without-args name: ... language: julia entry: bin/foo.jl ``` -------------------------------- ### Enable Meta Hooks in Pre-commit Source: https://pre-commit.com/ Use `repo: meta` to enable pre-commit's built-in hooks for validating the configuration itself. These hooks help ensure your `.pre-commit-config.yaml` is correctly set up. ```yaml - repo: meta hooks: - id: ... ``` -------------------------------- ### Configuration Schema Source: https://pre-commit.com/ Details the structure of the .pre-commit-config.yaml file, including top-level configuration, repository definitions, and hook-level settings. ```APIDOC ## .pre-commit-config.yaml Structure ### Top-Level Configuration - **repos** (list) - Required - A list of repository mappings. - **default_install_hook_types** (list) - Optional - List of --hook-type values used by default. - **default_language_version** (mapping) - Optional - Mapping from language to default language_version. - **default_stages** (list) - Optional - Configuration-wide default for hook stages. - **files** (string) - Optional - Global file include pattern. - **exclude** (string) - Optional - Global file exclude pattern. - **fail_fast** (boolean) - Optional - Stop running hooks after the first failure. - **minimum_pre_commit_version** (string) - Optional - Minimum required version of pre-commit. ### Repository Mapping - **repo** (string) - Required - Repository URL or sentinel values (local, meta). - **rev** (string) - Required - Revision or tag to clone. - **hooks** (list) - Required - List of hook mappings. ### Hook Mapping - **id** (string) - Required - Hook identifier from the repository. - **alias** (string) - Optional - Additional reference ID. - **name** (string) - Optional - Override hook name. - **language_version** (string) - Optional - Override language version. - **files** (string) - Optional - Override file include pattern. - **exclude** (string) - Optional - File exclude pattern. - **types** (list) - Optional - Override file types (AND). - **types_or** (list) - Optional - Override file types (OR). - **exclude_types** (list) - Optional - File types to exclude. - **args** (list) - Optional - Additional parameters for the hook. - **stages** (list) - Optional - Git hooks to run for. - **additional_dependencies** (list) - Optional - Dependencies to install in the hook environment. - **always_run** (boolean) - Optional - Run even if no files match. - **verbose** (boolean) - Optional - Force output printing. - **log_file** (string) - Optional - File path to write hook output on failure. ``` -------------------------------- ### Run Specific pre-commit Hook Source: https://pre-commit.com/ Runs a specified hook (e.g., `flake8`) against all currently staged files. ```bash pre-commit run flake8 ``` -------------------------------- ### Set default language versions Source: https://pre-commit.com/ Define global default language versions at the top level of the configuration. ```yaml default_language_version: # force all unspecified python hooks to run python3 python: python3 # force all unspecified ruby hooks to run ruby 2.1.5 ruby: 2.1.5 ``` -------------------------------- ### Identify file types via CLI Source: https://pre-commit.com/ Use the identify-cli tool to inspect the tags associated with a file on disk. ```bash $ identify-cli setup.py ["file", "non-executable", "python", "text"] $ identify-cli some-random-file ["file", "non-executable", "text"] $ identify-cli --filename-only some-random-file; echo $? 1 ``` -------------------------------- ### pre-commit migrate-config Source: https://pre-commit.com/ Migrates a list-based configuration to the new map-based configuration format for `.pre-commit-config.yaml`. ```APIDOC ## pre-commit migrate-config [options] ### Description Migrate list configuration to the new map configuration format. ### Options (no additional options) ``` -------------------------------- ### Configure CircleCI cache Source: https://pre-commit.com/ Implement cache restoration and saving using a checksum of the configuration and Python version. ```yaml steps: - run: command: | cp .pre-commit-config.yaml pre-commit-cache-key.txt python --version --version >> pre-commit-cache-key.txt - restore_cache: keys: - v1-pc-cache-{{ checksum "pre-commit-cache-key.txt" }} # ... - save_cache: key: v1-pc-cache-{{ checksum "pre-commit-cache-key.txt" }} paths: - ~/.cache/pre-commit ``` -------------------------------- ### Configure default hook stages Source: https://pre-commit.com/ Sets the default git stages for hooks that do not explicitly define their own stages. ```yaml default_stages: [pre-commit, pre-push] ``` -------------------------------- ### .pre-commit-hooks.yaml Configuration Source: https://pre-commit.com/ Schema definition for the .pre-commit-hooks.yaml file used to register hooks. ```APIDOC ## .pre-commit-hooks.yaml Configuration ### Description Defines the configuration for a pre-commit hook. ### Fields - **id** (string) - Required - The id of the hook. - **name** (string) - Required - The name of the hook shown during execution. - **entry** (string) - Required - The executable to run. - **language** (string) - Required - The language of the hook. - **files** (string) - Optional - Pattern of files to run on. - **exclude** (string) - Optional - Pattern of files to exclude. - **types** (list) - Optional - List of file types to run on (AND). - **types_or** (list) - Optional - List of file types to run on (OR). - **exclude_types** (list) - Optional - List of file types to exclude. - **always_run** (boolean) - Optional - If true, runs even if no files match. - **fail_fast** (boolean) - Optional - If true, stops hooks if this one fails. - **verbose** (boolean) - Optional - If true, forces output printing. - **pass_filenames** (boolean) - Optional - If false, no filenames are passed to the hook. - **require_serial** (boolean) - Optional - If true, executes in a single process. - **description** (string) - Optional - Metadata description. - **language_version** (string) - Optional - Version of the language to use. - **minimum_pre_commit_version** (string) - Optional - Minimum compatible version. - **args** (list) - Optional - Additional parameters to pass to the hook. - **stages** (list) - Optional - Git hook stages to run on. ``` -------------------------------- ### Filter files using types Source: https://pre-commit.com/ Configure hooks to match files based on specific type tags. ```yaml files: ^foo/ types: [file, python] ``` -------------------------------- ### Define a repository mapping Source: https://pre-commit.com/ Specifies the source repository and revision for hooks. ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v1.2.3 hooks: - ... ``` -------------------------------- ### Use verbose regular expressions Source: https://pre-commit.com/ Enable verbose regex mode using the (?x) flag and YAML multiline literals for complex patterns. ```yaml # ... - id: my-hook exclude: | (?x)^( path/to/file1.py| path/to/file2.py| path/to/file3.py )$ ``` -------------------------------- ### Validate pre-commit Manifest File Source: https://pre-commit.com/ Validates the `.pre-commit-hooks.yaml` manifest file to ensure it adheres to the expected format. ```bash pre-commit validate-manifest ``` -------------------------------- ### Configure docker_image hook without ENTRYPOINT Source: https://pre-commit.com/ Use this configuration when the docker image does not have an ENTRYPOINT defined, or when you want to override it. The 'entry' field specifies the command to use as the entrypoint. ```yaml - id: dockerfile-no-entrypoint-1 name: ... language: docker_image entry: --entrypoint my-exe my.registry.example.com/docker-image-2:latest ``` ```yaml # Alternative equivalent solution - id: dockerfile-no-entrypoint-2 name: ... language: docker_image entry: my.registry.example.com/docker-image-3:latest my-exe ``` -------------------------------- ### Pre-commit Hazmat CD for Monorepo Subdirectory Targeting Source: https://pre-commit.com/ The `pre-commit hazmat cd` helper allows targeting a subdirectory within a monorepo. It changes the directory before running the hook and adjusts filename arguments. Ensure `minimum_pre_commit_version` is set to `4.5.0` or higher. Remember to copy `args` to `entry` and blank out `args`. ```yaml # recommended: # minimum_pre_commit_version: 4.5.0 repos: - repo: ... rev: ... hooks: - id: example alias: example-repo1 name: example (repo1) files: ^repo1/ # important! ends with `--` # important! copy `args: [...]` to entry and blank out `args: []` entry: pre-commit hazmat cd repo1 example-bin --arg1 -- args: [] - id: example alias: example-repo2 name: example (repo2) files: ^repo2/ entry: pre-commit hazmat cd repo2 example-bin --arg1 -- args: [] # ... etc. ``` -------------------------------- ### Configure AppVeyor cache Source: https://pre-commit.com/ Cache the pre-commit repository store in AppVeyor. ```yaml cache: - '%USERPROFILE%\.cache\pre-commit' ``` -------------------------------- ### Add pre-commit status badge Source: https://pre-commit.com/ Display a pre-commit enabled badge in your repository documentation. ```markdown [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit) ``` ```html pre-commit ``` ```restructuredtext .. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit :target: https://github.com/pre-commit/pre-commit :alt: pre-commit ``` ```asciidoc image:https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit[pre-commit, link=https://github.com/pre-commit/pre-commit] ``` -------------------------------- ### pre-commit autoupdate freeze usage Source: https://pre-commit.com/ Updates pre-commit configuration to frozen versions using the --freeze flag. Shows output and verification of frozen hashes. ```bash $ : update to frozen versions $ pre-commit autoupdate --freeze Updating https://github.com/pre-commit/pre-commit-hooks ... updating v2.1.0 -> v2.4.0 (frozen). Updating https://github.com/asottile/pyupgrade ... updating v1.25.0 -> v1.25.2 (frozen). $ grep rev: .pre-commit-config.yaml rev: 0161422b4e09b47536ea13f49e786eb3616fe0d7 # frozen: v2.4.0 rev: 34a269fd7650d264e4de7603157c10d0a9bb8211 # frozen: v1.25.2 ``` -------------------------------- ### Pre-commit Hazmat N1 for Single-File Argument Hooks Source: https://pre-commit.com/ The `pre-commit hazmat n1` helper is for hooks that only accept a single filename argument. It runs such hooks one at a time, which can be significantly slower. Ensure `minimum_pre_commit_version: 4.5.0`. ```yaml # recommended: # minimum_pre_commit_version: 4.5.0 repos: - repo: ... rev: ... hooks: - id: example # important! ends with `--` # important! copy `args: [...]` to entry and blank out `args: []` entry: pre-commit hazmat n1 example-bin --arg1 -- args: [] ``` -------------------------------- ### pre-commit validate-config Source: https://pre-commit.com/ Validates the syntax and structure of `.pre-commit-config.yaml` files. ```APIDOC ## pre-commit validate-config [options] [filenames ...] ### Description Validate `.pre-commit-config.yaml` files ``` -------------------------------- ### Configure julia hook with extra dependencies Source: https://pre-commit.com/ Configure a julia hook that requires additional dependencies. These are passed to 'pkg> add' and can augment or override the existing environment. ```yaml - id: baz-with-extra-deps name: ... language: julia entry: bin/baz.jl additional_dependencies: - 'ExtraDepA@1' - 'ExtraDepB@2.4' ``` -------------------------------- ### Add pre-commit to Python project requirements Source: https://pre-commit.com/ Include pre-commit in your Python project's requirements.txt or requirements-dev.txt for dependency management. ```text pre-commit ``` -------------------------------- ### Run pre-commit Hooks Between Git Refs Source: https://pre-commit.com/ Executes hooks against files changed between two specified Git references (e.g., `HEAD^^^` and `HEAD`). Useful for pre-receive hooks. ```bash pre-commit run --from-ref HEAD^^^ --to-ref HEAD ``` -------------------------------- ### pre-commit autoupdate default usage Source: https://pre-commit.com/ Updates pre-commit configuration to the latest tags on the default branch. Shows output and how to verify changes with grep. ```bash $ : default: update to latest tag on default branch $ pre-commit autoupdate # by default: pick tags Updating https://github.com/pre-commit/pre-commit-hooks ... updating v2.1.0 -> v2.4.0. Updating https://github.com/asottile/pyupgrade ... updating v1.25.0 -> v1.25.2. $ grep rev: .pre-commit-config.yaml rev: v2.4.0 rev: v1.25.2 ``` -------------------------------- ### Configure proxy environment variables in tox Source: https://pre-commit.com/ Pass proxy-related environment variables to the tox test environment to allow git to clone over HTTP/HTTPS behind a proxy. ```ini [testenv] passenv = http_proxy https_proxy no_proxy ``` -------------------------------- ### Define custom hook arguments Source: https://pre-commit.com/ Custom hooks receive arguments defined in the config followed by a list of staged files. ```yaml - repo: https://github.com/path/to/your/hook/repo rev: badf00ddeadbeef hooks: - id: my-hook-script-id args: [--myarg1=1, --myarg1=2] ``` ```bash path/to/script-or-system-exe --myarg1=1 --myarg1=2 dir/file1 dir/file2 file3 ``` ```bash path/to/script-or-system-exe dir/file1 dir/file2 file3 ``` -------------------------------- ### pre-commit gc Source: https://pre-commit.com/ Cleans unused cached hook repositories to manage disk space. ```APIDOC ## pre-commit gc [options] Clean unused cached repos. `pre-commit` keeps a cache of installed hook repositories which grows over time. This command can be run periodically to clean out unused repos from the cache directory. ### Options (no additional options) ``` -------------------------------- ### pre-commit validate-manifest Source: https://pre-commit.com/ Validates the syntax and structure of `.pre-commit-hooks.yaml` files. ```APIDOC ## pre-commit validate-manifest [options] [filenames ...] ### Description Validate `.pre-commit-hooks.yaml` files ``` -------------------------------- ### Configure Azure Pipelines cache Source: https://pre-commit.com/ Use immutable cache keys based on Python version and configuration hash in Azure Pipelines. ```yaml jobs: - job: precommit # ... variables: PRE_COMMIT_HOME: $(Pipeline.Workspace)/pre-commit-cache steps: # ... - script: echo "##vso[task.setvariable variable=PY]$(python -VV)" - task: CacheBeta@0 inputs: key: pre-commit | .pre-commit-config.yaml | "$(PY)" path: $(PRE_COMMIT_HOME) ``` -------------------------------- ### Configure GitLab CI cache Source: https://pre-commit.com/ Set a static cache path for pre-commit in GitLab CI jobs. ```yaml my_job: variables: PRE_COMMIT_HOME: ${CI_PROJECT_DIR}/.cache/pre-commit cache: paths: - ${PRE_COMMIT_HOME} ``` -------------------------------- ### Configure a fail language hook Source: https://pre-commit.com/ Use the 'fail' language to forbid files based on a filename pattern. The 'entry' field provides a message displayed when the hook fails. ```yaml - repo: local hooks: - id: changelogs-rst name: changelogs must be rst entry: changelog filenames must end in .rst language: fail files: 'changelog/.*(? 5df1a4bf6f04a1ed3a643167b38d502575e29aef. $ grep rev: .pre-commit-config.yaml rev: 5df1a4bf6f04a1ed3a643167b38d502575e29aef rev: v1.25.0 ``` -------------------------------- ### Override types for specific hooks Source: https://pre-commit.com/ Revert to file-based matching by overriding the default types setting. ```yaml - id: check-json types: [file] # override `types: [json]` files: \.(json|myext)$ ``` -------------------------------- ### Override language version for a hook Source: https://pre-commit.com/ Specify a particular language version for an individual hook. ```yaml - repo: https://github.com/pre-commit/mirrors-scss-lint rev: v0.54.0 hooks: - id: scss-lint language_version: 2.1.5 ``` -------------------------------- ### Skip Specific Hook During Commit Source: https://pre-commit.com/ Temporarily disables a specific hook (e.g., `flake8`) by setting the `SKIP` environment variable. The commit proceeds with other hooks active. ```bash $ SKIP=flake8 git commit -m "foo" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.