[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,95 +2,186 @@
|
||||
id: wiki-2026-0508-husky
|
||||
title: Husky
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-9068BA]
|
||||
aliases: [Husky Git Hooks, husky v9, lint-staged, pre-commit]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [git, hooks, devex, ci, lint-staged]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Husky"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: javascript
|
||||
framework: husky-v9
|
||||
---
|
||||
|
||||
# [[Husky|Husky]]
|
||||
# Husky
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Husky는 개발 프로젝트에서 Git 훅([[Git Hooks|Git Hooks]])을 쉽게 설정, 관리 및 팀원들과 공유할 수 있도록 지원하는 소프트웨어 도구입니다 [1]. 기본적으로 버전 관리 대상이 아닌 Git 훅의 한계를 극복하여 `.husky/`와 같은 추적 가능한 디렉토리를 통해 훅 스크립트를 관리하게 해줍니다 [1, 2]. 주로 `[[lint-staged|lint-staged]]`와 결합하여 커밋이나 푸시 전에 자동으로 코드 린팅(linting) 및 포맷팅을 수행하여 코드 품질을 강제하는 데 사용됩니다 [3, 4].
|
||||
## 매 한 줄
|
||||
> **"매 npm-friendly git hooks 의 facto-standard"**. Husky 는 매 `.husky/` directory 안에 매 plain shell script 로 hook 정의 — 매 `git config core.hooksPath` 으로 자동 설정. 매 v9 (2024-2026) 부터 매 거의 zero-config: `npx husky init` → 매 husky/_/h prepare-commit-msg 등 매 wrapper 자동 생성. 매 lint-staged 와의 매 pairing 이 매 표준 setup.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **Git 훅의 한계 극복 및 구동 원리:** Git의 기본 훅은 `.git/hooks/` 디렉토리에 저장되어 버전 관리 도구에 의해 추적되지 않습니다. 이로 인해 새로운 팀원이 프로젝트를 클론할 때 훅이 자동으로 설정되지 않는 문제가 발생합니다 [1]. Husky는 Git의 `core.hooksPath` 속성을 사용하여 추적 가능한 디렉토리(예: `.husky/`)에 실제 훅 파일(셸 스크립트)을 생성하고 관리함으로써 이 문제를 해결합니다 [1, 2].
|
||||
* **설치 및 자동화 설정:** `npx husky init` (또는 `husky-init`) 명령어를 실행하면 프로젝트 루트에 `.husky` 폴더가 생성되고 `package.json`에 `prepare` 스크립트가 추가됩니다 [5-7]. 이 `prepare` 스크립트는 팀원들이 로컬에서 `npm install`을 실행할 때 Husky 훅이 자동으로 설치되도록 보장하여 모든 팀원이 동일한 검사 환경을 갖추게 합니다 [5-7].
|
||||
* **lint-staged와의 결합:** 전체 프로젝트 코드를 매번 검사하는 것은 많은 시간이 소요되므로, Husky의 `pre-commit` 훅 내부에서 `lint-staged`를 호출하는 방식이 현대적인 표준 설정으로 사용됩니다 [1, 8, 9]. 이 조합을 통해 커밋을 위해 스테이징된(staged) 파일에 대해서만 [[ESLint|ESLint]]나 [[Prettier|Prettier]]를 실행함으로써 1~2초 내에 검사를 완료할 수 있습니다 [1, 9].
|
||||
* **검사 우회(Bypass) 및 환경 설정:** 개발 과정에서 미완성 코드를 커밋해야 하는 등 훅 실행을 건너뛰어야 할 때는 Git의 기본 기능인 `--no-verify` 플래그(예: `git commit --no-verify`)를 사용할 수 있습니다 [10, 11]. 또한 CI 서버나 프로덕션 환경 등 훅 설치 및 실행이 필요 없는 경우, `HUSKY=0` 환경 변수를 설정하여 Husky를 완전히 비활성화할 수 있습니다 [12].
|
||||
* **예외 상황 및 트러블슈팅:**
|
||||
* **GUI 및 버전 관리자 이슈:** SourceTree나 VS Code 같은 Git GUI 도구나 Node 버전 관리자(nvm, fnm 등)를 사용할 때 `PATH`가 제대로 초기화되지 않아 훅에서 명령어를 찾을 수 없는 오류(`command not found`)가 발생할 수 있습니다. Husky는 각 훅을 실행하기 전에 `~/.config/husky/init.sh`를 소싱(source)하여 이 문제를 우회할 수 있도록 지원합니다 [13, 14].
|
||||
* **서브모듈 및 중첩 패키지:** 모노레포나 서브모듈([[Submodules|Submodules]]) 구조에서는 최상위 루트가 아닌 하위 디렉토리에 패키지가 위치할 수 있습니다. Git은 기본적으로 리포지토리 루트에서 훅을 실행하므로, 이런 경우 `prepare` 스크립트 내에서 경로를 이동하거나(cd) 서브모듈의 컨텍스트 내에 Husky를 개별적으로 설치하여 동작하도록 구성해야 합니다 [14, 15].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 핵심 개념
|
||||
- **core.hooksPath = .husky/_**: Husky 가 매 이 path 로 git 을 redirect — 매 user 의 매 hook script 와 매 husky framework script 분리.
|
||||
- **Plain shell**: 매 `.husky/pre-commit` 의 매 첫 line shebang 없이 — Husky v9 가 매 `_/h` wrapper 통해 실행.
|
||||
- **Skip via env**: `HUSKY=0` 또는 `HUSKY_SKIP_HOOKS=1` — 매 CI 또는 emergency commit.
|
||||
- **prepare script**: `package.json` 의 `"prepare": "husky"` 가 매 install 시 자동 setup.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Git Hooks|Git Hooks]], lint-staged, ESLint, [[Prettier|Prettier]]
|
||||
- **Projects/Contexts:** CI/CD Pipeline, [[Monorepo|Monorepo]], [[Submodules|Submodules]]
|
||||
- **Contradictions/Notes:** 소스에 따르면, 많은 개발자가 Husky와 `lint-staged`를 혼동하여 하나의 덩어리로 생각하곤 합니다. 하지만 두 도구는 명확히 구분되어야 합니다. Husky는 단순히 Git의 기본 훅을 관리하고 연결하는 '배선(hook wiring)' 역할을 할 뿐 작업 실행기(task runner)가 아니며, 실제 변경된 파일 단위로 작업을 오케스트레이션 하는 것은 `lint-staged`의 역할입니다 [2, 4, 16].
|
||||
### 매 lint-staged 와의 결합
|
||||
- 매 staged files 만 lint/format → 매 commit 속도 ↑.
|
||||
- 매 prettier --write + eslint --fix + 매 자동 re-stage.
|
||||
- 매 large monorepo 에서도 매 fast (only changed paths).
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
### 매 hook 우선순위 (자주 쓰는)
|
||||
1. **pre-commit**: lint-staged + type-check (changed only).
|
||||
2. **commit-msg**: commitlint (Conventional Commits 검증).
|
||||
3. **pre-push**: full test suite + build smoke.
|
||||
4. **post-merge**: pnpm install if `package.json` changed.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Initial setup
|
||||
```bash
|
||||
# in repo root
|
||||
pnpm add -D husky lint-staged
|
||||
pnpm pkg set scripts.prepare="husky"
|
||||
pnpm prepare
|
||||
npx husky init # creates .husky/pre-commit with `npm test` placeholder
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### .husky/pre-commit (lint-staged + type-check)
|
||||
```sh
|
||||
npx lint-staged
|
||||
pnpm exec tsc --noEmit
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### lint-staged config (package.json)
|
||||
```json
|
||||
{
|
||||
"lint-staged": {
|
||||
"*.{ts,tsx,js,jsx}": [
|
||||
"eslint --fix --max-warnings=0",
|
||||
"prettier --write"
|
||||
],
|
||||
"*.{json,md,yml,yaml}": ["prettier --write"],
|
||||
"*.css": ["stylelint --fix", "prettier --write"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### .husky/commit-msg (commitlint)
|
||||
```sh
|
||||
npx --no -- commitlint --edit "$1"
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
```js
|
||||
// commitlint.config.js
|
||||
module.exports = {
|
||||
extends: ['@commitlint/config-conventional'],
|
||||
rules: {
|
||||
'subject-max-length': [2, 'always', 100],
|
||||
'scope-enum': [2, 'always', ['ui', 'api', 'docs', 'ci', 'deps']],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### .husky/pre-push (test + build)
|
||||
```sh
|
||||
pnpm test --run --silent
|
||||
pnpm build
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Skip in CI / emergency
|
||||
```bash
|
||||
# CI: prepare script no-op when not in dev install
|
||||
# package.json
|
||||
{
|
||||
"scripts": {
|
||||
"prepare": "node -e \"if (process.env.CI) process.exit(0)\" && husky"
|
||||
}
|
||||
}
|
||||
|
||||
# Emergency commit (use sparingly)
|
||||
HUSKY=0 git commit -m "hotfix: critical patch"
|
||||
# or
|
||||
git commit --no-verify -m "..."
|
||||
```
|
||||
|
||||
### Monorepo: only run hooks if relevant
|
||||
```sh
|
||||
# .husky/pre-commit
|
||||
CHANGED=$(git diff --cached --name-only)
|
||||
echo "$CHANGED" | grep -q "^apps/web/" && (cd apps/web && pnpm lint-staged)
|
||||
echo "$CHANGED" | grep -q "^apps/api/" && (cd apps/api && pnpm lint-staged)
|
||||
```
|
||||
|
||||
### Conditional hook based on branch
|
||||
```sh
|
||||
# .husky/pre-push
|
||||
BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||
if [ "$BRANCH" = "main" ]; then
|
||||
pnpm test --run
|
||||
pnpm build
|
||||
else
|
||||
pnpm test --run --bail=1
|
||||
fi
|
||||
```
|
||||
|
||||
### Adopt in existing repo
|
||||
```bash
|
||||
# After cloning, dependencies need install to run 'prepare'
|
||||
pnpm install # triggers `prepare` → husky sets core.hooksPath
|
||||
git config --get core.hooksPath # → .husky/_
|
||||
```
|
||||
|
||||
### Husky + pnpm workspaces filter
|
||||
```sh
|
||||
# .husky/pre-commit
|
||||
STAGED=$(git diff --cached --name-only)
|
||||
PKGS=$(echo "$STAGED" | awk -F/ '/^packages\// {print $2}' | sort -u)
|
||||
for p in $PKGS; do
|
||||
pnpm --filter "@repo/$p" lint-staged
|
||||
done
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| TS/JS project | Husky v9 + lint-staged |
|
||||
| Polyglot (Python, Go) | pre-commit framework (multi-lang) |
|
||||
| Heavy hooks (>10s) | move to pre-push, lighten pre-commit |
|
||||
| Solo dev hobby | optional — lint in CI alone may suffice |
|
||||
| Enterprise enforcement | husky + commitlint + branch protection |
|
||||
|
||||
**기본값**: 매 TS/JS team — Husky v9 + lint-staged + commitlint.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Git Hooks]] · [[DevEx]]
|
||||
- 변형: [[pre-commit]] · [[lefthook]] · [[simple-git-hooks]]
|
||||
- 응용: [[Lint-Staged]] · [[Commitlint]] · [[Conventional Commits]]
|
||||
- Adjacent: [[ESLint]] · [[Prettier]] · [[Biome]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 hook script 작성, lint-staged config 생성, commitlint rule 제안, monorepo conditional logic.
|
||||
**언제 X**: 매 binary install verification — local 환경에서 매 직접 실행.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **30s pre-commit**: 매 dev 가 매 --no-verify 습관화 → 매 hook 무용지물.
|
||||
- **Run full test in pre-commit**: 매 pre-push 로 옮기기.
|
||||
- **No CI fallback**: 매 hook 만 신뢰 → 매 --no-verify bypass 시 dirty commit.
|
||||
- **Husky 의 commit hook 안 비밀 커밋 검증 누락**: 매 detect-secrets / gitleaks pairing.
|
||||
- **Per-developer husky version drift**: 매 lockfile pin 필수.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Husky v9 docs 2026, lint-staged v15+).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Husky v9 + lint-staged + commitlint patterns |
|
||||
|
||||
Reference in New Issue
Block a user