Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
150 changes: 150 additions & 0 deletions docs/GitActions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# GitActions Service

The `GitActions` service provides comprehensive Git operations for the CodeBuddy extension, enabling advanced features like commit message generation and pull request reviews.

## Features

### Core Git Operations
- **Staged Differences**: Get staged changes for commit message generation
- **PR Differences**: Compare current branch against base branch for PR reviews
- **Branch Management**: Get current branch info, available branches, and base branch detection
- **Repository Status**: Check repository cleanliness and status

### Advanced Operations
- **Commit History**: Get commit history between branches
- **File Operations**: Get file content at specific commits
- **Diff Statistics**: Get detailed diff statistics
- **Remote Operations**: Get remote URLs and information

## Usage

### Basic Usage
```typescript
import { GitActions } from '../services/git-actions';

const gitActions = new GitActions();

// Get staged changes for commit message
const stagedDiff = await gitActions.getStagedDifferenceSummary();

// Get PR differences for review
const prDiff = await gitActions.getPRDifferenceSummary();

// Get current branch information
const branchInfo = await gitActions.getCurrentBranchInfo();
```

### Branch Operations
```typescript
// Get all available branches
const branches = await gitActions.getAvailableBranches();

// Get the base branch (automatically detected)
const baseBranch = await gitActions.getBaseBranch();

// Check if a branch exists
const exists = await gitActions.branchExists('main');
```

### Repository Status
```typescript
// Check if repository is clean
const isClean = await gitActions.isRepositoryClean();

// Get detailed repository status
const status = await gitActions.getRepositoryStatus();
```

### Advanced Operations
```typescript
// Get commit history between branches
const commits = await gitActions.getCommitHistory('main', 'feature-branch');

// Get modified files between branches
const modifiedFiles = await gitActions.getModifiedFiles('main');

// Get diff statistics
const diffStats = await gitActions.getDiffStats('main');

// Get file content at specific commit
const content = await gitActions.getFileAtCommit('src/file.ts', 'abc123');
```

## Integration with Commands

### GenerateCommitMessage
The `GenerateCommitMessage` command uses `GitActions` to get staged differences:

```typescript
const gitActions = new GitActions();
const stagedDiff = await gitActions.getStagedDifferenceSummary();
```

### ReviewPR
The `ReviewPR` command uses `GitActions` for comprehensive PR analysis:

```typescript
const gitActions = new GitActions();

// Get target branch from user input
const targetBranch = await selectTargetBranch();

// Get PR differences
const prDiff = await gitActions.getPRDifferenceSummary(targetBranch);

// Get additional context
const diffStats = await gitActions.getDiffStats(targetBranch);
const commitHistory = await gitActions.getCommitHistory(targetBranch);
```

## Error Handling

All GitActions methods include proper error handling and logging:

```typescript
try {
const result = await gitActions.someOperation();
return result;
} catch (error) {
console.error("Git operation failed:", error);
throw error;
}
```

## Base Branch Detection

The service automatically detects the base branch using this priority:

1. **Default Branches**: Checks for `main`, `master`, `develop`, `dev`
2. **Merge Base**: Uses `git merge-base` to find common ancestor
3. **Upstream Branch**: Falls back to upstream tracking branch
4. **Final Fallback**: Defaults to `main`

## Configuration

The GitActions service is configured with these default options:

```typescript
const options: Partial<SimpleGitOptions> = {
binary: "git",
maxConcurrentProcesses: 6,
trimmed: false,
baseDir: workspaceRoot,
};
```

## Dependencies

- **simple-git**: Core Git operations
- **vscode**: VS Code API for workspace access

## Future Enhancements

Potential future additions to the GitActions service:

