### pre-commit install Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Install the pre-commit script. ```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`](#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. ### Example Invocations - `pre-commit install`: Default invocation. Installs the hook scripts alongside any existing git hooks. - `pre-commit install --install-hooks --overwrite`: Idempotently replaces existing git hook scripts with pre-commit, and also installs hook environments. `pre-commit install` will install hooks from [`default_install_hook_types`](#top_level-default_install_hook_types) if `--hook-type` is not specified on the command line. ``` -------------------------------- ### Initialize template directory for hooks Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Commands to install hook scripts into a template directory for automatic setup on new clones. ```bash git config --global init.templateDir ~/.git-template pre-commit init-templatedir ~/.git-template ``` ```batch pre-commit init-templatedir %HOMEPATH%\.git-template ``` ```powershell pre-commit init-templatedir $HOME\.git-template ``` -------------------------------- ### Verify pre-commit installation Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/install.md Check the installed version of pre-commit. ```cmd pre-commit --version ``` -------------------------------- ### Example .pre-commit-config.yaml configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md A sample configuration file used for demonstrating pre-commit autoupdate functionality. ```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] ``` -------------------------------- ### Sample Repository Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/plugins.md Example of a repository entry in .pre-commit-config.yaml, specifying the repository URL, revision, and hooks to be used. ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v1.2.3 hooks: - ... ``` -------------------------------- ### Install Missing Pre-commit Hook Environments Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Installs environments for all missing pre-commit hooks. Environments are created on first use unless this command or `install --install-hooks` is executed. ```bash pre-commit install-hooks ``` -------------------------------- ### Sample Top-Level Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/plugins.md A basic example of a top-level .pre-commit-config.yaml file, including exclude patterns and fail-fast settings. ```yaml exclude: '^$' fail_fast: false repos: - ... ``` -------------------------------- ### Install git hook scripts Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/install.md Initialize the git hooks to run automatically on commit. ```console $ pre-commit install pre-commit installed at .git/hooks/pre-commit ``` -------------------------------- ### Install pre-commit via pip Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/install.md Use pip to install the pre-commit package manager. ```bash pip install pre-commit ``` -------------------------------- ### Example pre-commit Hook Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md An example of a hook definition in YAML format, specifying its ID, name, description, entry point, language, and file types. ```yaml - id: trailing-whitespace name: Trim Trailing Whitespace description: This hook trims trailing whitespace. entry: trailing-whitespace-fixer language: python types: [text] ``` -------------------------------- ### Example of pre-commit hooks running on a cloned repository Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Demonstrates how pre-commit hooks are automatically applied to a newly cloned repository, even if it doesn't have a configuration file. ```pre-commit $ 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 ... ``` -------------------------------- ### Install pre-commit with default hook types Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Install pre-commit using the default Git hook types specified in the configuration. This command will install hooks for each type listed in `default_install_hook_types`. ```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 ``` -------------------------------- ### Define a pre-commit hook configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/plugins.md A basic example showing how to specify a repository, revision, and hook ID in the configuration file. ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v1.2.3 hooks: - id: trailing-whitespace ``` -------------------------------- ### Set up Git's init.templateDir for Automatic pre-commit Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Configure git to use a template directory for new repositories. This ensures pre-commit hooks are automatically set up without manual installation. ```console $ git config --global init.templateDir ~/.git-template $ pre-commit init-templatedir ~/.git-template pre-commit installed at /home/asottile/.git-template/hooks/pre-commit ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/usage.md Run this command to install pre-commit into your project's git hooks. This ensures pre-commit will automatically run on every commit. ```bash $ pre-commit install pre-commit installed at /home/asottile/workspace/pytest/.git/hooks/pre-commit ``` -------------------------------- ### pre-commit init-templatedir Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Install hook script in a directory intended for use with `git config init.templateDir`. ```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. ### Example Invocations ```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 ``` Now whenever a repository is cloned or created, it will have the hooks set up already! ``` -------------------------------- ### pre-commit install-hooks Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Installs all missing environments for the available hooks defined in the configuration. ```APIDOC ## pre-commit install-hooks ### Description Install all missing environments for the available hooks. Each hook is initialized in a separate environment appropriate to the language the hook is written in. ### Method CLI Command ### Endpoint pre-commit install-hooks ``` -------------------------------- ### Filter files by type and path using AND logic Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Example YAML configuration demonstrating how to match files that are within a specific directory ('foo/') AND are of a 'python' type. ```yaml files: ^foo/ types: [file, python] ``` -------------------------------- ### Error on commit when pre-commit install is forgotten Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Illustrates the error message produced when a commit is attempted without running `pre-commit install` after a configuration is detected. ```console $ 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 ``` -------------------------------- ### Template hook to prompt for pre-commit installation Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md A bash script for a template hook that checks for a pre-commit configuration and prompts the user to run `pre-commit install` if it's missing. ```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 ``` -------------------------------- ### Configure default Git hook types for installation Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Set a default set of Git hook types to be installed by pre-commit by configuring the top-level `default_install_hook_types` in your configuration file. ```yaml default_install_hook_types: [pre-commit, pre-push, commit-msg] ``` -------------------------------- ### Default Stages Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/plugins.md Configure default stages for all hooks. This example sets hooks to run during 'pre-commit' and 'pre-push' stages. ```yaml default_stages: [pre-commit, pre-push] ``` -------------------------------- ### Example pre-commit configuration for a local hook Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md This YAML configuration defines a repository and a hook to be used. It specifies the local repository path, a revision, and the hook ID. ```yaml repos: - repo: ../hook-repo rev: 84f01ac09fcd8610824f9626a590b83cfae9bcbd hooks: - id: foo ``` -------------------------------- ### Install pre-commit for specific Git hook types Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Install pre-commit hooks for specific Git hook types by using the --hook-type flag. This flag can be specified multiple times to include several hook types. ```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 ``` -------------------------------- ### GitHub Actions Cache Setup Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Integrate pre-commit caching with GitHub Actions using the official cache action. The cache key includes the Python version and a hash of the configuration file. ```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 Git Hook with pre-commit (pre-push) Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Utilize git's hook configuration (available in git 2.54+) to manage pre-commit hooks. This example shows how to set up a `pre-push` hook using `git config`. ```bash # an example with pre-push: # # git config set hook.pre-commit.pre-push.event pre-push # git config set hook.pre-commit.pre-push.command 'pre-commit hook-impl --hook-type pre-push --' ``` -------------------------------- ### Global Git Configuration for pre-commit Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Globally enable pre-commit for all repositories using `git config set --global`. This setup includes `--skip-on-missing-config` to handle repositories without a `.pre-commit-config.yaml`. ```bash git config set --global hook.pre-commit.pre-commit.event pre-commit git config set --global hook.pre-commit.pre-commit.command 'pre-commit hook-impl --hook-type pre-commit --skip-on-missing-config --' ``` -------------------------------- ### Commit with Pre-commit Hooks Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/usage.md Example output showing pre-commit hooks running after a git commit. Hooks like black, Trim Trailing Whitespace, and Flake8 are executed, with results indicating Passed or Skipped. ```bash $ 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(+) ``` -------------------------------- ### Git Fetch Error Example Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Illustrates a common error when Git fails to fetch due to permission issues, often encountered when SSH keys are not correctly configured or passed through in CI/testing environments. ```text [INFO] Initializing environment for git@github.com:pre-commit/pre-commit-hooks. An unexpected error has occurred: CalledProcessError: command: ('/usr/bin/git', 'fetch', 'origin', '--tags') return code: 128 expected return code: 0 stdout: (none) stderr: git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Check the log at /home/asottile/.cache/pre-commit/pre-commit.log ``` -------------------------------- ### Filter files by path and multiple types using OR logic Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Example YAML configuration showing how to match files within a specific directory ('foo/') that are of EITHER 'javascript', 'jsx', 'ts', OR 'tsx' type. ```yaml files: ^foo/ types_or: [javascript, jsx, ts, tsx] ``` -------------------------------- ### Azure Pipelines Cache Setup Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Set up caching for Azure Pipelines, including the Python version and configuration hash in the cache key for immutability. This ensures consistent cache usage across builds. ```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) ``` -------------------------------- ### Pass Arguments to Hooks Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Configure static arguments for hooks using the 'args' property in your .pre-commit-config.yaml. This example passes a max line length argument to the flake8 hook. ```yaml - repo: https://github.com/PyCQA/flake8 rev: 4.0.1 hooks: - id: flake8 args: [--max-line-length=131] ``` -------------------------------- ### Override default types for a hook to match specific file extensions Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Example YAML configuration for the 'check-json' hook, overriding its default 'json' type to match files with '.json' or '.myext' extensions using the 'files' argument. ```yaml - id: check-json types: [file] # override `types: [json]` files: \.(json|myext)$ ``` -------------------------------- ### Generate Sample Pre-commit Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Produces a sample `.pre-commit-config.yaml` file. ```bash pre-commit sample-config ``` -------------------------------- ### Interactive Hook Development with pre-commit try-repo Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md Demonstrates the initial command for using `pre-commit try-repo` to test hooks locally. This command is used to streamline the process of trying out a repository while developing hooks. ```bash ~/work/hook-repo $ git checkout origin/main -b feature # ... make some changes ``` -------------------------------- ### Run hooks against all files Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/install.md Execute all configured hooks on every file in the repository. ```pre-commit $ 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 ``` -------------------------------- ### Handling repositories without pre-commit configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Shows how pre-commit skips hooks in newly initialized repositories if no `.pre-commit-config.yaml` file is found, preventing errors. ```console $ 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 ``` -------------------------------- ### Running a local hook with pre-commit try-repo Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md This command attempts to run a hook from a local repository. Use --verbose for more details. It shows the configuration being used and the results of the hook execution. ```bash ~/work/other-repo $ pre-commit try-repo ../hook-repo foo --verbose --all-files ``` -------------------------------- ### Define pre-commit configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/install.md Create a .pre-commit-config.yaml file to define hooks and repositories. ```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 run Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Executes configured hooks against files in the repository. ```APIDOC ## pre-commit run ### Description Run hooks against files in the repository. ### Method CLI Command ### Endpoint pre-commit run [hook-id] [options] ### Parameters #### Path Parameters - **hook-id** (string) - Optional - Specify a single hook-id to run only that hook. #### Query Parameters - **-a, --all-files** (flag) - Optional - Run on all the files in the repo. - **--files** (list) - Optional - Specific filenames to run hooks on. - **--from-ref** (string) - Optional - Starting reference for range-based file selection. - **--to-ref** (string) - Optional - Ending reference for range-based file selection. - **--hook-stage** (string) - Optional - Select a stage to run. - **--show-diff-on-failure** (flag) - Optional - Run git diff after hook failure. - **-v, --verbose** (flag) - Optional - Produce hook output independent of success. ``` -------------------------------- ### Configure julia hook with arguments Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md Configure a julia hook where the entry point is a julia source file and arguments are passed to it. ```yaml - id: bar-with-args name: ... language: julia entry: bin/bar.jl --arg1 --arg2 ``` -------------------------------- ### pre-commit try-repo Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Tests hooks in a repository, useful for development or verification before adding to configuration. ```APIDOC ## pre-commit try-repo ### Description Try the hooks in a repository. Prints a generated configuration before running the hooks. ### Method CLI Command ### Endpoint pre-commit try-repo REPO [options] ### Parameters #### Path Parameters - **REPO** (string) - Required - Clonable hooks repository or local path. #### Query Parameters - **--ref** (string) - Optional - Manually select a ref to run against. ``` -------------------------------- ### Configure docker_image hook with entrypoint Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md 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 ``` -------------------------------- ### Run Pre-commit Hooks Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Executes pre-commit hooks. Can run a specific hook, all hooks on all files, or hooks on specified files or file ranges. Useful for CI or staged file checks. ```bash pre-commit run ``` ```bash pre-commit run --all-files ``` ```bash pre-commit run flake8 ``` ```bash git ls-files -- "*.py" | xargs pre-commit run --files ``` ```bash pre-commit run --from-ref HEAD^^^ --to-ref HEAD ``` -------------------------------- ### Validate Pre-commit Manifest File Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Checks the syntax and structure of `.pre-commit-hooks.yaml` files. ```bash pre-commit validate-manifest ``` -------------------------------- ### Validate Pre-commit Configuration File Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Checks the syntax and structure of `.pre-commit-config.yaml` files. ```bash pre-commit validate-config ``` -------------------------------- ### Test Pre-commit Hooks in a Repository Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Tests hooks from a specified repository, useful for developing new hooks or evaluating repositories before adding them to your configuration. Supports local paths and remote repositories. ```bash pre-commit try-repo https://github.com/pre-commit/pre-commit-hooks ``` ```bash pre-commit try-repo ../path/to/repo ``` ```bash pre-commit try-repo ../pre-commit-hooks flake8 ``` -------------------------------- ### Migrate Pre-commit Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Migrates a list-based pre-commit configuration to the newer map-based format. ```bash pre-commit migrate-config ``` -------------------------------- ### Pre-commit Global Options Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md All pre-commit commands accept these global options. ```APIDOC ## Global Options ### --color {auto,always,never} Whether to use color in output. Defaults to `auto`. Can be overridden by using `PRE_COMMIT_COLOR={auto,always,never}` or disabled using `TERM=dumb`. ### -c CONFIG, --config CONFIG Path to alternate config file. ### -h, --help Show help and available options. ``` -------------------------------- ### Run Hook with Single File Argument (pre-commit hazmat n1) Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md The `pre-commit hazmat n1` command is for hooks that accept only one filename argument. It runs them sequentially, which can be slow. Ensure the `entry` ends with `--` and that `args` from the hook definition are copied to `entry` while `args` remains an empty list. ```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: [] ``` -------------------------------- ### Configure Git Hook with pre-commit (pre-commit event) Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md This configuration sets up the `pre-commit` event for git hooks using `git config`. It specifies the command to run `pre-commit hook-impl` with the hook type `pre-commit`. ```bash # note, the "hook" name here is `pre-commit.pre-commit` # for the `pre-commit` "tool" and the `pre-commit` "event" git config set hook.pre-commit.pre-commit.event pre-commit git config set hook.pre-commit.pre-commit.command 'pre-commit hook-impl --hook-type pre-commit --' ``` -------------------------------- ### Run Hook with Single File Argument (pre-commit hazmat ignore-exit-code) Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Use `pre-commit hazmat ignore-exit-code` to run hooks that expect a single filename argument, processing them one by one. Ensure `args` are copied to `entry` and `args` is an empty list. Set `verbose: true` to prevent output hiding. ```yaml repos: - repo: ... rev: ... hooks: - id: example # important! copy `args: [...]` to entry and blank out `args: []` entry: pre-commit hazmat ignore-exit-code example-bin --arg1 -- args: [] # otherwise the output will always be hidden verbose: true ``` -------------------------------- ### Update pre-commit configurations Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Commands to update repository versions in the pre-commit configuration file. ```console $ : 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 ``` ```console $ : update a specific repository to the latest revision of the default branch $ pre-commit autoupdate --bleeding-edge --repo https://github.com/pre-commit/pre-commit-hooks Updating https://github.com/pre-commit/pre-commit-hooks ... updating v2.1.0 -> 5df1a4bf6f04a1ed3a643167b38d502575e29aef. $ grep rev: .pre-commit-config.yaml rev: 5df1a4bf6f04a1ed3a643167b38d502575e29aef rev: v1.25.0 ``` ```console $ : 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 ``` -------------------------------- ### Configure julia hook with additional dependencies Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md Configure a julia hook that requires additional dependencies. These are passed to `pkg> add` and use Pkg REPL mode syntax. ```yaml - id: baz-with-extra-deps name: ... language: julia entry: bin/baz.jl additional_dependencies: - 'ExtraDepA@1' - 'ExtraDepB@2.4' ``` -------------------------------- ### Add pre-commit to requirements Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/install.md Include pre-commit in your project's requirements file. ```text pre-commit ``` -------------------------------- ### Travis CI Cache Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Configure caching for pre-commit on Travis CI by specifying the cache directory. ```yaml cache: directories: - $HOME/.cache/pre-commit ``` -------------------------------- ### Configure julia hook without arguments Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md Configure a julia hook where the entry point is a julia source file and no arguments are passed. ```yaml - id: foo-without-args name: ... language: julia entry: bin/foo.jl ``` -------------------------------- ### Meta Hooks for Configuration Validation Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Enable meta hooks by specifying `repo: meta`. These hooks validate the pre-commit configuration itself, checking hook applicability and exclude directive effectiveness. ```yaml - repo: meta hooks: - id: ... ``` -------------------------------- ### pre-commit gc Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Clean unused cached repos. ```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-hooks.yaml Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md Defines the schema and fields required for a .pre-commit-hooks.yaml file to register hooks within a repository. ```APIDOC ## .pre-commit-hooks.yaml Configuration ### Description The .pre-commit-hooks.yaml file is required in a git repository to define pre-commit plugins. It specifies how hooks are executed, their entry points, and filtering criteria. ### Request Body - **id** (string) - Required - The unique identifier for the hook. - **name** (string) - Required - The display name of the hook. - **entry** (string) - Required - The executable command or entry point. - **language** (string) - Required - The language of the hook (e.g., python, node). - **files** (string) - Optional - Pattern of files to run on (default: ''). - **exclude** (string) - Optional - Pattern of files to exclude (default: '^$'). - **types** (list) - Optional - List of file types to run on (default: [file]). - **types_or** (list) - Optional - List of file types to run on (OR logic) (default: []). - **exclude_types** (list) - Optional - List of file types to exclude (default: []). - **always_run** (boolean) - Optional - Run even if no files match (default: false). - **fail_fast** (boolean) - Optional - Stop running hooks if this one fails (default: false). - **verbose** (boolean) - Optional - Force output printing (default: false). - **pass_filenames** (boolean) - Optional - Pass filenames to the hook (default: true). - **require_serial** (boolean) - Optional - Execute in a single process (default: false). - **description** (string) - Optional - Metadata description of the hook (default: ''). - **language_version** (string) - Optional - Version override (default: default). - **minimum_pre_commit_version** (string) - Optional - Minimum compatible version (default: '0'). - **args** (list) - Optional - Additional parameters for the hook (default: []). - **stages** (list) - Optional - Git hook stages to run for (default: all stages). ### Request Example - id: trailing-whitespace name: Trim Trailing Whitespace description: This hook trims trailing whitespace. entry: trailing-whitespace-fixer language: python types: [text] ``` -------------------------------- ### Configure docker_image hook without entrypoint Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md 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 docker tag and the executable. ```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 ``` -------------------------------- ### Appveyor CI Cache Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Configure caching for pre-commit on Appveyor CI to speed up builds. Ensure the cache path matches pre-commit's default cache directory. ```yaml cache: - '%USERPROFILE%\.cache\pre-commit' ``` -------------------------------- ### Identify file types using identify-cli Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Command-line usage of the `identify-cli` tool to determine the types associated with a file, such as 'file', 'python', and 'text'. ```console $ 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 $? ``` -------------------------------- ### Custom Hook Argument Handling Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Define how your custom hook script receives arguments from the pre-commit configuration. If `args` are defined, they are passed before staged files; otherwise, only staged files are passed. ```yaml - repo: https://github.com/path/to/your/hook/repo rev: badf00ddeadbeef hooks: - id: my-hook-script-id args: [--myarg1=1, --myarg1=2] ``` ```shell path/to/script-or-system-exe --myarg1=1 --myarg1=2 dir/file1 dir/file2 file3 ``` ```shell path/to/script-or-system-exe dir/file1 dir/file2 file3 ``` -------------------------------- ### pre-commit clean Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Clean out cached pre-commit files. ```APIDOC ## pre-commit clean [options] Clean out cached pre-commit files. ### Options (no additional options) ``` -------------------------------- ### Configure Git Hook to Always Run a Hook on All Files Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md This advanced configuration uses `git config` to set up a hook that always runs a specific pre-commit hook (`hookid`) on all files. This deviates from normal pre-commit behavior and can be slow. ```bash git config set hook.pre-commit.pre-commit-always.event pre-commit git config set hook.pre-commit.pre-commit-always.command 'pre-commit run hookid --hook-stage pre-commit --all-files' ``` -------------------------------- ### Repository Local Hooks Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Configure repository-local hooks by setting `repo` to `local`. These hooks are distributed with the repository and can use various languages, provided they support `additional_dependencies` or specific language types. ```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'] ``` -------------------------------- ### Dart hook additional dependencies configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md This YAML snippet shows how to specify additional dependencies for a Dart hook, including version pinning for a specific package. ```yaml additional_dependencies: ['hello_world_dart:1.0.0'] ``` -------------------------------- ### pre-commit validate-config Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Validates the .pre-commit-config.yaml file structure. ```APIDOC ## pre-commit validate-config ### Description Validate .pre-commit-config.yaml files. ### Method CLI Command ### Endpoint pre-commit validate-config [filenames ...] ``` -------------------------------- ### Configure fail language hook Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/new-hooks.md Use the `fail` language to prevent files by filename. 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/.*(?> 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 ``` -------------------------------- ### pre-commit autoupdate Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Auto-update pre-commit config to the latest repos' versions. ```APIDOC ## pre-commit autoupdate [options] Auto-update pre-commit config to the latest repos' versions. ### Options - `--bleeding-edge`: Update to the bleeding edge of the default branch instead of the latest tagged version (the default behaviour). - `--freeze`: Store "frozen" hashes in [`rev`](#repos-rev) instead of tag names. - `--repo REPO`: Only update this repository. This option may be specified multiple times. - `-j` / `--jobs`: _new in 3.3.0_ Number of threads to use (default: 1). ### Example Invocations ```bash # Default: update to latest tag on default branch pre-commit autoupdate # Update a specific repository to the latest revision of the default branch pre-commit autoupdate --bleeding-edge --repo https://github.com/pre-commit/pre-commit-hooks # Update to frozen versions pre-commit autoupdate --freeze ``` Pre-commit will preferentially pick tags containing a `.` if there are ties. ``` -------------------------------- ### Set Default Language Versions Globally Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Configure default language versions for all hooks of a specific language at the top level of your `.pre-commit-config.yaml`. ```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 ``` -------------------------------- ### Verbose Regex for Exclusions Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Use verbose regular expressions with the `(?x)` flag and YAML multiline literals to define complex exclusion patterns for hooks. ```yaml - id: my-hook exclude: | (?x)^( path/to/file1.py| path/to/file2.py| path/to/file3.py )$ ``` -------------------------------- ### Hazmat: Ignoring Exit Codes Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Employ `pre-commit hazmat ignore-exit-code` to allow hooks to exit with non-zero status codes without failing the pre-commit process. This is generally discouraged as it can introduce warning noise. ```yaml # recommended: ``` -------------------------------- ### Pre-commit Badge AsciiDoc Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Incorporate a pre-commit badge into AsciiDoc formatted documents, providing a link to the project's repository. ```asciidoc image:https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit[pre-commit, link=https://github.com/pre-commit/pre-commit] ``` -------------------------------- ### Skip a specific hook using SKIP environment variable Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md To skip a single hook instead of disabling all pre-commit checks, set the SKIP environment variable to a comma-separated list of hook IDs. ```bash $ SKIP=flake8 git commit -m "foo" ``` -------------------------------- ### Default Language Version Configuration Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/plugins.md Specify the default language version for hooks. This is useful for ensuring consistent Python versions across hooks. ```yaml default_language_version: python: python3.7 ``` -------------------------------- ### Tox Pass Proxy Environment Variables Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Configure tox to pass proxy environment variables (http_proxy, https_proxy, no_proxy). This is required for Git operations over HTTP/HTTPS when working behind a corporate proxy. ```ini [testenv] passenv = http_proxy https_proxy no_proxy ``` -------------------------------- ### Uninstall Pre-commit Script Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/cli.md Removes the pre-commit script from the repository. Can target specific hook types. ```bash pre-commit uninstall ``` -------------------------------- ### Hazmat: Monorepo Subdirectory Targeting Source: https://github.com/pre-commit/pre-commit.com/blob/main/sections/advanced.md Use `pre-commit hazmat cd` to target a subdirectory within a monorepo. This helper changes the directory before executing the hook and adjusts filename arguments. Ensure `args` are copied to `entry` and then cleared. ```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. ```