銀河鉄道

Git|Pre-Commit Hooks to Safeguard Code Quality

サムネイル
pre-commitis nota test suite

Before pushing your code to GitHub, it’s a good idea to run checks automatically.
pre-commit is a tool that does exactly that — it acts like a guardian to prevent messy or broken code from being committed.

What is pre-commit?

pre-commit automatically runs checks before each commit.
It ensures that only clean, well-formatted, and type-safe code passes through.

pre-commit vs GitHub Actions

ToolTimingPurpose
pre-commitBefore committingRuns checks locally before the code leaves your machine
GitHub ActionsAfter committingRuns tests and workflows on GitHub’s servers

Setup: Configuration File

Create a file named .pre-commit-config.yaml in the project root directory

(the same folder where .git exists).


This file defines what checks to run — such as formatting, linting, or type checking.

Example:

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.5.7
    hooks:
      - id: ruff
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.10.0
    hooks:
      - id: mypy

  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: check-yaml
      - id: trailing-whitespace

Meaning of Each Key

KeyDescription
repoThe GitHub repository that provides the hook
revThe version or tag of that repository
hooksThe list of actions to run
idThe specific hook or tool name
argsOptional arguments (e.g. --fix to auto-format)

Common Hook Repositories

RepositoryPurpose
astral-sh/ruff-pre-commitCode formatting and linting
pre-commit/mirrors-mypyType checking
pre-commit/pre-commit-hooksBasic checks (YAML, whitespace, etc.)
PyCQA/banditSecurity scanning
PyCQA/isortSorting imports

Setting Up

① Install hooks

pre-commit install

This creates a script in .git/hooks/pre-commit,
which tells Git to run the defined checks before committing.

② Run on all files (initial check)

pre-commit run --all-files 2>&1 | head -200
  • --all-files → runs checks on every file
  • head -200 → shows only the first 200 lines of output
    During this process, tools like ruff (formatter) and mypy (type checker) are initialized.

After Setup

From now on, every time you run git commit,
the defined checks will run automatically — and your commit will be rejected if any errors are found.

Example:

Workflow Overview

  1. Write configuration in .pre-commit-config.yaml
  2. Run pre-commit install (creates .git/hooks/pre-commit)
  3. Commit your code
  4. Hooks execute automatically before the commit
  5. If errors exist, the commit is stopped

Summary

  • pre-commit defines when the checks run (before commit).
  • Linters and formatters define what is checked.
  • The .pre-commit-config.yaml file lets you freely combine and customize these tools.

Result:
Only clean, safe, and consistent code gets committed.

Vocabulary

EnglishJapanese
pre-commit hookコミット前フック
run –all-files全ファイル実行
linterコードスタイルチェッカー
formatter自動整形ツール
environment initialization環境初期化
hook installationフックの設置
commit gateコミット時の品質ゲート

Githubにアップする前に、チェックする

pre-commitとは

コミットする前に自動でコードをチェックしてくれるツール。
汚れたコードをコミットできないようにする見張り役のような存在。

GitHub Actionsとの違い
  • pre-commit:コミット前にチェックする
  • GitHub Actions:コミット後にチェックする

設定ファイルを用意する

ファイル名: .pre-commit-config.yaml

.pre-commit-config.yamlを作る。

ここに、チェック内容(Lint・整形・型検査など)を書く。

これが「どんなテストを走らせるか」を決めるメニュー。

ファイルの置き場所

プロジェクトのルートディレクトリ(=.gitがある場所)

ファイルの中身(書き方サンプル)

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.5.7
    hooks:
      - id: ruff
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.10.0
    hooks:
      - id: mypy

  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: check-yaml
      - id: trailing-whitespace

各要素の意味

項目内容
repo:ツール定義を配布しているGitHubリポジトリ
rev:そのリポジトリのバージョン(Gitタグ推奨)
hooks:実行する処理のリスト
id:実際に動かすフック(ツール名など)
args:追加のオプション(例:--fixで自動整形)

repoとは|ツール定義を配布しているGitHubリポジトリ

pre-commitはあらかじめ決まったツールを持っているわけではない。

使いたいフックを自由に選んで使う。

= Gitフックの中でツールを呼び出す

代表的なフックリポジトリ

代表的なフックリポジトリ
astral-sh/ruff-pre-commitコード整形・Lint
pre-commit/mirrors-mypy型チェック
pre-commit/pre-commit-hooks基本ルール(空白・YAMLなど)
PyCQA/banditセキュリティチェック
PyCQA/isortimport整列

設定ファイルの準備後、セットアップをする

① フックを登録する

pre-commit install

これで .git/hooks/pre-commit にスクリプトが作成される。
Gitがコミット前にこのスクリプトを実行する設定になる。

② 全ファイルをチェックする

pre-commit run --all-files 2>&1 | head -200
  • --all-files:すべてのファイルをチェックする
  • head -200:結果のうち最初の200行だけを表示する
  • 実行時に ruff(整形)や mypy(型チェック)などのツールが初期化される

セットアップが完了したら

chat_api.py などの既存コードに統合したり、CI/CD(自動テスト環境)に組み込んだりする。

3.git commit を実行するたびにチェックが入る

設定したチェックが自動で実行される。

例)

git commit -m をした後に、赤文字でErrorが表示される

フロー

  1. .pre-commit-config.yaml に設定を書く
  2. pre-commit install.git/hooks/pre-commit が生成される
  3. コミット実行時に、指定したフック(ツール)が順に実行される
  4. エラーがあればコミットが止まる

まとめ

  • pre-commitは「いつ実行するか(コミット前)」を担当する仕組み
  • LintやFormatterなどのツールは「何を実行するか」を担当する
  • どのツールを使うかは、.pre-commit-config.yaml自分で選んで組み合わせる

きれいで安全なコードだけがコミットを通過する仕組みになる。

Vocabulary

EnglishJapanese
pre-commit hookコミット前フック
run –all-files全ファイル実行
linterコードスタイルチェッカー
formatter自動整形ツール
environment initialization環境初期化
hook installationフックの設置
commit gateコミット時の品質ゲート

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