0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

windows環境でpre-commitを使ってgit hookを管理する方法

Posted at

はじめに

mac環境で行っている記事が多かったので書いてみました。

環境

Windows 11
python 3.10.4
powershell 5.1
pre-commit 2.21.0

手順

前提:仮想環境の作成

※以下すべての手順(1~5)は仮想環境上で行われています。

mkdir pre_commit_test
cd pre_commit_test
python -m venv .venv
.\.venv\Scripts\activate
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -For

1 pre-commitインストール

pip install pre-commit

2 git init

git init

3 設定ファイルの作成

※ powershellからpre-commit用yamlファイルを扱う場合、encodeが必要

pre-commit sample-config | out-file .pre-commit-config.yaml -encoding utf8

以下のようなファイルができる↓

.pre-commit-config.yaml
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v3.2.0
    hooks:
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-added-large-files

4 pre-commit 設定ファイルをgit hooks に適用

pre-commit install

5 テストする

sample.py
"test" 

※ 上記コードは 空白あり 最終行が空行ではない

sample.py作成後、

git add
git commit -m "add sample.py"

結果↓

Trim Trailing Whitespace.................................................Failed
- hook id: trailing-whitespace
- exit code: 1
- files were modified by this hook

Fixing sample.py

Fix End of Files.........................................................Failed
- hook id: end-of-file-fixer
- exit code: 1
- files were modified by this hook

Fixing sample.py

Check Yaml...........................................(no files to check)Skipped
Check for added large files..............................................Passed

修正後

sample.py
"test"

※ 空白の削除と最終行に空行を追加を自動で行ってくれている。

修正後commit結果↓

Trim Trailing Whitespace.................................................Passed
Fix End of Files.........................................................Passed
Check Yaml...........................................(no files to check)Skipped
Check for added large files..............................................Passed
[master 9a75752] add sample.py
 1 file changed, 1 insertion(+)
 create mode 100644 sample.py

おわりに

次回はpython scriptをgit hooksに適用させる方法について書きたいと思います。

参考

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?