-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclaude_code_ccdebug.py
More file actions
365 lines (293 loc) · 11.6 KB
/
claude_code_ccdebug.py
File metadata and controls
365 lines (293 loc) · 11.6 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/bin/env python3
"""
Claude Code /ccdebug Command Implementation
實現 /ccdebug slash command 的核心功能
"""
import os
import sys
import json
import re
import subprocess
import tempfile
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from datetime import datetime, timedelta
import pyperclip
class CCDebugCommand:
"""Implementation of /ccdebug slash command for Claude Code"""
def __init__(self):
self.config = self.load_config()
self.last_error = None
self.error_history = []
def load_config(self) -> Dict:
"""Load user configuration"""
config_paths = [
Path.cwd() / '.ccdebugrc',
Path.home() / '.ccdebugrc',
]
default_config = {
"defaultLanguage": "zh",
"defaultMode": "deep",
"autoSuggest": True,
"copyToClipboard": True,
"contextLines": 10,
"excludePatterns": ["node_modules", ".git", "__pycache__"],
}
for config_path in config_paths:
if config_path.exists():
try:
with open(config_path) as f:
user_config = json.load(f)
default_config.update(user_config)
break
except:
pass
return default_config
def parse_command(self, command: str) -> Tuple[Dict, str]:
"""Parse /ccdebug command and options"""
# Remove /ccdebug prefix
if command.startswith('/ccdebug'):
command = command[8:].strip()
elif command.startswith('/ccdb'):
command = command[5:].strip()
options = {
'lang': self.config['defaultLanguage'],
'mode': self.config['defaultMode'],
'copy': self.config['copyToClipboard'],
'context_lines': self.config['contextLines'],
}
error_content = ""
parts = command.split()
i = 0
while i < len(parts):
part = parts[i]
# Language options
if part in ['--zh', '--cn']:
options['lang'] = 'zh'
elif part == '--en':
options['lang'] = 'en'
elif part == '--auto-lang':
options['auto_lang'] = True
# Analysis modes
elif part == '--quick':
options['mode'] = 'quick'
elif part == '--deep':
options['mode'] = 'deep'
elif part == '--full':
options['mode'] = 'full'
# Input sources
elif part == '--last':
options['use_last'] = True
elif part == '--clipboard':
options['use_clipboard'] = True
elif part == '--file' and i + 1 < len(parts):
options['file'] = parts[i + 1]
i += 1
# Output options
elif part == '--copy':
options['copy'] = True
elif part == '--save' and i + 1 < len(parts):
options['save'] = parts[i + 1]
i += 1
# Context options
elif part == '--context' and i + 1 < len(parts):
options['context_file'] = parts[i + 1]
i += 1
elif part == '--line' and i + 1 < len(parts):
options['line_number'] = int(parts[i + 1])
i += 1
# Special modes
elif part == '--watch' and i + 1 < len(parts):
options['watch'] = parts[i + 1]
i += 1
elif part == '--batch':
options['batch'] = True
elif part == '--test-mode':
options['test_mode'] = True
# Help
elif part in ['--help', '-h']:
options['help'] = True
# Error content (anything not starting with --)
elif not part.startswith('--'):
error_content = ' '.join(parts[i:])
break
i += 1
return options, error_content
def execute(self, command: str) -> str:
"""Execute /ccdebug command"""
options, error_content = self.parse_command(command)
# Handle help
if options.get('help'):
return self.show_help()
# Get error content from various sources
if options.get('use_last') and self.last_error:
error_content = self.last_error
elif options.get('use_clipboard'):
error_content = pyperclip.paste()
elif options.get('file'):
try:
error_content = Path(options['file']).read_text()
except:
return f"❌ 無法讀取文件: {options['file']}"
if not error_content:
return "❌ 未提供錯誤內容。請使用 /ccdebug --help 查看使用方法。"
# Auto-detect language if needed
if options.get('auto_lang'):
options['lang'] = self.detect_language(error_content)
# Run analysis based on mode
if options['mode'] == 'quick':
result = self.quick_analysis(error_content, options)
elif options['mode'] == 'deep':
result = self.deep_analysis(error_content, options)
elif options['mode'] == 'full':
result = self.full_analysis(error_content, options)
else:
result = self.deep_analysis(error_content, options)
# Handle output
if options.get('copy'):
pyperclip.copy(result)
result += "\n\n✅ 已複製到剪貼板"
if options.get('save'):
Path(options['save']).write_text(result)
result += f"\n✅ 已保存到: {options['save']}"
# Store in history
self.error_history.append({
'time': datetime.now(),
'error': error_content[:100] + '...',
'options': options
})
return result
def quick_analysis(self, error_content: str, options: Dict) -> str:
"""Quick analysis using basic ccdebug"""
cmd = ['python3', '-m', 'claudecode_debugger.cli_new']
cmd.extend([error_content])
cmd.extend(['--lang', options['lang']])
return self.run_ccdebug(cmd)
def deep_analysis(self, error_content: str, options: Dict) -> str:
"""Deep analysis with suggestions"""
cmd = ['python3', '-m', 'claudecode_debugger.cli_new']
cmd.extend([error_content])
cmd.extend(['--lang', options['lang']])
cmd.extend(['--suggest', '--analyze-stack'])
if options.get('verbose'):
cmd.append('--verbose')
return self.run_ccdebug(cmd)
def full_analysis(self, error_content: str, options: Dict) -> str:
"""Full analysis with context"""
cmd = ['python3', '-m', 'claudecode_debugger.cli_new']
cmd.extend([error_content])
cmd.extend(['--lang', options['lang']])
cmd.extend(['--suggest', '--analyze-stack', '--verbose'])
if options.get('context_file'):
cmd.extend(['--context', options['context_file']])
return self.run_ccdebug(cmd)
def run_ccdebug(self, cmd: List[str]) -> str:
"""Run ccdebug command and return output"""
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
return result.stdout
else:
return f"❌ 分析失敗:\n{result.stderr}"
except subprocess.TimeoutExpired:
return "❌ 分析超時(30秒)"
except Exception as e:
return f"❌ 執行錯誤: {str(e)}"
def detect_language(self, error_content: str) -> str:
"""Auto-detect language from error content"""
chinese_patterns = ['錯誤', '異常', '失敗', '找不到', '無法']
for pattern in chinese_patterns:
if pattern in error_content:
return 'zh'
return 'en'
def show_help(self) -> str:
"""Show help message"""
return """
🛠️ **CCDebug Command Help**
**基本用法:**
- `/ccdebug` - 分析上一個錯誤
- `/ccdebug "error message"` - 分析特定錯誤
- `/ccdb` - 簡短別名
**語言選項:**
- `--zh` / `--cn` - 使用中文
- `--en` - 使用英文
- `--auto-lang` - 自動檢測語言
**分析模式:**
- `--quick` - 快速分析
- `--deep` - 深度分析(預設)
- `--full` - 完整分析含代碼上下文
**輸入來源:**
- `--last` - 使用上一個錯誤
- `--clipboard` - 從剪貼板讀取
- `--file <path>` - 從文件讀取
**輸出選項:**
- `--copy` - 複製到剪貼板
- `--save <path>` - 保存到文件
**範例:**
```
/ccdebug --last --zh
/ccdebug "TypeError: undefined" --deep
/ccdb --file error.log --save report.md
```
💡 提示: 在 ~/.ccdebugrc 設定預設選項
"""
def watch_errors(self, error_content: str, last_error: Optional[str] = None) -> Optional[str]:
"""Monitor for errors and suggest /ccdebug"""
error_patterns = [
r'Error:|Exception:|Failed:|錯誤:|異常:|失敗:',
r'Traceback \(most recent call last\):',
r'TypeError:|AttributeError:|ValueError:',
r'at .+ \(.+:\d+:\d+\)',
]
for pattern in error_patterns:
if re.search(pattern, error_content, re.IGNORECASE):
self.last_error = error_content
return self.suggest_command(error_content)
return None
def suggest_command(self, error_content: str) -> str:
"""Suggest appropriate /ccdebug command"""
# Detect error type
is_test = 'test' in error_content.lower() or 'spec' in error_content.lower()
is_build = 'build' in error_content.lower() or 'compile' in error_content.lower()
has_stack = 'Traceback' in error_content or ' at ' in error_content
suggestions = []
# Basic suggestion
lang = '--zh' if self.detect_language(error_content) == 'zh' else '--en'
suggestions.append(f"/ccdebug --last {lang}")
# Specific suggestions
if has_stack:
suggestions.append(f"/ccdebug --last {lang} --deep")
if is_test:
suggestions.append(f"/ccdebug --last {lang} --test-mode")
if is_build:
suggestions.append(f"/ccdebug --last {lang} --full")
return f"""
🔍 偵測到錯誤,建議使用:
{chr(10).join(f'• `{s}`' for s in suggestions)}
或使用 `/ccdebug --help` 查看更多選項
"""
# Command line interface
def main():
"""CLI interface for testing"""
if len(sys.argv) < 2:
print("Usage: python claude_code_ccdebug.py '<command>'")
print("Example: python claude_code_ccdebug.py '/ccdebug --last --zh'")
return
command = ' '.join(sys.argv[1:])
ccdebug = CCDebugCommand()
# Test with sample error
ccdebug.last_error = """
Traceback (most recent call last):
File "app.py", line 42, in process
result = data.process()
AttributeError: 'NoneType' object has no attribute 'process'
"""
result = ccdebug.execute(command)
print(result)
if __name__ == "__main__":
main()