22
2

More than 1 year has passed since last update.

お題は不問!Qiita Engineer Festa 2023で記事投稿!

pre-commit + commitizen + commitlint で快適なコミットを実現する

Last updated at Posted at 2023-07-18

コミットのイメージ

usage_example.gif

  • コミット前に静的解析やフォーマッター、セキュリティチェックが自動で走る
  • コミットメッセージを対話的に作成できる(もし所定の形式に沿わない場合、エラーとして弾く)

→ あまり意識しなくとも、品質を高めつつ、コミットメッセージを統一できる
→ ただし、あくまでローカルでのチェックになるので、リポジトリ側でのチェックは別で必要

サンプルリポジトリ

利用ツールについて

pre-commit

  • .pre-commit-config.yamlで各種hooksを一元管理できる
  • 静的解析やフォーマッタ、セキュリティ検査などをコミット前に自動実行

commitizen + cz-customizable

  • コミットメッセージを対話的に作成できる
  • .cz_config.js で設定することで、テンプレートは変更可能

commitlint + commitlint-config-gitmoji

  • commitlint.config.jsでコミットメッセージのフォーマットを指定
  • 上記フォーマットに当てはまらなければ、エラーとしてコミットを止めてくれる
  • 絵文字を使いたかったのでgitmojiを選択

環境構築

pre-commit

インストール

以下を参考に、pre-commitコマンドが使えるようにする

  • asdfが使える場合は、そちらでも可
  • pipが使えない場合は、Pythonのインストールからやってみること

設定

  • 以下を参考にhooksを設定

  • Supported hooks が参考になる
    • 各hooksの設定はそれぞれの紹介ページを参照

Node.js

インストール

以下から Node.js をインストールし、npmコマンドが使えるようにする

yarnを使いたい場合は入れておく

npm install -g yarn

commitizen、cz-customizable

インストール

npm install --save-dev commitizen cz-customizable

or

yarn add -D commitizen cz-customizable

設定

対話形式で組み立てるメッセージのテンプレートを設定する

  • package.json で coonfig設定
package.json
...
  "config": {
    "commitizen": {
      "path": "node_modules/cz-customizable"
    },
    "cz-customizable": {
      "config": "./.cz_config.js"
    }
  },
...

commit-lint, commitlint-config-gitmoji

インストール

npm install --save-dev @commitlint/cli commitlint-config-gitmoji

or

yarn add -D @commitlint/cli commitlint-config-gitmoji

設定

commitlint を git_hooksに追加

  • commit-msgファイルを作成
./git_hooks/commit-msg
#!/bin/sh
npx --no-install commitlint --edit "$1"
  • package.json で scripts設定
    • リポジトリをクローンしたとき、個別設定が不要なようにprepareで定義
    • ついでにコミットのためのコマンドも設定
package.json
...
  "scripts": {
    "prepare": "bash -c \"cp ./git_hooks/commit-msg ./.git/hooks/\"",
    "commit": "pre-commit run && npx cz"
  },
...
Windowsの場合
・・・
    "prepare": "cmd /c \"COPY .\\git_hooks\\commit-msg .\\.git\\hooks\\\"",
・・・
  • git_hooksに追加
npm install

or

yarn install

いざコミット

pre-commit → commitizen の順に実施したいため、コマンドでコミットする
(pre-commitが後になると、エラーが出た場合に折角コミットメッセージ組み立てたのにやり直し、となってしまうため)

npm run commit

or

yarn commit
22
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
2