Skip to content

Commit 702e281

Browse files
committed
🔧 chore: refactor imports and improve code structure
🔧 chore: refactor imports and improve code structure 🔧 Refactoring: - Reordered import statements for consistency in several files. - Changed type annotations from 'List' and 'Dict' to 'list' and 'dict' for better readability. ✨ Code Improvements: - Enhanced readability by adjusting whitespace and formatting in multiple files. - Removed redundant imports to streamline the codebase. These changes improve the code structure and readability, making future development easier.
1 parent ce86008 commit 702e281

14 files changed

+72
-70
lines changed

commitloom/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
"""CommitLoom - Weave perfect git commits with AI-powered intelligence."""
22

33
from .cli.main import CommitLoom, main
4-
from .core.git import GitOperations, GitFile, GitError
5-
from .core.analyzer import CommitAnalyzer, CommitAnalysis, Warning, WarningLevel
4+
from .core.analyzer import CommitAnalysis, CommitAnalyzer, Warning, WarningLevel
5+
from .core.git import GitError, GitFile, GitOperations
66
from .services.ai_service import AIService, CommitSuggestion, TokenUsage
77

88
__version__ = "0.1.0"

commitloom/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
"""Entry point for running commitloom as a module."""
33

44
from pathlib import Path
5+
56
from dotenv import load_dotenv
6-
import os
77

88
# Load environment variables before any imports
99
env_path = Path(__file__).parent.parent / ".env"

commitloom/cli/console.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
"""Console output formatting and user interaction."""
22

3+
34
from rich.console import Console
45
from rich.panel import Panel
5-
from rich.prompt import Confirm, Prompt
6-
from rich.text import Text
76
from rich.progress import (
7+
BarColumn,
88
Progress,
99
SpinnerColumn,
10-
TextColumn,
11-
BarColumn,
1210
TaskProgressColumn,
11+
TextColumn,
1312
)
14-
from typing import List, Optional
13+
from rich.prompt import Confirm, Prompt
14+
from rich.text import Text
1515

16-
from ..core.analyzer import CommitAnalysis, WarningLevel
16+
from ..core.analyzer import CommitAnalysis, CommitAnalyzer, WarningLevel
1717
from ..core.git import GitFile
1818
from ..services.ai_service import TokenUsage
19-
from ..core.analyzer import CommitAnalyzer
2019

2120
console = Console()
2221

@@ -32,7 +31,7 @@ def create_progress() -> Progress:
3231
)
3332

3433

