尝试启动钩子
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
|
||||
# 从 stdin 加载输入
|
||||
try:
|
||||
input_data = json.load(sys.stdin)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
context_parts = []
|
||||
|
||||
# 添加项目基本信息
|
||||
if os.path.exists("package.json"):
|
||||
context_parts.append("这是一个 Node.js 项目")
|
||||
elif os.path.exists("requirements.txt") or os.path.exists("pyproject.toml"):
|
||||
context_parts.append("这是一个 Python 项目")
|
||||
elif os.path.exists("Cargo.toml"):
|
||||
context_parts.append("这是一个 Rust 项目")
|
||||
|
||||
# 添加 Git 状态信息
|
||||
try:
|
||||
result = subprocess.run(["git", "status", "--porcelain"],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
if result.stdout.strip():
|
||||
context_parts.append("当前有未提交的更改")
|
||||
else:
|
||||
context_parts.append("工作目录是干净的")
|
||||
|
||||
# 获取当前分支
|
||||
branch_result = subprocess.run(["git", "branch", "--show-current"],
|
||||
capture_output=True, text=True)
|
||||
if branch_result.returncode == 0:
|
||||
branch = branch_result.stdout.strip()
|
||||
context_parts.append(f"当前分支:{branch}")
|
||||
except:
|
||||
pass
|
||||
|
||||
# 添加最近的活动信息
|
||||
if os.path.exists(".claude"):
|
||||
context_parts.append("项目已配置 Claude Code")
|
||||
|
||||
# 添加时间信息
|
||||
current_time = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||
context_parts.append(f"会话开始时间:{current_time}")
|
||||
|
||||
# 构建上下文信息
|
||||
if context_parts:
|
||||
additional_context = "项目状态概览:\n" + "\n".join(f"- {part}" for part in context_parts)
|
||||
|
||||
# 获取全局 Claude 配置目录路径
|
||||
home_claude_dir = os.path.expanduser("~/.claude")
|
||||
# my_context = """\n重要配置信息:
|
||||
# - 全局 Claude 配置目录路径:""" + home_claude_dir + """
|
||||
# - 当你需要修改或查找全局 Claude 配置时,请始终使用此目录:""" + home_claude_dir + """
|
||||
# - 不要使用 AppData\\Roaming\\.claude,该目录在此系统上不存在"""
|
||||
|
||||
my_context = """每次回答我问题的时候要先说'是的,大先生'"""
|
||||
|
||||
output = {
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"message":"你好,大先生",
|
||||
"additionalContext": my_context
|
||||
}
|
||||
}
|
||||
print(json.dumps(output))
|
||||
print("你好,大先生222", file=sys.stderr)
|
||||
sys.exit(0)
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
name: session-namer
|
||||
description: 会话命名管理工具 - 在开始新任务前帮助命名或恢复会话
|
||||
---
|
||||
|
||||
# 会话命名管理
|
||||
|
||||
当您开始新的工作会话时,此技能帮助您管理会话命名。
|
||||
|
||||
## 当前会话状态
|
||||
|
||||
请检查是否需要命名当前会话:
|
||||
|
||||
### 可用操作
|
||||
|
||||
1. **命名当前会话**
|
||||
使用命令: `/rename <会话名称>`
|
||||
例如: `/rename 实现各向异性形变`
|
||||
|
||||
2. **恢复历史会话**
|
||||
使用命令: `/resume <会话名称>`
|
||||
或在 REPL 中使用: `/continue`
|
||||
|
||||
3. **继续当前会话**
|
||||
如果不需要命名,直接开始工作即可
|
||||
|
||||
## BladeSmith 项目常用会话命名建议
|
||||
|
||||
基于项目结构,建议的会话命名模式:
|
||||
|
||||
- **功能开发**: `feat-功能名称` (如 `feat-温度系统`)
|
||||
- **Bug 修复**: `fix-问题描述` (如 `fix-边缘约束问题`)
|
||||
- **代码重构**: `refactor-模块名称` (如 `refactor-GPU着色器`)
|
||||
- **性能优化**: `perf-优化目标` (如 `perf-网格简化`)
|
||||
- **文档编写**: `docs-文档主题` (如 `docs-API文档`)
|
||||
- **测试相关**: `test-测试内容` (如 `test-形变系统`)
|
||||
|
||||
## 最近的 Git 分支作为参考
|
||||
|
||||
当前分支: hammer-deformation-phase1
|
||||
|
||||
如果需要查看更多分支或上下文,我可以帮您:
|
||||
- 列出最近的 git 分支
|
||||
- 查看最近的提交历史
|
||||
- 查看未完成的工作
|
||||
|
||||
---
|
||||
|
||||
**是否需要我帮助您命名当前会话?** 请告诉我您计划做什么,或者直接使用 `/rename` 命令。
|
||||
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Claude Code 启动时显示系统信息和统计
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
import subprocess
|
||||
import platform
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
def get_file_count(directory, pattern="*"):
|
||||
"""获取目录下匹配模式的文件数量"""
|
||||
try:
|
||||
return len(list(Path(directory).rglob(pattern)))
|
||||
except:
|
||||
return 0
|
||||
|
||||
def get_repo_stats():
|
||||
"""获取 Git 仓库统计信息"""
|
||||
stats = {}
|
||||
try:
|
||||
# 获取提交数量
|
||||
result = subprocess.run(
|
||||
["git", "rev-list", "--count", "HEAD"],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
if result.returncode == 0:
|
||||
stats['commits'] = result.stdout.strip()
|
||||
|
||||
# 获取最新提交
|
||||
result = subprocess.run(
|
||||
["git", "log", "-1", "--format=%h %s"],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
if result.returncode == 0:
|
||||
stats['latest'] = result.stdout.strip()
|
||||
|
||||
# 获取分支数量
|
||||
result = subprocess.run(
|
||||
["git", "branch", "-a"],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
if result.returncode == 0:
|
||||
branches = [line for line in result.stdout.split('\n') if line.strip()]
|
||||
stats['branches'] = len(branches)
|
||||
|
||||
except Exception as e:
|
||||
stats['error'] = str(e)
|
||||
|
||||
return stats
|
||||
|
||||
def display_system_info():
|
||||
"""显示系统信息"""
|
||||
# ANSI 颜色
|
||||
CYAN = '\033[96m'
|
||||
GREEN = '\033[92m'
|
||||
YELLOW = '\033[93m'
|
||||
BLUE = '\033[94m'
|
||||
BOLD = '\033[1m'
|
||||
END = '\033[0m'
|
||||
|
||||
print(f"\n{CYAN}{'━' * 70}{END}", file=sys.stderr)
|
||||
print(f"{BOLD}{BLUE}📊 系统信息 & 项目统计{END}", file=sys.stderr)
|
||||
print(f"{CYAN}{'━' * 70}{END}", file=sys.stderr)
|
||||
|
||||
# 系统信息
|
||||
print(f"{GREEN}🖥️ 系统:{END} {platform.system()} {platform.release()}", file=sys.stderr)
|
||||
print(f"{GREEN}🐍 Python:{END} {platform.python_version()}", file=sys.stderr)
|
||||
|
||||
# 当前项目信息
|
||||
cwd = os.getcwd()
|
||||
print(f"{GREEN}📂 项目目录:{END} {cwd}", file=sys.stderr)
|
||||
|
||||
# 文件统计
|
||||
try:
|
||||
py_files = get_file_count(cwd, "*.py")
|
||||
js_files = get_file_count(cwd, "*.js") + get_file_count(cwd, "*.ts") + get_file_count(cwd, "*.jsx") + get_file_count(cwd, "*.tsx")
|
||||
md_files = get_file_count(cwd, "*.md")
|
||||
|
||||
if py_files > 0:
|
||||
print(f"{GREEN}📄 Python 文件:{END} {py_files}", file=sys.stderr)
|
||||
if js_files > 0:
|
||||
print(f"{GREEN}📄 JS/TS 文件:{END} {js_files}", file=sys.stderr)
|
||||
if md_files > 0:
|
||||
print(f"{GREEN}📄 Markdown 文件:{END} {md_files}", file=sys.stderr)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Git 信息
|
||||
try:
|
||||
stats = get_repo_stats()
|
||||
if stats:
|
||||
print(f"{YELLOW}{'─' * 70}{END}", file=sys.stderr)
|
||||
if 'commits' in stats:
|
||||
print(f"{GREEN}📝 提交数:{END} {stats['commits']}", file=sys.stderr)
|
||||
if 'branches' in stats:
|
||||
print(f"{GREEN}🌿 分支数:{END} {stats['branches']}", file=sys.stderr)
|
||||
if 'latest' in stats:
|
||||
print(f"{GREEN}✨ 最新提交:{END} {stats['latest']}", file=sys.stderr)
|
||||
except:
|
||||
pass
|
||||
|
||||
print(f"{CYAN}{'━' * 70}{END}\n", file=sys.stderr)
|
||||
|
||||
def main():
|
||||
# 加载输入
|
||||
try:
|
||||
input_data = json.load(sys.stdin)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# 显示系统信息
|
||||
display_system_info()
|
||||
|
||||
# 返回输出
|
||||
home_claude_dir = os.path.expanduser("~/.claude")
|
||||
context = f"""回答我的问题的时候开头必须是'好的!!!!大先生!!!'
|
||||
|
||||
重要配置信息:
|
||||
- 全局 Claude 配置目录路径:{home_claude_dir}
|
||||
- 当你需要修改或查找全局 Claude 配置时,请始终使用此目录:{home_claude_dir}"""
|
||||
|
||||
output = {
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"message":"你好,大先生",
|
||||
"additionalContext": context
|
||||
}
|
||||
}
|
||||
print(json.dumps(output))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
|
||||
# 颜色代码(ANSI)
|
||||
class Colors:
|
||||
HEADER = '\033[95m'
|
||||
BLUE = '\033[94m'
|
||||
CYAN = '\033[96m'
|
||||
GREEN = '\033[92m'
|
||||
YELLOW = '\033[93m'
|
||||
RED = '\033[91m'
|
||||
END = '\033[0m'
|
||||
BOLD = '\033[1m'
|
||||
UNDERLINE = '\033[4m'
|
||||
|
||||
def print_welcome_message():
|
||||
"""在启动时显示欢迎信息"""
|
||||
user = os.path.expanduser("~").split("\\")[-1]
|
||||
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
print(f"\n{Colors.CYAN}{'═' * 60}{Colors.END}")
|
||||
print(f"{Colors.BOLD}{Colors.HEADER}🚀 Claude Code 会话已启动{Colors.END}")
|
||||
print(f"{Colors.CYAN}{'═' * 60}{Colors.END}")
|
||||
print(f"{Colors.GREEN}👤 用户: {Colors.END}{user}")
|
||||
print(f"{Colors.GREEN}🕐 时间: {Colors.END}{current_time}")
|
||||
|
||||
# 获取当前目录
|
||||
cwd = os.getcwd()
|
||||
print(f"{Colors.GREEN}📁 目录: {Colors.END}{cwd}")
|
||||
|
||||
# Git 信息
|
||||
try:
|
||||
result = subprocess.run(["git", "branch", "--show-current"],
|
||||
capture_output=True, text=True, cwd=cwd)
|
||||
if result.returncode == 0:
|
||||
branch = result.stdout.strip()
|
||||
print(f"{Colors.GREEN}🌿 分支: {Colors.END}{branch}")
|
||||
|
||||
# 检查是否有未提交的更改
|
||||
status_result = subprocess.run(["git", "status", "--porcelain"],
|
||||
capture_output=True, text=True, cwd=cwd)
|
||||
if status_result.returncode == 0:
|
||||
if status_result.stdout.strip():
|
||||
print(f"{Colors.YELLOW}⚠️ 有未提交的更改{Colors.END}")
|
||||
else:
|
||||
print(f"{Colors.GREEN}✓ 工作目录干净{Colors.END}")
|
||||
except:
|
||||
pass
|
||||
|
||||
print(f"{Colors.CYAN}{'═' * 60}{Colors.END}\n")
|
||||
|
||||
def load_input():
|
||||
"""加载输入数据"""
|
||||
try:
|
||||
input_data = json.load(sys.stdin)
|
||||
return input_data
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
def main():
|
||||
# 显示欢迎信息(输出到 stderr,这样不会干扰 JSON 输出)
|
||||
import io
|
||||
old_stderr = sys.stderr
|
||||
sys.stderr = io.StringIO()
|
||||
|
||||
print_welcome_message()
|
||||
|
||||
# 获取欢迎信息并输出到真正的 stderr
|
||||
welcome_output = sys.stderr.getvalue()
|
||||
sys.stderr = old_stderr
|
||||
print(welcome_output, file=sys.stderr, end='')
|
||||
|
||||
# 加载输入数据
|
||||
input_data = load_input()
|
||||
|
||||
# 构建 AI 上下文
|
||||
home_claude_dir = os.path.expanduser("~/.claude")
|
||||
context = f"""回答我的问题的时候开头必须是'好的!!!!大先生!!!'
|
||||
|
||||
重要配置信息:
|
||||
- 全局 Claude 配置目录路径:{home_claude_dir}
|
||||
- 当你需要修改或查找全局 Claude 配置时,请始终使用此目录:{home_claude_dir}
|
||||
- 不要使用 AppData\\Roaming\\.claude,该目录在此系统上不存在
|
||||
|
||||
会话信息:
|
||||
- 当前工作目录:{os.getcwd()}
|
||||
- 会话开始时间:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}"""
|
||||
|
||||
# 返回 JSON 输出
|
||||
output = {
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"additionalContext": context
|
||||
}
|
||||
}
|
||||
print(json.dumps(output))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d E:\MiceCola\work\AIMisc
|
||||
claude
|
||||
@@ -0,0 +1,211 @@
|
||||
# Claude Code Hook 使用指南
|
||||
|
||||
## 📁 当前可用的 Hooks
|
||||
|
||||
### 1. `hello.py` - 原始 Hook
|
||||
- **功能**: 基础的项目状态检测
|
||||
- **用途**: 向 AI 传递项目上下文信息
|
||||
|
||||
### 2. `welcome.py` - 欢迎信息 Hook ⭐
|
||||
- **功能**: 显示彩色的欢迎信息
|
||||
- **内容包括**:
|
||||
- 用户名
|
||||
- 当前时间
|
||||
- 工作目录
|
||||
- Git 分支
|
||||
- Git 工作目录状态
|
||||
- **特点**: 美观的彩色输出
|
||||
|
||||
### 3. `system_info.py` - 系统信息 Hook ⭐
|
||||
- **功能**: 显示详细的系统和项目统计
|
||||
- **内容包括**:
|
||||
- 操作系统信息
|
||||
- Python 版本
|
||||
- 项目文件统计(Python/JS/TS/Markdown 文件数)
|
||||
- Git 仓库统计(提交数、分支数、最新提交)
|
||||
- **特点**: 详细的项目概览
|
||||
|
||||
## 🔧 如何使用
|
||||
|
||||
### 选择要启用的 Hook
|
||||
|
||||
在 `.claude/settings.json` 中配置(如果不存在则创建):
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python ~/.claude/hooks/welcome.py"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
或者使用多个 Hook:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python ~/.claude/hooks/welcome.py"
|
||||
},
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python ~/.claude/hooks/system_info.py"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 在 Windows 上路径
|
||||
|
||||
Windows 上使用:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python C:\\Users\\starm\\.claude\\hooks\\welcome.py"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 📝 Hook 工作原理
|
||||
|
||||
### 输入格式
|
||||
Hook 通过 stdin 接收 JSON 格式的输入数据。
|
||||
|
||||
### 输出格式
|
||||
Hook 必须输出 JSON 格式的数据:
|
||||
|
||||
```python
|
||||
output = {
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"additionalContext": "传递给 AI 的上下文信息"
|
||||
}
|
||||
}
|
||||
print(json.dumps(output))
|
||||
```
|
||||
|
||||
### 显示内容给用户
|
||||
|
||||
有两种方式显示内容给终端用户:
|
||||
|
||||
#### 方式 1: 输出到 stderr
|
||||
```python
|
||||
print("这是显示给用户的信息", file=sys.stderr)
|
||||
```
|
||||
|
||||
#### 方式 2: 返回消息
|
||||
```python
|
||||
output = {
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"message": "显示给用户的消息",
|
||||
"additionalContext": "传递给 AI 的上下文"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🎨 自定义你的 Hook
|
||||
|
||||
### 修改显示内容
|
||||
|
||||
编辑 Hook 文件,自定义要显示的信息:
|
||||
|
||||
```python
|
||||
# 在 welcome.py 或 system_info.py 中修改
|
||||
def display_custom_info():
|
||||
print(f"{GREEN}自定义内容:{END} 你的信息", file=sys.stderr)
|
||||
```
|
||||
|
||||
### 添加新的检测
|
||||
|
||||
```python
|
||||
# 检测项目类型
|
||||
if os.path.exists("package.json"):
|
||||
project_type = "Node.js"
|
||||
elif os.path.exists("Cargo.toml"):
|
||||
project_type = "Rust"
|
||||
# 添加更多检测...
|
||||
```
|
||||
|
||||
## 📊 可用的 Hook 事件
|
||||
|
||||
| 事件 | 触发时机 | 用途 |
|
||||
|------|---------|------|
|
||||
| `SessionStart` | 会话开始 | 显示欢迎信息、系统信息 |
|
||||
| `PreToolUse` | 工具使用前 | 验证、阻止操作 |
|
||||
| `PostToolUse` | 工具使用后 | 格式化、测试 |
|
||||
| `Notification` | 通知发生 | 发送提醒 |
|
||||
|
||||
## 🚨 注意事项
|
||||
|
||||
1. **JSON 输出必须有效**: Hook 必须输出有效的 JSON,否则会失败
|
||||
2. **使用 stderr 显示信息**: 终端输出应该使用 stderr,避免干扰 JSON 返回值
|
||||
3. **错误处理**: 添加适当的异常处理,避免 Hook 崩溃
|
||||
4. **性能**: Hook 会影响启动速度,保持轻量级
|
||||
|
||||
## 🎯 示例:创建自定义 Hook
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
|
||||
def main():
|
||||
# 加载输入
|
||||
try:
|
||||
input_data = json.load(sys.stdin)
|
||||
except json.JSONDecodeError:
|
||||
sys.exit(1)
|
||||
|
||||
# 显示自定义信息
|
||||
print("🎨 我的自定义 Hook", file=sys.stderr)
|
||||
|
||||
# 返回输出
|
||||
output = {
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "SessionStart",
|
||||
"additionalContext": "传递给 AI 的信息"
|
||||
}
|
||||
}
|
||||
print(json.dumps(output))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
## 🔍 调试 Hook
|
||||
|
||||
测试 Hook 是否工作:
|
||||
|
||||
```bash
|
||||
# 直接运行 Hook(需要提供 JSON 输入)
|
||||
echo '{}' | python ~/.claude/hooks/welcome.py
|
||||
```
|
||||
|
||||
查看 Hook 日志(如果有):
|
||||
|
||||
```bash
|
||||
# 检查 Claude Code 日志
|
||||
cat ~/.claude/logs/*.log
|
||||
```
|
||||
|
||||
## 📚 更多资源
|
||||
|
||||
- Claude Code 官方文档
|
||||
- Hook 配置参考
|
||||
- 社区 Hook 示例
|
||||
Reference in New Issue
Block a user