自分用にpre-commitとactを動かす環境を作る手順
pre-commit(git hookの管理ツール)やCIを、
Gitのリポジトリに導入することで、コードの品質管理を行いやすくすることができます。
ただし複数人が関わるリポジトリへの導入・機能追加は、
開発者間の調整や、プロジェクトの管理方針うんぬんが関わってきて、
ちょっとしたツールを小回りよく導入することが難しいことが多々あります。
そこで、このエントリでは自分個人の作業効率のために、
pre-commitとact(GitHub Actionsのworkflowを手元のPCで動かすことができる)を導入する手順を示します。
pre-commit
https://pre-commit.com/
act | GitHub
https://github.com/nektos/act
pre-commitのインストール
以下のサイトを参照して、pre-commitをインストールします。
pre-commit
https://pre-commit.com/
aptが動作するLinux環境であれば、次のようなコマンドを実行します。
sudo apt install pre-commit
actのインストール
DockerEngineはセットアップできている前提として、 以下のサイトの手順を参照して、actをインストールします。
Installation | act - User Guide https://nektosact.com/installation/index.html
具体的には、次のようなコマンドを実行します。
sudo mkdir /opt/act && cd $_
curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash
自分用のpre-commit-configを作成、git hookに登録
自分用のpre-commit-configを作成します。
明確にリポジトリの他のコードとわけるため、ここでは.local
配下に作成します。
以下のpre-commit-configは、EOFと改行コードをfixする設定の例です。
.local/pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: end-of-file-fixer
- id: mixed-line-ending
args:
- --fix=lf
git hookへの登録は、次のコマンドのように行います。
pre-commit install -c .local/pre-commit-config.yaml
以上で、git commit
を行った時に、pre-commitによるfixが行われるようになります。
自分用のworkflowを作成、git hookに登録
ここでは、
リモートリポジトリにpushする前に、actからpytestを実行する設定を作成します。
この設定も、他のコードとわけるため、ここでは.local
配下に作成します。
以下のworkflowは、pytestを実行する設定の例です。
.local/workflows/unit_test.yaml
name: pytest
on:
push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- run: |
pip install -r requirements.txt
pip install -r test-requirements.txt
pytest tests/
gitのpre-push hookを以下のように作成します。
.git/hooks/pre-push
#!/usr/bin/env bash
ACT_BIN=/opt/act/bin/act
$ACT_BIN --workflows ./.local/workflows/
以上で、git push
を行った時に、actによるworkflowの実行が行われるようになります。
自分用の設定をgit管理から除外
最後に.local
をgit管理から除外しておきます。
次のように、
~/.gitconfig
にexcludesfileを指定して、そのファイルに.local
を記載しておきます。
~/.gitconfig
[core]
excludesfile = ~/.gitconfig.d/.gitignore
~/.gitconfig.d/.gitignore
.local
以上。