-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·298 lines (247 loc) · 8.95 KB
/
install.sh
File metadata and controls
executable file
·298 lines (247 loc) · 8.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/bin/bash
set -euo pipefail
# ============================================================
# 曜日バリデーター for Claude Code — インストーラー
# ============================================================
#
# 使い方:
# curl -sL <URL>/install.sh | bash
# または
# bash install.sh
#
# 何をするか:
# 1. ~/.claude/hooks/validate_dates.py を配置
# 2. ~/.claude/settings.json にPostToolUseフックを追加
#
# アンインストール:
# bash install.sh --uninstall
# ============================================================
HOOK_DIR="$HOME/.claude/hooks"
HOOK_FILE="$HOOK_DIR/validate_dates.py"
SETTINGS_FILE="$HOME/.claude/settings.json"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
info() { echo -e "${GREEN}[OK]${NC} $1"; }
warn() { echo -e "${YELLOW}[注意]${NC} $1"; }
error() { echo -e "${RED}[エラー]${NC} $1"; }
# --- アンインストール ---
if [[ "${1:-}" == "--uninstall" ]]; then
echo "曜日バリデーターをアンインストールします..."
if [[ -f "$HOOK_FILE" ]]; then
rm "$HOOK_FILE"
info "validate_dates.py を削除しました"
else
warn "validate_dates.py は見つかりませんでした"
fi
if [[ -f "$SETTINGS_FILE" ]]; then
# settings.json からフック設定を除去
python3 -c "
import json, sys
with open('$SETTINGS_FILE', 'r') as f:
settings = json.load(f)
hooks = settings.get('hooks', {})
post_hooks = hooks.get('PostToolUse', [])
# validate_dates を含むエントリを除去
new_post_hooks = []
for entry in post_hooks:
hook_list = entry.get('hooks', [])
filtered = [h for h in hook_list if 'validate_dates' not in h.get('command', '')]
if filtered:
entry['hooks'] = filtered
new_post_hooks.append(entry)
if new_post_hooks:
hooks['PostToolUse'] = new_post_hooks
else:
hooks.pop('PostToolUse', None)
if hooks:
settings['hooks'] = hooks
else:
settings.pop('hooks', None)
with open('$SETTINGS_FILE', 'w') as f:
json.dump(settings, f, indent=2, ensure_ascii=False)
f.write('\n')
"
info "settings.json からフック設定を除去しました"
fi
echo ""
info "アンインストール完了!"
exit 0
fi
# --- インストール ---
echo ""
echo "================================================"
echo " 曜日バリデーター for Claude Code"
echo " 日付+曜日の間違いを自動検出するフック"
echo "================================================"
echo ""
# Python3 確認
if ! command -v python3 &>/dev/null; then
error "python3 が見つかりません。Python 3 をインストールしてください。"
exit 1
fi
info "Python3 確認OK"
# ディレクトリ作成
mkdir -p "$HOOK_DIR"
# スクリプトのソースを判定(同じディレクトリにあるか、インライン埋め込みか)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_PY="$SCRIPT_DIR/validate_dates.py"
if [[ -f "$SOURCE_PY" ]]; then
# ローカルファイルからコピー
cp "$SOURCE_PY" "$HOOK_FILE"
else
# インライン生成
cat > "$HOOK_FILE" << 'PYTHON_SCRIPT'
#!/usr/bin/env python3
"""
日本語テキスト中の日付+曜日パターンを検証するClaude Codeフック。
Write/Edit後に自動実行し、曜日の間違いがあれば警告を出力する。
"""
import json
import re
import sys
from datetime import date
WEEKDAYS_JA = {
0: '月', 1: '火', 2: '水', 3: '木', 4: '金', 5: '土', 6: '日',
}
PATTERNS = [
re.compile(r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日\s*[((]\s*([月火水木金土日])\s*(?:曜日?)?\s*[))]'),
re.compile(r'(?<!\d)(\d{1,2})\s*月\s*(\d{1,2})\s*日\s*[((]\s*([月火水木金土日])\s*(?:曜日?)?\s*[))]'),
re.compile(r'(\d{4})\s*[/\-]\s*(\d{1,2})\s*[/\-]\s*(\d{1,2})\s*[((]\s*([月火水木金土日])\s*(?:曜日?)?\s*[))]'),
re.compile(r'(?<!\d)(\d{1,2})\s*/\s*(\d{1,2})\s*[((]\s*([月火水木金土日])\s*(?:曜日?)?\s*[))]'),
]
def guess_year(month, day):
today = date.today()
candidate = today.year
try:
d = date(candidate, month, day)
if (today - d).days > 90:
candidate += 1
except ValueError:
pass
return candidate
def validate_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
except (OSError, UnicodeDecodeError):
return []
errors = []
for line_num, line in enumerate(content.split('\n'), 1):
for m in PATTERNS[0].finditer(line):
year, month, day, wd = int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4)
err = check_weekday(year, month, day, wd, line_num, m.group(0))
if err:
errors.append(err)
for m in PATTERNS[1].finditer(line):
if PATTERNS[0].search(line[max(0, m.start()-5):m.end()]):
continue
month, day, wd = int(m.group(1)), int(m.group(2)), m.group(3)
err = check_weekday(guess_year(month, day), month, day, wd, line_num, m.group(0))
if err:
errors.append(err)
for m in PATTERNS[2].finditer(line):
year, month, day, wd = int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4)
err = check_weekday(year, month, day, wd, line_num, m.group(0))
if err:
errors.append(err)
for m in PATTERNS[3].finditer(line):
if PATTERNS[2].search(line[max(0, m.start()-5):m.end()]):
continue
month, day, wd = int(m.group(1)), int(m.group(2)), m.group(3)
err = check_weekday(guess_year(month, day), month, day, wd, line_num, m.group(0))
if err:
errors.append(err)
return errors
def check_weekday(year, month, day, weekday_ja, line_num, matched):
try:
d = date(year, month, day)
correct = WEEKDAYS_JA[d.weekday()]
if weekday_ja != correct:
return (
f'[日付エラー] 行{line_num}: "{matched}" → '
f'{year}年{month}月{day}日は{weekday_ja}曜日ではなく【{correct}曜日】です'
)
except ValueError:
return f'[日付エラー] 行{line_num}: "{matched}" → 無効な日付です({year}/{month}/{day})'
return None
def main():
tool_input = json.loads(sys.stdin.read())
file_path = tool_input.get('tool_input', {}).get('file_path', '')
if not file_path:
return
if not any(file_path.endswith(ext) for ext in ('.md', '.html', '.txt', '.csv', '.json')):
return
errors = validate_file(file_path)
if errors:
print('\n'.join(errors), file=sys.stderr)
sys.exit(2)
if __name__ == '__main__':
main()
PYTHON_SCRIPT
fi
chmod +x "$HOOK_FILE"
info "validate_dates.py を配置しました → $HOOK_FILE"
# --- settings.json にフック追加 ---
if [[ ! -f "$SETTINGS_FILE" ]]; then
echo '{}' > "$SETTINGS_FILE"
warn "settings.json を新規作成しました"
fi
# バックアップ
cp "$SETTINGS_FILE" "${SETTINGS_FILE}.bak.$(date +%Y%m%d%H%M%S)"
info "settings.json のバックアップを作成しました"
# Python でJSONを安全に編集
python3 << 'PYEOF'
import json
import sys
settings_file = "$HOME/.claude/settings.json".replace("$HOME", __import__("os").path.expanduser("~"))
with open(settings_file, 'r') as f:
settings = json.load(f)
# 既にインストール済みか確認
hooks = settings.get('hooks', {})
post_hooks = hooks.get('PostToolUse', [])
already_installed = False
for entry in post_hooks:
for h in entry.get('hooks', []):
if 'validate_dates' in h.get('command', ''):
already_installed = True
break
if already_installed:
print("[注意] フック設定は既にインストール済みです。スキップします。", file=sys.stderr)
sys.exit(0)
# 新しいフックエントリを追加
new_hook_entry = {
"hooks": [
{
"command": "python3 ~/.claude/hooks/validate_dates.py",
"statusMessage": "日付+曜日の整合性チェック",
"timeout": 10,
"type": "command"
}
],
"matcher": "Write|Edit|MultiEdit"
}
post_hooks.append(new_hook_entry)
hooks['PostToolUse'] = post_hooks
settings['hooks'] = hooks
with open(settings_file, 'w') as f:
json.dump(settings, f, indent=2, ensure_ascii=False)
f.write('\n')
PYEOF
info "settings.json にフック設定を追加しました"
echo ""
echo "================================================"
echo " インストール完了!"
echo "================================================"
echo ""
echo " Claude Codeでファイルを編集すると、"
echo " 日付+曜日の整合性が自動チェックされます。"
echo ""
echo " 対応フォーマット:"
echo " 4月29日(火) 2026年4月29日(水)"
echo " 4/29(火) 2026/4/29(水)"
echo ""
echo " アンインストール:"
echo " bash install.sh --uninstall"
echo ""