代码搜索与导航
在大型项目中快速定位代码、理解代码关系是开发者的核心需求。传统IDE需要记大量快捷键、用多个搜索面板、频繁切换文件窗口。而Claude Code通过自然语言就能完成所有代码搜索和导航任务,让你专注于理解代码逻辑本身,而不是记忆复杂的操作命令。
搜索代码片段
基础文本搜索
最简单的搜索方式就是用自然语言描述你想找的内容:
在整个项目中搜索"handleError"
Claude Code会自动使用ripgrep(rg)进行高效搜索:
🔍 Searching for "handleError" in project...
Found 23 occurrences in 8 files:
📄 src/controllers/UserController.js
Line 45: handleError(error, res)
Line 89: handleError(error, res)
Line 134: handleError(error, res)
📄 src/controllers/PostController.js
Line 23: handleError(error, res)
Line 67: handleError(error, res)
📄 src/middleware/errorHandler.js
Line 12: function handleError(error, req, res, next) {
Line 15-18: Definition of handleError function
📄 src/utils/api.js
Line 78: handleError(err)
... (4 more files)
Would you like me to:
1. Show the handleError function definition
2. Find all usages of handleError
3. Analyze the error handling pattern
智能上下文搜索
Claude Code理解代码语义,可以进行智能搜索:
找到所有处理用户登录失败的代码
Claude Code会分析代码逻辑而不只是文本:
🔍 Semantic search for "login failure handling"...
Found 3 relevant code sections:
1. src/controllers/AuthController.js (lines 45-67)
```javascript
if (!user) {
logger.warn('Login attempt with non-existent user', { email });
return res.status(401).json({
error: 'Invalid credentials',
code: 'AUTH_FAILED'
});
}
-
src/middleware/auth.js (lines 23-45)
// Token validation failure
if (!token) {
return res.status(401).json({
error: 'Authentication required',
code: 'NO_TOKEN'
});
} -
src/services/loginService.js (lines 89-112)
// Password mismatch handling
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
logger.warn('Invalid password attempt', { userId: user.id });
throw new AuthenticationError('Invalid credentials');
}
Pattern detected: 401 status codes + error logging + warning logs
### 对比传统方式
**传统IDE方式:**
1. 按 `Ctrl+Shift+F` 打开全局搜索
2. 输入搜索关键词
3. 在结果列表中逐个点击查看
4. 需要自己判断哪些结果相关
5. 手动跳转到每个文件
**Claude Code方式:**
找出所有可能导致内存泄漏的代码模式
Claude Code会:
- 理解"内存泄漏"的代码特征
- 搜索未清理的事件监听器、定时器、闭包等
- 提供详细分析和修复建议
- 标注风险等级
## 查找函数定义
### 快速定位定义
想知道某个函数在哪里定义:
找到sendEmail函数的定义
Claude Code会精确定位:
````text
📍 Function Definition: sendEmail
📄 src/services/emailService.js (lines 45-89)
```javascript
/**
* 发送邮件
* @param {Object} options - 邮件选项
* @param {string} options.to - 收件人邮箱
* @param {string} options.subject - 邮件主题
* @param {string} options.html - HTML内容
* @param {string} options.text - 纯文本内容(可选)
* @returns {Promise[Object]} 发送结果
*/
async sendEmail({ to, subject, html, text }) {
try {
// 验证邮箱格式
if (!this.isValidEmail(to)) {
throw new Error('Invalid email address');
}
// 构建邮件选项
const mailOptions = {
from: process.env.EMAIL_FROM,
to,
subject,
html,
text: text || this.htmlToText(html)
};
// 发送邮件
const info = await this.transporter.sendMail(mailOptions);
// 记录日志
logger.info('Email sent successfully', {
messageId: info.messageId,
to,
subject
});
return info;
} catch (error) {
logger.error('Failed to send email', {
error: error.message,
to,
subject
});
throw new EmailServiceError('Failed to send email', error);
}
}
Metadata:
- File: src/services/emailService.js
- Class: EmailService
- Exported as: module.exports (singleton)
- Dependencies: nodemailer, logger
- Error handling: Yes (try-catch + custom error)
- Lines of code: 45
### 智能跳转
Claude Code可以理解不同的引用方式:
```
跳转到AuthService的login方法
```
即使引用方式不同,也能准确定位:
```
🔍 Found multiple references to "AuthService.login":
1. Direct import:
src/routes/authRoutes.js
Line 12: const { login } = require('./services/AuthService');
2. Destructured from class:
src/controllers/AuthController.js
Line 5: const { login } = AuthService;
3. Method call:
src/tests/auth.test.js
Line 45: await AuthService.login(email, password);
📍 Definition location:
📄 src/services/AuthService.js (lines 23-67)
```javascript
static async login(email, password) {
// ... implementation
}
```
Would you like me to:
1. Show the full implementation
2. Find all usages of this method
3. Analyze the method's complexity
```
### 链式定义查找
当调用链很长时,Claude Code可以追踪完整链路:
```
追踪userProfile从API到数据库的完整调用链
```
Claude Code会构建完整的调用图:
```
🔗 Call Chain Analysis: userProfile
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📍 Entry Point: API Route
📄 src/routes/userRoutes.js (line 23)
router.get('/profile', UserController.getProfile)
↓
📍 Controller Layer
📄 src/controllers/UserController.js (lines 45-78)
async getProfile(req, res) {
const userId = req.user.id;
const profile = await UserService.getProfile(userId);
// ... response handling
}
↓
📍 Service Layer
📄 src/services/UserService.js (lines 123-156)
async getProfile(userId) {
const user = await User.findById(userId);
if (!user) {
throw new NotFoundError('User not found');
}
return this.sanitizeProfile(user);
}
↓
📍 Model Layer
📄 src/models/User.js (lines 67-89)
static async findById(id) {
const query = 'SELECT * FROM users WHERE id = $1';
const result = await db.query(query, [id]);
return result.rows[0];
}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Statistics:
- Total layers: 4 (Route → Controller → Service → Model)
- Total files: 4
- Total functions: 4
- Database queries: 1
- Error handling points: 2
⚠️ Observations:
- Good separation of concerns
- Proper error handling in Service layer
- Missing input validation in Controller
- No caching mechanism (consider adding Redis cache)
💡 Suggestions:
1. Add request validation middleware
2. Implement profile caching (TTL: 5min)
3. Add database query logging
```
## 跳转到引用
### 查找所有使用位置
了解函数或变量在哪里被使用:
```
找出所有调用sendWelcomeEmail的地方
```
Claude Code会提供完整的引用分析:
```
📊 Usage Analysis: sendWelcomeEmail function
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Total References: 7 calls across 5 files
📄 src/controllers/UserController.js (3 calls)
Line 67: After user registration
await sendWelcomeEmail(user.email, user.name);
Context: New user signup flow
Line 145: After email verification
await sendWelcomeEmail(user.email, user.name, { verified: true });
Context: Email verification completion
Line 203: After email change
await sendWelcomeEmail(newUser.email, newUser.name, { emailChanged: true });
Context: Email address update
📄 src/controllers/AdminController.js (2 calls)
Line 89: Manual invitation
await sendWelcomeEmail(email, name, { invitedBy: admin.name });
Context: Admin invites user
Line 234: Bulk import
for (const user of importedUsers) {
await sendWelcomeEmail(user.email, user.name);
}
Context: Batch user import (⚠️ potential performance issue)
📄 src/services/onboardingService.js (1 call)
Line 45: During onboarding
await sendWelcomeEmail(user.email, user.name, { onboardingData });
Context: Post-registration onboarding flow
📄 src/tests/email.test.js (1 call)
Line 123: Test case
await sendWelcomeEmail('test@example.com', 'Test User');
Context: Unit test
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 Pattern Analysis:
✓ Good: Consistent async/await usage
✓ Good: Error handling in all calling functions
⚠️ Issue: Bulk import may trigger rate limiting
⚠️ Issue: No retry mechanism for failed sends
💡 Recommendations:
1. Implement queue system for bulk operations
2. Add exponential backoff for retries
3. Monitor email delivery rates
4. Add unit tests for edge cases
```
### 依赖关系分析
理解模块之间的依赖关系:
```
分析OrderController的依赖关系
```
Claude Code会构建依赖图:
```
📊 Dependency Analysis: OrderController
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📥 Incoming Dependencies (Who depends on this?)
• src/routes/orderRoutes.js
→ Direct import: require('./controllers/OrderController')
• src/tests/order.test.js
→ Test import: require('../controllers/OrderController')
📤 Outgoing Dependencies (What does this depend on?)
Level 1 (Direct):
• src/services/OrderService.js
→ Used for: Order business logic
→ Functions: create, update, delete, getList
• src/services/PaymentService.js
→ Used for: Payment processing
→ Functions: processPayment, refund
• src/services/NotificationService.js
→ Used for: User notifications
→ Functions: sendOrderConfirmation
• src/middleware/validators.js
→ Used for: Input validation
→ Functions: validateOrderInput
• src/utils/logger.js
→ Used for: Logging
→ Functions: info, error, warn
• src/models/Order.js
→ Used for: Data model
→ Properties: schema definitions
Level 2 (Indirect):
• src/models/User.js (via OrderService)
• src/models/Product.js (via OrderService)
• src/services/EmailService.js (via NotificationService)
• src/database/db.js (via all models)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📈 Complexity Metrics:
• Direct dependencies: 6
• Total dependency depth: 3 levels
• Circular dependencies: 0 ✓
• Coupling score: Medium (acceptable)
⚠️ Potential Issues:
1. High coupling with services (6 services)
2. PaymentService and NotificationService could be abstracted
3. Consider using dependency injection
💡 Refactoring Suggestions:
1. Introduce service layer façade
2. Use dependency injection pattern
3. Consider event-driven architecture for notifications
```
## 全局搜索
### 跨文件类型搜索
Claude Code可以同时搜索多种文件类型:
```
在所有文件中搜索"API_KEY"
```
```
🔍 Global search for "API_KEY"...
Found in 12 files across multiple file types:
📄 Configuration Files (4 files)
.env.example
Line 3: API_KEY=your_api_key_here
Line 15: EXTERNAL_API_KEY=another_key
config/defaults.json
Line 8: "apiKey": "default_key"
webpack.config.js
Line 45: process.env.API_KEY
.env.development
Line 2: API_KEY=dev_12345
📄 Source Code (5 files)
src/services/api.js
Line 12: const API_KEY = process.env.API_KEY;
Line 67: headers: { 'X-API-Key': API_KEY }
src/utils/config.js
Line 23: apiKey: config.API_KEY || 'fallback'
src/controllers/externalApi.js
Line 34: const key = process.env.EXTERNAL_API_KEY;
📄 Documentation (3 files)
README.md
Line 78: Set `API_KEY` in your .env file
Line 134: Get your API key from: https://api.example.com
docs/deployment.md
Line 56: Export API_KEY before starting the server
docs/api-reference.md
Line 23: All requests require API_KEY in header
⚠️ Security Alert:
Found API keys that may be exposed:
• .env.development contains a hardcoded key (dev_12345)
• config/defaults.json contains default key
💡 Recommendations:
1. Add .env.development to .gitignore
2. Remove hardcoded keys from config files
3. Use environment-specific keys
4. Add API key validation
```
### 按目录范围搜索
限制搜索范围以提高精度:
```
在src/controllers目录中搜索所有使用try-catch的代码
```
```
🔍 Searching in src/controllers/ for "try-catch" patterns...
Found 34 try-catch blocks in 8 controller files:
📄 src/controllers/UserController.js (8 blocks)
Line 23-34: createUser method
Pattern: Standard error catching
Caught: Database errors
Response: 500 status with error message
Line 45-56: updateUser method
Pattern: Standard error catching
Caught: Validation errors
Response: 400 status with validation details
... (6 more)
📄 src/controllers/OrderController.js (6 blocks)
Line 12-28: createOrder method
Pattern: Standard error catching
Caught: Payment errors, validation errors
Response: Different status codes based on error type
... (4 more)
━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━
📊 Analysis Results:
Total try-catch blocks: 34
Average per file: 4.25 blocks
Error handling consistency: 75%
⚠️ Issues Found:
1. Inconsistent error response format (3 different patterns)
2. Missing error logging in 8 blocks
3. Generic error messages in 12 blocks
4. No error classification (user errors vs system errors)
💡 Refactoring Plan:
1. Create centralized error handler (save ~100 lines)
2. Implement error class hierarchy
3. Add error logging middleware
4. Standardize error response format
Would you like me to implement these improvements?
```
### 组合条件搜索
使用多个条件进行精确搜索:
```
找出所有:
1. 导入了useState但未使用的文件
2. 定义了async函数但没有await的文件
3. 有TODO注释超过30天的文件
```
Claude Code 会执行复合分析:
```
🔍 Multi-condition analysis...
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Condition 1: useState imported but not used
Found 3 files:
src/components/UserProfile.jsx
Line 3: import { useState, useEffect } from 'react'
Analysis: useState imported but only useEffect is used
Action: Remove useState from import
src/components/Dashboard.jsx
Line 4: import { useState, useMemo } from 'react'
Analysis: useState imported but only useMemo is used
Action: Remove useState from import
src/hooks/useAuth.js
Line 2: import { useState, useEffect } from 'react'
Analysis: useState imported but was used in commented code
Action: Remove or uncomment usage
Condition 2: async functions without await
Found 2 files:
src/controllers/AuthController.js
Line 89: async loginWithoutAwait(req, res)
Analysis: Function marked async but has no await
Impact: Unnecessary promise wrapping
Fix: Remove async keyword
src/services/dataFetcher.js
Line 234: async fetchAllData()
Analysis: All promises are handled with .then() instead of await
Impact: Mixed async patterns
Fix: Convert to async/await or remove async
Condition 3: TODO comments older than 30 days
Found 7 TODOs:
src/services/paymentService.js (Line 45)
Created: 2024-10-15 (62 days ago)
Comment: // TODO: Implement PayPal integration
Priority: High (blocking feature)
src/utils/cache.js (Line 67)
Created: 2024-09-20 (87 days ago)
Comment: // TODO: Add Redis caching
Priority: Medium (performance improvement)
... (5 more)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 Summary:
• Unused imports: 3 files (quick fixes)
• Async issues: 2 files (low priority)
• Old TODOs: 7 items (3 high priority)
🚀 Suggested Actions:
1. Fix unused imports (2 minutes)
2. Remove unnecessary async keywords (1 minute)
3. Create GitHub issues for old TODOs (5 minutes)
4. Implement high-priority TODOs (2-3 hours)
Would you like me to execute fixes for 1 and 2?
```
## 正则表达式搜索
### 基础正则搜索
对于复杂的模式匹配,Claude Code可以使用正则表达式:
```
用正则表达式找出所有的邮箱地址
```
Claude Code会自动构建合适的正则表达式:
```
🔍 Regex Search: Email addresses
Pattern used: [\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}
Found 47 email addresses in 12 files:
📄 src/config/email.js (3 emails)
Line 12: noreply@example.com
Line 15: support@example.com
Line 18: admin@example.com
📄 tests/fixtures/users.json (15 emails)
Line 23: user1@example.com
Line 24: user2@example.com
... (13 more)
📄 docs/deployment.md (5 emails)
Line 78: Contact admin@example.com for access
Line 89: Send reports to reports@example.com
... (3 more)
⚠️ Security Check:
No real email addresses found (all are example.com domain)
💡 Suggestions:
1. Consolidate email configuration in one place
2. Use environment variables for production emails
3. Add email validation regex unit tests
```
### 复杂模式匹配
搜索更复杂的代码模式:
```
找出所有没有错误处理的数据库查询
```
Claude Code会构建复杂的正则模式:
```
🔍 Pattern Search: Database queries without error handling
Pattern analyzed:
• db.query calls without try-catch
• Model methods without error handling
• Direct SQL queries without .catch()
Found 15 queries without proper error handling:
📄 src/services/userService.js (5 queries)
Line 45: db.query('SELECT * FROM users WHERE id = ?', [id])
❌ No error handling
Impact: Database errors will crash the server
Fix: Wrap in try-catch or add .catch()
Line 67: await User.findByEmail(email)
❌ No error handling
Impact: Unhandled promise rejection
Fix: Add try-catch block
... (3 more)
📄 src/repositories/orderRepository.js (8 queries)
Line 23: connection.query(sql, params)
❌ No error handling
❌ No connection release on error
Impact: Connection leak + server crash
Fix: Wrap with error handling + cleanup
... (7 more)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚨 Critical Issues:
• 15 queries can crash the server
• 8 queries may cause connection leaks
• 0% error handling coverage
💡 Refactoring Plan:
1. Create database wrapper with automatic error handling
2. Implement connection pool management
3. Add centralized error logging
4. Create helper functions for common queries
Example fix:
Before:
const result = await db.query('SELECT * FROM users');
return result.rows;
After:
try {
const result = await db.query('SELECT * FROM users');
return result.rows;
} catch (error) {
logger.error('Database query failed', { error });
throw new DatabaseError('Failed to fetch users');
}
Would you like me to implement these fixes?
```
### 代码气味检测
使用正则表达式检测常见的代码问题:
```
检测代码中的反模式:
1. console.log在生产代码中
2. 硬编码的密钥和密码
3. var关键字的使用
4. 嵌套超过4层的代码
```
```
🔍 Code Smell Detection
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Smell 1: console.log in production code
Found 23 occurrences:
📄 src/controllers/UserController.js (8 logs)
Line 34: console.log('User created:', user)
Severity: Medium
Impact: Performance issue, information leakage
Fix: Replace with logger.info()
Line 67: console.log(error)
Severity: High
Impact: Error details leaked to console
Fix: Replace with logger.error()
... (6 more)
📄 src/services/api.js (15 logs)
Line 123: console.log('API request:', data)
Severity: High
Impact: May leak sensitive data
Fix: Remove or use sanitized logging
Smell 2: Hardcoded secrets
Found 3 occurrences:
📄 src/config/db.js
Line 12: password: 'admin123'
Severity: CRITICAL
Impact: Security vulnerability
Action: Move to environment variable immediately
Line 15: apiKey: 'sk_live_abc123xyz'
Severity: CRITICAL
Impact: Exposed payment API key
Action: Rotate key and use environment variable
📄 src/services/external.js
Line 45: const secret = 'my_secret_key'
Severity: High
Impact: Hardcoded encryption key
Action: Generate unique key per environment
Smell 3: var keyword usage
Found 7 occurrences:
📄 src/utils/helpers.js (4 vars)
Line 23: var count = 0
Severity: Low
Impact: Outdated syntax
Fix: Replace with const or let
... (3 more)
Smell 4: Deep nesting (4+ levels)
Found 5 occurrences:
📄 src/controllers/OrderController.js
Line 89-123: 5 levels of nesting
Severity: Medium
Impact: Reduced readability
Fix: Extract nested logic into separate functions
📄 src/services/paymentService.js
Line 156-198: 6 levels of nesting
Severity: High
Impact: Cognitive complexity too high
Fix: Break down into smaller functions
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Summary:
• Total issues: 38
• Critical: 3 (security)
• High: 18 (performance + security)
• Medium: 12 (readability)
• Low: 5 (style)
🎯 Priority Actions:
1. Rotate exposed API keys (DO IMMEDIATELY)
2. Move secrets to environment variables
3. Replace console.log with logger
4. Refactor deeply nested code
⏱️ Estimated time:
• Critical fixes: 30 minutes
• High priority fixes: 2 hours
• Medium + Low: 3 hours
Would you like me to start with the critical security fixes?
```
## 符号导航
### 类和接口导航
快速浏览类的结构和继承关系:
```
显示UserModel类的完整结构
```
```text
🏗️ Class Structure: UserModel
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📄 Location: src/models/User.js (lines 12-234)
📋 Class Hierarchy:
BaseModel
└── UserModel (extends BaseModel)
📦 Properties:
• id: string (UUID, primary key)
• email: string (unique, indexed)
• password: string (hashed)
• name: string
• role: enum ['user', 'admin', 'moderator']
• isActive: boolean (default: true)
• createdAt: Date
• updatedAt: Date
• lastLoginAt: Date (nullable)
🔧 Static Methods:
• findById(id): Promise[User]
Location: Line 45-56
Returns: User instance or null
Throws: NotFoundError
• findByEmail(email): Promise[User]
Location: Line 67-78
Returns: User instance or null
Indexes: email field
• create(data): Promise[User]
Location: Line 89-112
Validates: Email format, password strength
Hashes: Password before saving
• findAll(filters): Promise[User[]]
Location: Line 123-145
Supports: Pagination, filtering, sorting
🎯 Instance Methods:
• validate(): boolean
Location: Line 156-178
Checks: Email, password, required fields
• hashPassword(): Promise[void]
Location: Line 189-201
Algorithm: bcrypt (10 rounds)
• toJSON(): Object
Location: Line 212-234
Excludes: Password field
Includes: Safe user data only
🔗 Relationships:
• hasMany: Order (orders placed by user)
• hasMany: Review (reviews written by user)
• belongsToMany: Role (many-to-many via UserRoles)
📊 Statistics:
• Total lines: 223
• Methods: 8 (4 static, 4 instance)
• Properties: 8
• Relationships: 3
• Complexity: Medium
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 Observations:
✓ Good: Follows MVC pattern
✓ Good: Password hashing implemented
✓ Good: Proper data hiding (toJSON excludes password)