Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
206 changes: 163 additions & 43 deletions .claude/hooks/pre_git_quality_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,14 @@
import shutil
import subprocess
import os
import time
from pathlib import Path

# 設定
DEFAULT_TIMEOUT = 300 # 5分
MAX_RETRIES = 2 # 最大リトライ回数
RETRY_DELAY = 2 # リトライ間隔(秒)

# Read input from Claude
data = json.load(sys.stdin)
cmd = (data.get("tool_input", {}) or {}).get("command") or ""
Expand Down Expand Up @@ -87,6 +93,50 @@ def has_biome(root: str) -> bool:
return False


def detect_linter_conflicts(root: str) -> list:
"""Biome と他の lint/format ツールの競合を検出"""
conflicts = []
pkg_path = Path(root) / "package.json"

if not pkg_path.exists():
return conflicts

try:
with open(pkg_path) as f:
pkg = json.load(f)
all_deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})}
except Exception:
return conflicts

has_biome_installed = "@biomejs/biome" in all_deps
if not has_biome_installed:
return conflicts

# ESLint との競合検出
eslint_tools = ["eslint", "@eslint/js", "eslint-config-prettier"]
found_eslint = [t for t in eslint_tools if t in all_deps]
if found_eslint:
conflicts.append({
"type": "eslint",
"tools": found_eslint,
"message": "Biome と ESLint が同時に導入されています。"
"どちらか一方への統合を検討してください。",
})

# Prettier との競合検出
prettier_tools = ["prettier", "prettier-plugin-tailwindcss"]
found_prettier = [t for t in prettier_tools if t in all_deps]
if found_prettier:
conflicts.append({
"type": "prettier",
"tools": found_prettier,
"message": "Biome と Prettier が同時に導入されています。"
"Biome は Prettier 互換のフォーマッタを内蔵しています。",
})

return conflicts


def get_package_scripts(root: str) -> dict:
"""package.json の scripts を取得"""
pkg_path = Path(root) / "package.json"
Expand All @@ -105,6 +155,96 @@ def has_node_modules(root: str) -> bool:
return (Path(root) / "node_modules").exists()


def is_retryable_error(returncode: int, stderr: str) -> bool:
"""リトライ可能なエラーかどうか判定"""
# ネットワーク系エラー
network_errors = [
"ECONNREFUSED",
"ETIMEDOUT",
"ENOTFOUND",
"network error",
"socket hang up",
"EAI_AGAIN",
]
for err in network_errors:
if err in stderr:
return True
# 一時的なファイルロック
if "EBUSY" in stderr or "resource busy" in stderr.lower():
return True
return False
Comment on lines +158 to +175

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Unused returncode parameter.

The returncode parameter is declared but never used in the function body. The current implementation only checks stderr content for retryable error patterns.

Consider either removing the parameter or using it to identify additional retryable conditions (e.g., specific exit codes that indicate transient failures).

🔧 Option 1: Remove unused parameter
-def is_retryable_error(returncode: int, stderr: str) -> bool:
+def is_retryable_error(stderr: str) -> bool:
     """リトライ可能なエラーかどうか判定"""

Then update the call site at line 205-206:

-            if attempt < max_retries and is_retryable_error(
-                result.returncode, result.stderr
-            ):
+            if attempt < max_retries and is_retryable_error(result.stderr):
🔧 Option 2: Use returncode for additional checks
 def is_retryable_error(returncode: int, stderr: str) -> bool:
     """リトライ可能なエラーかどうか判定"""