- **Conflict Resolution**: Helper methods for merge conflicts
- **Stash Operations**: Stash management utilities
- **Tag Operations**: Tag creation and management
- **Patch Operations**: Patch generation and application
- **Hooks Integration**: Git hooks management
- **Performance Optimization**: Caching and batched operations
2 changes: 2 additions & 0 deletions src/application/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export enum CODEBUDDY_ACTIONS {
generateUnitTest = "CodeBuddy.generateUnitTest",
generateDiagram = "CodeBuddy.generateMermaidDiagram",
inlineChat = "CodeBuddy.inLineChat",
restart = "CodeBuddy.restart",
reviewPR = "CodeBuddy.reviewPR",
}
export enum COMMON {
GROQ_CHAT_HISTORY = "groqChatHistory",
Expand Down
151 changes: 143 additions & 8 deletions src/commands/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,149 @@ export class Comments extends CodeCommandHandler {
}

generatePrompt() {
const PROMPT = `
A good code review comment describes the intent behind the code without
repeating information that's obvious from the code itself. Good comments
describe "why", explain any "magic" values and non-obvious behaviour.
Respond based on the programming language of the requested code. Unless stated otherwise.
Note: Only add function level comments. Do not write comment in between the code.
Be creative in crafting your comment, but be careful not unnecessary comments.
`;
const PROMPT = `You are CodeBuddy, a documentation expert. Create clear, valuable comments that enhance code understanding without stating the obvious.

## Documentation Philosophy

### 📝 **Comment Strategy**
Focus on **WHY** over **WHAT** - explain intent, not implementation details.

### 🎯 **Comment Types**

#### 🏗️ **Function/Method Documentation**
\`\`\`typescript
/**
* Calculates compound interest using the formula A = P(1 + r/n)^(nt)
* Handles edge cases for zero principal and negative rates
*
* @param principal - Initial investment amount (must be positive)
* @param rate - Annual interest rate as decimal (e.g., 0.05 for 5%)
* @param compound - Compounding frequency per year
* @param years - Investment duration in years
* @returns Final amount after compound interest
* @throws {ValidationError} When principal <= 0 or rate < 0
*
* @example
* calculateCompoundInterest(1000, 0.05, 12, 5) // Returns: 1283.36
*/
function calculateCompoundInterest(principal, rate, compound, years) {
// Validation logic here...
}
\`\`\`

#### 🧠 **Complex Logic Explanation**
\`\`\`typescript
// Use binary search to find insertion point for maintaining sorted order
// This approach provides O(log n) complexity vs O(n) for linear search
let left = 0, right = array.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (array[mid] < value) {
left = mid + 1; // Search right half
} else {
right = mid; // Search left half including mid
}
}
\`\`\`

#### ⚠️ **Warning Comments**
\`\`\`typescript
// IMPORTANT: This function modifies the original array for performance
// If immutability is required, use [...array].sort() instead
function quickSort(array) { /* sorting logic */ }

// TODO: Replace with async/await pattern in next refactor
// Current callback approach causes nested callback complexity
function processData(data, callback) { /* processing logic */ }

// HACK: Workaround for Safari bug with Date parsing
// Remove once Safari 16+ support is no longer needed
if (isSafari && version < 16) {
date = new Date(dateString.replace(/-/g, '/'));
}
\`\`\`

#### 🔗 **API Documentation**
\`\`\`typescript
/**
* User authentication service
* Integrates with OAuth providers and manages session state
*
* Rate limiting: 5 requests per minute per IP
* Session duration: 24 hours with auto-refresh
*/
class AuthService {
/**
* Authenticate user credentials against configured providers
*
* @param credentials - User login information
* @param options - Authentication options
* @param options.provider - OAuth provider ('google' | 'github' | 'local')
* @param options.rememberMe - Extend session to 30 days
* @returns Promise resolving to user session or rejection
*/
async authenticate(credentials, options = {}) {
// Implementation...
}
}
\`\`\`

### ❌ **Avoid These Comment Anti-Patterns**
\`\`\`typescript
// BAD: States the obvious
let count = 0; // Initialize count to zero

// BAD: Outdated comment
// This function returns a string (actually returns Promise<string>)
async function getData() { return await fetch('/api/data'); }

// BAD: Redundant with code
// Loop through all users
for (const user of users) {
// Process each user
processUser(user);
}
\`\`\`

### ✅ **Good Comment Examples**
\`\`\`typescript
// GOOD: Explains business logic
// Apply 15% discount for premium members, 5% for regular members
// Discount caps at $100 to prevent abuse on high-value orders
const discount = user.isPremium
? Math.min(order.total * 0.15, 100)
: Math.min(order.total * 0.05, 100);

// GOOD: Explains non-obvious performance choice
// Use WeakMap to prevent memory leaks when components unmount
// Regular Map would keep references to deleted DOM elements
const componentCache = new WeakMap();

// GOOD: Documents external constraint
// API returns dates in UTC timezone without 'Z' suffix
// Convert to proper ISO format before parsing
const isoDate = apiDate.endsWith('Z') ? apiDate : apiDate + 'Z';
\`\`\`

## Documentation Guidelines

### 📋 **Comment Checklist**
- [ ] Explains **why**, not **what**
- [ ] Documents non-obvious business logic
- [ ] Warns about side effects or gotchas
- [ ] Includes parameter validation rules
- [ ] Provides usage examples for complex APIs
- [ ] Documents performance implications
- [ ] Notes external dependencies or constraints

### 🎯 **Focus Areas**
1. **Business Logic**: Why specific rules or calculations exist
2. **Performance Decisions**: Why this approach over alternatives
3. **Edge Cases**: How unusual inputs are handled
4. **External Constraints**: API quirks, browser compatibility
5. **Future Considerations**: TODOs, known limitations

**Task**: Add meaningful, valuable comments to the provided code. Focus on clarifying intent, explaining complex logic, and documenting important decisions or constraints.`;
return PROMPT;
}

Expand Down
Loading