---
# System prepended metadata

title: gitHook
tags: [Git]

---

---
title: gitHook
tags: Git
---

# pre-commit-hooks

- 定義在 `.pre-commit-config.yaml`
- git hook 會被寫入於 `.git/hooks/` (註: `.git/hooks/`不會被加入版控)
- 大部分都可以從 [pre-commit-hooks](https://github.com/pre-commit/pre-commit-hooks) 找到所需的 hooks
-  black 和 flake8 等工具也都有提供 pre-commit hook

## Scenario
- 初步過濾顯而易見的錯誤
- pre-commit hooks 的作用域僅限 local
- 當有足夠的 UT 可以在 pre-commit 階段跑
- server 端可以設置強制性的 pre-receive hook
:::danger
可以透過 `--no-verify` 繞過檢查:
```bash=
git commit --no-verify
```
:::

## Installation
作為 python package 安裝:
```bash=
pip install pre-commit-hooks
```

## hooks of client / server

### Client-side hooks
- pre-commit
- prepare-commit-msg
- commit-msg
- post-commit
- post-checkout
- pre-rebase
### Server-side hooks
- pre-receive
- update
- post-receive

### 使用時機

    (Client-side, Pre-*)：coding style checking
    (Client-side, Post-*)：check branch status for safety
    (Server-side, Pre-*)：protect master
    (Server-side, Post-*)：notification

## Usage

```bash=
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.0.1  # Use the ref you want to point at
    hooks:
    -   id: trailing-whitespace
    # -   id: ...
```
- `repos`: pre-commit 從哪裡獲取 hook 
    - `repo`: finding git repository, i.e., pre-commit-hooks
    - `rev`: version of the repository
    - `hooks`: indicating a specific hook
        - `id`: hook id
        - `args`: additional augments


## 檢查目錄下所有檔案

```bash=
pre-commit run --all-files
```


## Content

### check code regulation
- black
    > https://github.com/psf/black
    > is the uncompromising Python code formatter
- flake8
    > https://gitlab.com/pycqa/flake8
    > python-specified, PEP8 standard
- double-quote-string-fixer
    > replaces double quoted strings with single quoted strings.
- trailing-whitespace
    > Trims trailing whitespace.


### check security
- aws-credentials
    > Checks for the existence of AWS secrets that you have set up with the AWS CLI.
- private-key
    > Checks for the existence of private keys.
### check format
- check-json
    > Attempts to load all json files to verify syntax.
- check-yaml
    > Attempts to load all yaml files to verify syntax.
### check at least
- check-added-large-files
    > Prevent giant files from being committed.
- check-merge-conflict
    > Check for files that contain merge conflict strings.
- check-ast
    > Simply check whether files parse as valid python.


## Ref
- https://github.com/pre-commit/pre-commit-hooks
- https://mropengate.blogspot.com/2019/08/pre-commit-git-hooks_4.html
- https://zh-tw.coderbridge.com/series/66cb226274ea4d349abd49d2aef44037/posts/25dbe7d486ed453eb314ca25b069bac9
