Pre-Commit 설정

강태원·2023년 12월 16일
1

뒤에 내용들을 블로그에 게시하기 전에, 너무 코드들이 깔끔하지 못하고 더러워보여서 미약하게나마 리팩토링을 진행한다고 조금 글이 늦어졌다.

Pre-Commit

Pre-Commit이란?

깃허브와 같은 코드 저장소에 커밋을 수행하기 전에 포맷팅이나 린팅이 잘 되어 있는지 확인해주는 도구라고 볼 수 있다. 리팩토링을 진행하면서 코드 가독성을 높이기 위해 도입해보았다.

pip install pre-commit
pre-commit install

먼저 pre-commit을 설치해준 뒤

.vscode/
 ㄴ settings.json
pyproject.toml
.flake8
.pre-commit-config.yaml

최상위 깃에 위 파일들을 생성한다.

settings.json

# settings.json
{
"python.linting.flake8Enabled": true,
  "python.linting.flake8Args": [
      "--max-line-length=100"
  ],
  "python.formatting.provider": "black",
  "python.formatting.blackArgs": ["--line-length", "100"]
}

.flake8

# .flake8
[flake8]
exclude =
    .git,
    .gitignore,
    *.pot,
    *.py[co],
    __pycache__,
    venv,
    .env

ignore =
    E121,
    E126,
    E127,
    E128,
    E203,
    E225,
    E226,
    E231,
    E241,
    E251,
    E261,
    E265,
    E302,
    E303,
    E305,
    E402,
    E501,
    E741,
    W291,
    W292,
    W293,
    W391,
    W503,
    W504,
    F403,
    B007,
    B950,

max-line-length = 100

.pyproject.toml

# .pyproject.toml

[tool.black]
line-length = 100
target-version = ['py311']
exclude = '''
  \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist
'''

[tool.flake8]
max-line-length = 100

.pre-commit-config.yaml

# .pre-commit-config.yaml

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

  - repo: https://github.com/psf/black
    rev: 23.9.1
    hooks:
      - id: black
        name: black
        description: "Black: The uncompromising Python code formatter"
        entry: black
        language: python
        minimum_pre_commit_version: 2.9.2
        require_serial: true
        types_or: [python, pyi]

  - repo: https://github.com/pycqa/flake8
    rev: 6.1.0
    hooks:
      - id: flake8

이렇게 설정 파일들을 각각 작성해주고 난 뒤 vscode에서 저장하면 black 포맷터가 자동으로 파일을 포맷팅해준다.

이 후 pre-commit을 설치한 가상환경을 activate하고 git commit 했을 때 pre-commit이 제대로 작동하는 것을 확인할 수 있다.

[예시]

profile
가치를 창출하는 개발자! 가 목표입니다

0개의 댓글