35-
def print_changed_files(files: List[GitFile]) -> None:
34+
def print_changed_files(files: list[GitFile]) -> None:
3635
"""Print list of changed files."""
3736
console.print(
3837
"\n[bold blue]📜 Changes detected in the following files:[/bold blue]"
@@ -57,7 +56,7 @@ def print_warnings(analysis: CommitAnalysis) -> None:
5756
console.print(f" • Files changed: {analysis.num_files}")
5857

5958

60-
def print_batch_start(batch_num: int, total_batches: int, files: List[GitFile]) -> None:
59+
def print_batch_start(batch_num: int, total_batches: int, files: list[GitFile]) -> None:
6160
"""Print information about starting a new batch."""
6261
console.print(
6362
f"\n[bold blue]📦 Processing Batch {batch_num}/{total_batches}[/bold blue]"
@@ -76,7 +75,7 @@ def print_batch_complete(batch_num: int, total_batches: int) -> None:
7675

7776
def print_batch_summary(total_files: int, total_batches: int) -> None:
7877
"""Print summary of batch processing plan."""
79-
console.print(f"\n[bold blue]🔄 Batch Processing Summary:[/bold blue]")
78+
console.print("\n[bold blue]🔄 Batch Processing Summary:[/bold blue]")
8079
console.print(f" • Total files: [cyan]{total_files}[/cyan]")
8180
console.print(f" • Number of batches: [cyan]{total_batches}[/cyan]")
8281
console.print(f" • Files per batch: [cyan]~{total_files // total_batches}[/cyan]")
@@ -89,7 +88,7 @@ def format_cost(cost: float) -> str:
8988
return f"{human_cost} {precise_cost}"
9089

9190

92-
def print_token_usage(usage: TokenUsage, batch_num: Optional[int] = None) -> None:
91+
def print_token_usage(usage: TokenUsage, batch_num: int | None = None) -> None:
9392
"""Print token usage summary."""
9493
batch_info = f" (Batch {batch_num})" if batch_num is not None else ""
9594
console.print(
@@ -112,7 +111,7 @@ def print_commit_message(message: str) -> None:
112111
console.print(Panel(Text(message), expand=False, border_style="green"))
113112

114113

115-
def print_batch_info(batch_number: int, files: List[str]) -> None:
114+
def print_batch_info(batch_number: int, files: list[str]) -> None:
116115
"""Print information about a batch of files."""
117116
console.print(f"\n[bold blue]📑 Batch {batch_number} Summary:[/bold blue]")
118117
for file in files:

commitloom/cli/main.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,22 @@
11
#!/usr/bin/env python3
22
"""Main CLI module for CommitLoom."""
33

4-
import os
5-
import sys
6-
import subprocess
7-
import logging
84
import argparse
5+
import logging
6+
import subprocess
7+
import sys
98
from pathlib import Path
10-
from typing import List, Dict
9+
1110
from dotenv import load_dotenv
1211

1312
# Load environment variables at module level
1413
env_path = Path(__file__).parent.parent.parent / ".env"
1514
load_dotenv(dotenv_path=env_path)
1615

17-
from ..core.git import GitOperations, GitFile, GitError
18-
from ..core.analyzer import CommitAnalyzer, CommitAnalysis
19-
from ..services.ai_service import AIService, CommitSuggestion
2016
from ..config.settings import config
17+
from ..core.analyzer import CommitAnalyzer
18+
from ..core.git import GitError, GitFile, GitOperations
19+
from ..services.ai_service import AIService, CommitSuggestion
2120
from . import console
2221

2322
# Configure logging
@@ -40,8 +39,8 @@ def __init__(self):
4039
self.ai_service = AIService()
4140

4241
def process_files_in_batches(
43-
self, changed_files: List[GitFile], auto_commit: bool = False
44-
) -> List[Dict]:
42+
self, changed_files: list[GitFile], auto_commit: bool = False
43+
) -> list[dict]:
4544
"""Process files in batches for better commit organization."""
4645
total_files = len(changed_files)
4746
total_batches = (
@@ -177,7 +176,7 @@ def run(self, auto_commit: bool = False, combine_commits: bool = False) -> None:
177176
console.print_error(f"An error occurred: {str(e)}")
178177

179178
def _create_individual_commit(
180-
self, batch: Dict, auto_confirm: bool = False
179+
self, batch: dict, auto_confirm: bool = False
181180
) -> None:
182181
"""Create an individual commit for a batch."""
183182
files = [f.path for f in batch["files"]]
@@ -220,7 +219,7 @@ def _create_individual_commit(
220219
except Exception:
221220
pass # Ignore status check errors
222221

223-
def _create_combined_commit(self, batches: List[Dict]) -> None:
222+
def _create_combined_commit(self, batches: list[dict]) -> None:
224223
"""Create a combined commit from all batches."""
225224
all_changes = {}
226225
summary_points = []

commitloom/config/settings.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"""Configuration settings for CommitLoom."""
22

33
import os
4+
from dataclasses import dataclass
45
from pathlib import Path
6+
57
from dotenv import load_dotenv
6-
from dataclasses import dataclass
7-
from typing import List, Dict
88

99
# Load environment variables at module level
1010
env_path = Path(__file__).parent.parent.parent / ".env"
@@ -28,8 +28,8 @@ class Config:
2828
cost_warning_threshold: float
2929
default_model: str
3030
token_estimation_ratio: int
31-
ignored_patterns: List[str]
32-
model_costs: Dict[str, ModelCosts]
31+
ignored_patterns: list[str]
32+
model_costs: dict[str, ModelCosts]
3333
api_key: str
3434

3535
@classmethod

commitloom/core/analyzer.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""Analyzer module for commit complexity and cost estimation."""
22

33
from dataclasses import dataclass
4-
from typing import List
54
from enum import Enum
65

76
from ..config.settings import config
@@ -31,7 +30,7 @@ class CommitAnalysis:
3130
estimated_tokens: int
3231
estimated_cost: float
3332
num_files: int
34-
warnings: List[Warning]
33+
warnings: list[Warning]
3534
is_complex: bool
3635

3736

@@ -60,7 +59,7 @@ def estimate_tokens_and_cost(
6059

6160
@staticmethod
6261
def analyze_diff_complexity(
63-
diff: str, changed_files: List[GitFile]
62+
diff: str, changed_files: list[GitFile]
6463
) -> CommitAnalysis:
6564
"""
6665
Analyzes the complexity of changes and returns warnings if necessary.
@@ -72,7 +71,7 @@ def analyze_diff_complexity(
7271
Returns:
7372
CommitAnalysis object containing analysis results
7473
"""
75-
warnings: List[Warning] = []
74+
warnings: list[Warning] = []
7675
estimated_tokens, estimated_cost = CommitAnalyzer.estimate_tokens_and_cost(diff)
7776

7877
# Check token limit

commitloom/core/git.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
"""Git operations and utilities."""
22

3-
import subprocess
43
import logging
5-
from typing import List, Optional
4+
import subprocess
65
from dataclasses import dataclass
76
from fnmatch import fnmatch
8-
import os
97

108
from ..config.settings import config
119

@@ -18,8 +16,8 @@ class GitFile:
1816
"""Represents a git file with its metadata."""
1917

2018
path: str
21-
size: Optional[int] = None
22-
hash: Optional[str] = None
19+
size: int | None = None
20+
hash: str | None = None
2321

2422

2523
class GitError(Exception):
@@ -40,7 +38,7 @@ def should_ignore_file(file_path: str) -> bool:
4038
)
4139

4240
@staticmethod
43-
def get_changed_files() -> List[GitFile]:
41+
def get_changed_files() -> list[GitFile]:
4442
"""Get list of staged files, excluding ignored files."""
4543
try:
4644
files = (
@@ -90,7 +88,7 @@ def get_changed_files() -> List[GitFile]:
9088
raise GitError(f"Failed to get changed files: {str(e)}")
9189

9290
@staticmethod
93-
def get_diff(files: Optional[List[GitFile]] = None) -> str:
91+
def get_diff(files: list[GitFile] | None = None) -> str:
9492
"""Get the staged diff, handling binary files."""
9593
try:
9694
if files is None:
@@ -137,7 +135,7 @@ def format_file_size(size: int) -> str:
137135
return f"{size:.2f} TB"
138136

139137
@staticmethod
140-
def stage_files(files: List[str]) -> None:
138+
def stage_files(files: list[str]) -> None:
141139
"""Stage specific files for commit."""
142140
try:
143141
# Get status of files to handle deleted ones correctly
@@ -202,7 +200,7 @@ def stage_files(files: List[str]) -> None:
202200

203201
@staticmethod
204202
def create_commit(
205-
title: str, message: str, files: Optional[List[str]] = None
203+
title: str, message: str, files: list[str] | None = None
206204
) -> bool:
207205
"""Create a git commit with the specified message."""
208206
try:
@@ -297,7 +295,7 @@ def pop_stashed_changes() -> None:
297295
)
298296

299297
@staticmethod
300-
def get_staged_files() -> List[str]:
298+
def get_staged_files() -> list[str]:
301299
"""Get list of currently staged files."""
302300
try:
303301
return (

commitloom/services/ai_service.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
"""AI service for generating commit messages using OpenAI."""
22

33
import json
4-
import requests
54
from dataclasses import dataclass
6-
from typing import Dict, List, Tuple
5+
6+
import requests
77

88
from ..config.settings import config
99
from ..core.git import GitFile
@@ -22,7 +22,7 @@ class TokenUsage:
2222

2323
@classmethod
2424
def from_api_usage(
25-
cls, usage: Dict[str, int], model: str = config.default_model
25+
cls, usage: dict[str, int], model: str = config.default_model
2626
) -> "TokenUsage":
2727
"""Create TokenUsage from API response usage data."""
2828
prompt_tokens = usage["prompt_tokens"]
@@ -49,7 +49,7 @@ class CommitSuggestion:
4949
"""Generated commit message suggestion."""
5050

5151
title: str
52-
body: Dict[str, Dict[str, List[str]]]
52+
body: dict[str, dict[str, list[str]]]
5353
summary: str
5454

5555

@@ -74,7 +74,7 @@ def format_commit_message(self, commit_data: CommitSuggestion) -> str:
7474
formatted_message += f"{commit_data.summary}\n"
7575
return formatted_message
7676

77-
def _generate_prompt(self, diff: str, changed_files: List[GitFile]) -> str:
77+
def _generate_prompt(self, diff: str, changed_files: list[GitFile]) -> str:
7878
"""Generate a prompt for commit message generation."""
7979
files_summary = ", ".join(f.path for f in changed_files[:3])
8080
if len(changed_files) > 3:
@@ -144,8 +144,8 @@ def _generate_prompt(self, diff: str, changed_files: List[GitFile]) -> str:
144144
}}"""
145145

146146
def generate_commit_message(
147-
self, diff: str, changed_files: List[GitFile]
148-
) -> Tuple[CommitSuggestion, TokenUsage]:
147+
self, diff: str, changed_files: list[GitFile]
148+
) -> tuple[CommitSuggestion, TokenUsage]:
149149
"""Generate a commit message using the OpenAI API."""
150150
prompt = self._generate_prompt(diff, changed_files)
151151

tests/conftest.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
23
import pytest
34

45

@@ -9,4 +10,4 @@ def mock_env_vars():
910
yield
1011
# Clean up
1112
if "OPENAI_API_KEY" in os.environ:
12-
del os.environ["OPENAI_API_KEY"]
13+
del os.environ["OPENAI_API_KEY"]

tests/test_ai_service.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
"""Tests for AI service module."""
22

3-
import pytest
4-
from unittest.mock import patch, MagicMock
53
import json
4+
from unittest.mock import MagicMock, patch
5+
6+
import pytest
67
import requests
78

9+
from commitloom.config.settings import config
10+
from commitloom.core.git import GitFile
811
from commitloom.services.ai_service import (
912
AIService,
10-
TokenUsage,
1113
CommitSuggestion,
14+
TokenUsage,
1215
)
13-
from commitloom.core.git import GitFile
14-
from commitloom.config.settings import config
1516

1617

1718
@pytest.fixture

tests/test_analyzer.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
"""Tests for analyzer module."""
22

33
import pytest
4+
5+
from commitloom.config.settings import config
46
from commitloom.core.analyzer import (
5-
CommitAnalyzer,
67
CommitAnalysis,
8+
CommitAnalyzer,
79
WarningLevel,
810
)
911
from commitloom.core.git import GitFile
10-
from commitloom.config.settings import config
1112

1213

1314
@pytest.fixture

0 commit comments

Comments
 (0)