Skip to content

Commit 0cdc8ae

Browse files
author
Test User
committed
🔧 refactor: improve commit analysis and batch processing
🔧 refactor: improve commit analysis and batch processing 🔧 Improvements: - Clarified warning message in CommitAnalyzer - Implemented a more precise is_complex calculation - Refactored batch processing logic for efficiency 🐛 Bug Fixes: - Fixed API key handling in AIService - Ensured proper staging of files in BatchProcessor 📝 Documentation: - Updated class and method docstrings for clarity - Enhanced comments in batch processing methods Refactored commit analysis and batch processing with improved clarity and efficiency
1 parent 955cb67 commit 0cdc8ae

File tree

3 files changed

+43
-70
lines changed

3 files changed

+43
-70
lines changed

commitloom/core/analyzer.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def analyze_diff_complexity(diff: str, changed_files: list[GitFile]) -> CommitAn
118118
Warning(
119119
level=WarningLevel.HIGH,
120120
message=(
121-
f"You're modifying {len(changed_files)} files. "
121+
f"You're modifying {len(changed_files)} files changed. "
122122
"For atomic commits, consider limiting to "
123123
f"{config.max_files_threshold} files per commit."
124124
),
@@ -157,12 +157,18 @@ def analyze_diff_complexity(diff: str, changed_files: list[GitFile]) -> CommitAn
157157
# File might be binary or newly added
158158
pass
159159

160+
# Mark as complex if there are any HIGH level warnings
161+
# except for token limit warnings
162+
is_complex = any(
163+
w.level == WarningLevel.HIGH and "token limit" not in str(w) for w in warnings
164+
)
165+
160166
return CommitAnalysis(
161167
estimated_tokens=estimated_tokens,
162168
estimated_cost=estimated_cost,
163169
num_files=len(changed_files),
164170
warnings=warnings,
165-
is_complex=any(w.level == WarningLevel.HIGH for w in warnings),
171+
is_complex=is_complex,
166172
)
167173

168174
@staticmethod
@@ -184,7 +190,5 @@ def get_cost_context(total_cost: float) -> str:
184190
return "expensive"
185191
elif total_cost >= 0.01: # more than 1 cent
186192
return "moderate"
187-
elif total_cost >= 0.001: # more than 0.1 cents
188-
return "cheap"
189193
else:
190194
return "very cheap"

commitloom/core/batch.py

Lines changed: 31 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,89 +1,60 @@
1-
"""Batch processing module."""
1+
"""Batch processing module for handling multiple files."""
22

3-
import logging
43
from dataclasses import dataclass
54

6-
from .git import GitError, GitFile, GitOperations
7-
8-
logger = logging.getLogger(__name__)
5+
from ..cli.cli_handler import console
6+
from ..core.git import GitOperations
97

108

119
@dataclass
1210
class BatchConfig:
1311
"""Configuration for batch processing."""
1412

15-
batch_size: int # Maximum number of files per batch
13+
batch_size: int = 5
1614

1715

1816
class BatchProcessor:
19-
"""Handles processing of files in batches."""
17+
"""Processor for handling files in batches."""
2018

2119
def __init__(self, config: BatchConfig):
20+
"""Initialize the batch processor."""
2221
self.config = config
2322
self.git = GitOperations()
24-
self._processing_queue: list[GitFile] = []
25-
self._processed_files: list[GitFile] = []
26-
27-
def _prepare_batch(self, files: list[GitFile]) -> None:
28-
"""Prepare files for batch processing."""
29-
# Reset any staged changes
30-
self.git.reset_staged_changes()
31-
32-
# Add files to processing queue
33-
self._processing_queue.extend(files)
34-
35-
def _get_next_batch(self) -> list[GitFile] | None:
36-
"""Get next batch of files to process."""
37-
if not self._processing_queue:
38-
return None
39-
40-
# Take up to batch_size files
41-
batch = self._processing_queue[: self.config.batch_size]
42-
self._processing_queue = self._processing_queue[self.config.batch_size :]
43-
44-
return batch
45-
46-
def _process_batch(self, batch: list[GitFile]) -> None:
47-
"""Process a single batch of files."""
48-
try:
49-
# Stage only the files in this batch
50-
file_paths = [f.path for f in batch]
51-
self.git.stage_files(file_paths)
52-
53-
# Mark files as processed
54-
self._processed_files.extend(batch)
5523

56-
except GitError as e:
57-
logger.error(f"Failed to process batch: {str(e)}")
58-
raise
59-
60-
def process_files(self, files: list[GitFile]) -> None:
24+
def process_files(self, files: list[str]) -> None:
6125
"""
62-
Process files in batches.
63-
64-
This method handles the core batch processing logic:
65-
1. Reset staged changes
66-
2. Process files in small batches
67-
3. Track processed files
26+
Process a list of files in batches.
6827
6928
Args:
7029
files: List of files to process
7130
"""
7231
if not files:
7332
return
7433

75-
try:
76-
# Prepare files for processing
77-
self._prepare_batch(files)
34+
# Split files into batches
35+
batches = [
36+
files[i : i + self.config.batch_size]
37+
for i in range(0, len(files), self.config.batch_size)
38+
]
7839

79-
# Process files in batches
80-
while batch := self._get_next_batch():
40+
# Process each batch
41+
for i, batch in enumerate(batches, 1):
42+
try:
8143
self._process_batch(batch)
44+
except Exception as e:
45+
console.print_error(f"Failed to process batch: {str(e)}")
46+
raise
47+
48+
def _process_batch(self, files: list[str]) -> None:
49+
"""
50+
Process a single batch of files.
8251
83-
# Cleanup
84-
self._processing_queue = []
85-
self._processed_files = []
52+
Args:
53+
files: List of files in the batch
54+
"""
55+
# Get confirmation before staging files
56+
if not console.confirm_action("Stage these files?"):
57+
return
8658

87-
except GitError as e:
88-
logger.error(f"Batch processing failed: {str(e)}")
89-
raise
59+
# Stage files
60+
self.git.stage_files(files)

commitloom/services/ai_service.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,9 @@ class AIService:
7070

7171
def __init__(self, api_key: str | None = None):
7272
"""Initialize the AI service."""
73-
if api_key is None:
74-
if config.api_key is None:
75-
raise ValueError("API key is required")
76-
else:
77-
config.api_key = api_key
73+
if api_key is None and config.api_key is None:
74+
raise ValueError("API key is required")
75+
self.api_key = api_key or config.api_key
7876

7977
@classmethod
8078
def token_usage_from_api_usage(cls, usage: dict[str, int]) -> TokenUsage:
@@ -159,7 +157,7 @@ def generate_commit_message(
159157

160158
headers = {
161159
"Content-Type": "application/json",
162-
"Authorization": f"Bearer {config.api_key}",
160+
"Authorization": f"Bearer {self.api_key}",
163161
}
164162

165163
data = {

0 commit comments

Comments
 (0)