+    # Transient exit codes (e.g., signal interrupts)
+    if returncode in (130, 137, 143):  # SIGINT, SIGKILL, SIGTERM
+        return True
+
     # ネットワーク系エラー
     network_errors = [
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def is_retryable_error(returncode: int, stderr: str) -> bool:
"""リトライ可能なエラーかどうか判定"""
# ネットワーク系エラー
network_errors = [
"ECONNREFUSED",
"ETIMEDOUT",
"ENOTFOUND",
"network error",
"socket hang up",
"EAI_AGAIN",
]
for err in network_errors:
if err in stderr:
return True
# 一時的なファイルロック
if "EBUSY" in stderr or "resource busy" in stderr.lower():
return True
return False
def is_retryable_error(returncode: int, stderr: str) -> bool:
"""リトライ可能なエラーかどうか判定"""
# Transient exit codes (e.g., signal interrupts)
if returncode in (130, 137, 143): # SIGINT, SIGKILL, SIGTERM
return True
# ネットワーク系エラー
network_errors = [
"ECONNREFUSED",
"ETIMEDOUT",
"ENOTFOUND",
"network error",
"socket hang up",
"EAI_AGAIN",
]
for err in network_errors:
if err in stderr:
return True
# 一時的なファイルロック
if "EBUSY" in stderr or "resource busy" in stderr.lower():
return True
return False
🧰 Tools
🪛 Ruff (0.15.4)

[warning] 158-158: Unused function argument: returncode

(ARG001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.claude/hooks/pre_git_quality_gates.py around lines 158 - 175, The function
is_retryable_error currently declares an unused returncode parameter; remove
that parameter from the function signature (change def
is_retryable_error(stderr: str) -> bool) and update every call site that passes
a return code to instead call is_retryable_error(stderr) so the function only
inspects stderr; ensure you update import/type hints if any and run tests to
confirm all callers compile.



def run_with_retry(
command: list,
cwd: str,
timeout: int = DEFAULT_TIMEOUT,
max_retries: int = MAX_RETRIES,
) -> tuple:
"""リトライ付きコマンド実行

Returns:
tuple: (success: bool, result: dict)
"""
last_result = None

for attempt in range(max_retries + 1):
try:
result = subprocess.run(
command,
cwd=cwd,
capture_output=True,
text=True,
timeout=timeout,
)

if result.returncode == 0:
return True, {"stdout": result.stdout, "stderr": result.stderr}

# リトライ可能なエラーかチェック
if attempt < max_retries and is_retryable_error(
result.returncode, result.stderr
):
time.sleep(RETRY_DELAY)
continue

last_result = {
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode,
}

# ツール未インストールの場合はスキップ扱い
is_tool_missing = (
result.returncode == 127
or "command not found" in result.stderr
or "No such file or directory" in result.stderr
)
if is_tool_missing:
return True, {"skipped": True, "reason": "ツール未インストール"}

return False, last_result

except subprocess.TimeoutExpired:
last_result = {"error": f"タイムアウト ({timeout}秒)"}
if attempt < max_retries:
time.sleep(RETRY_DELAY)
continue
return False, last_result

except FileNotFoundError:
return True, {"skipped": True, "reason": "コマンド未検出"}

except Exception as e:
last_result = {"error": str(e)}
if attempt < max_retries:
time.sleep(RETRY_DELAY)
continue
return False, last_result

return False, last_result or {"error": "Unknown error"}


# package.json のスクリプトを取得
scripts = get_package_scripts(repo_root)
if not scripts:
Expand All @@ -122,6 +262,16 @@ def has_node_modules(root: str) -> bool:
file=sys.stderr, flush=True)
sys.exit(2)

# Biome と他の lint ツールの競合警告
conflicts = detect_linter_conflicts(repo_root)
if conflicts:
print("", file=sys.stderr, flush=True)
print("⚠️ [Lint Tool Conflict Warning]", file=sys.stderr, flush=True)
for conflict in conflicts:
print(f" • {conflict['message']}", file=sys.stderr, flush=True)
print(f" 対象: {', '.join(conflict['tools'])}", file=sys.stderr, flush=True)
print("", file=sys.stderr, flush=True)

# 実行するチェックを自動検出
# 優先度順: format:check > format > lint > test > typecheck > shellcheck
CHECK_CANDIDATES = [
Expand Down Expand Up @@ -217,54 +367,24 @@ def has_node_modules(root: str) -> bool:
print(f" ▶ {check['name']}: {check['description']}",
file=sys.stderr, flush=True)

try:
result = subprocess.run(
check["command"],
cwd=repo_root,
capture_output=True,
text=True,
timeout=300,
)

if result.returncode != 0:
# ツール未インストール等の場合はスキップ
is_tool_missing = (
result.returncode == 127
or "command not found" in result.stderr
or "No such file or directory" in result.stderr
)
if is_tool_missing:
print(" ⚠ スキップ (ツール未インストール)",
file=sys.stderr, flush=True)
else:
failed_checks.append({
"name": check["name"],
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode,
})
print(f" ✗ 失敗 (exit code: {result.returncode})",
file=sys.stderr, flush=True)
success, result = run_with_retry(check["command"], repo_root)

if success:
if result.get("skipped"):
print(f" ⚠ スキップ ({result['reason']})",
file=sys.stderr, flush=True)
else:
print(" ✓ 成功", file=sys.stderr, flush=True)

except subprocess.TimeoutExpired:
else:
failed_checks.append({
"name": check["name"],
"error": "タイムアウト (5分)",
**result,
})
print(" ✗ タイムアウト", file=sys.stderr, flush=True)

except FileNotFoundError:
print(" ⚠ スキップ (コマンド未検出)",
file=sys.stderr, flush=True)

except Exception as e:
failed_checks.append({
"name": check["name"],
"error": str(e),
})
print(f" ✗ エラー: {e}", file=sys.stderr, flush=True)
if "error" in result:
print(f" ✗ {result['error']}", file=sys.stderr, flush=True)
else:
print(f" ✗ 失敗 (exit code: {result.get('returncode', '?')})",
file=sys.stderr, flush=True)

# 失敗があればブロック
if failed_checks:
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ The `git/gitconfig` file uses commented placeholders instead of hardcoded values
```bash
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
git config --global user.signingkey ~/.ssh/id_ed25519.pub
```

### Setup Instructions
Expand Down Expand Up @@ -85,7 +85,7 @@ git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
```bash
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
git config --global user.signingkey ~/.ssh/id_ed25519.pub
```

5. **Install packages using Homebrew**
Expand Down
4 changes: 2 additions & 2 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ SSH鍵をgitconfigに直接記載せず、以下の方法で設定してくだ
# SSH鍵を生成(まだ持っていない場合)
ssh-keygen -t ed25519 -C "your.email@example.com"

# 公開鍵を署名鍵として設定
git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
# SSH公開鍵のパスを署名鍵として設定
git config --global user.signingkey ~/.ssh/id_ed25519.pub

# GPG形式の署名を使用する場合
# git config --global user.signingkey YOUR_GPG_KEY_ID
Expand Down
4 changes: 2 additions & 2 deletions credentials/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ make credentials
[user]
# name = # Configure with: git config --global user.name "Your Name"
# email = # Configure with: git config --global user.email "your.email@example.com"
# signingkey = # Configure with: git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
# signingkey = # Configure with: git config --global user.signingkey ~/.ssh/id_ed25519.pub
```

### シェル環境変数トークンのフィルタリング
Expand Down Expand Up @@ -146,7 +146,7 @@ export BUNDLE_RUBYGEMS__PKG__GITHUB__COM="op://Dev/GITHUB_TOKEN/credential"
以下のコマンドで設定してください:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
git config --global user.signingkey ~/.ssh/id_ed25519.pub
```

## 1Password Vault 推奨構造
Expand Down
2 changes: 1 addition & 1 deletion git/gitconfig
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[user]
# name = # Configure with: git config --global user.name "Your Name"
# email = # Configure with: git config --global user.email "your.email@example.com"
# signingkey = # Configure with: git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
# signingkey = # Configure with: git config --global user.signingkey ~/.ssh/id_ed25519.pub

[url "https://github.com/"]
insteadOf = git@github.com:
Expand Down
Loading
Loading