Skip to content

Commit c973df8

Browse files
refactor(examples): configuration management system
changes: - file: mcp_demo.py area: core modified: [analyze_with_code2llm] - file: refactored_output.py area: core added: [main] modified: [save_data, OrderManager, send_email, __init__, validate_order, execute_query, +6 more] stats: lines: "+103/-49 (net +54)" files: 2 complexity: "+77% complexity (monitor)"
1 parent ee3a532 commit c973df8

File tree

6 files changed

+118
-52
lines changed

6 files changed

+118
-52
lines changed

CHANGELOG.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
1+
## [0.1.7] - 2026-03-01
2+
3+
### Summary
4+
5+
refactor(examples): configuration management system
6+
7+
### Other
8+
9+
- update examples/10_mcp_ollama_demo/mcp_demo.py
10+
- update examples/10_mcp_ollama_demo/refactored_output.py
11+
12+
113
## [0.1.6] - 2026-03-01
214

315
### Summary

VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
0.1.6
1+
0.1.7

examples/10_mcp_ollama_demo/mcp_demo.py

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,27 +74,46 @@ def analyze_with_code2llm(code_path: Path) -> dict:
7474
log_step(1, "Analyzing code structure with code2llm")
7575

7676
try:
77-
from code2llm import analyze_file
77+
from code2llm import ProjectAnalyzer
7878

7979
logger.info(f"Analyzing file: {code_path}")
80-
result = analyze_file(str(code_path))
80+
analyzer = ProjectAnalyzer()
81+
82+
# Analyze the directory containing the file
83+
project_result = analyzer.analyze_project(str(code_path.parent))
8184

8285
print(f"{Colors.GREEN}✓ Analysis complete{Colors.END}")
83-
print(f" Functions found: {len(result.get('functions', []))}")
84-
print(f" Classes found: {len(result.get('classes', []))}")
85-
print(f" Complexity: {result.get('complexity', 'N/A')}")
86+
print(f" Functions found: {project_result.get_function_count()}")
87+
print(f" Classes found: {project_result.get_class_count()}")
88+
print(f" Modules: {len(project_result.modules)}")
89+
print(f" Code smells detected: {len(project_result.smells)}")
90+
print(f" Entry points: {len(project_result.entry_points)}")
91+
92+
# Extract detailed information
93+
functions_info = [{'name': f.name, 'line': f.line_start} for f in project_result.functions]
94+
classes_info = [{'name': c.name, 'line': c.line_start} for c in project_result.classes]
95+
smells_info = [{'type': s.type, 'message': s.message, 'line': s.line} for s in project_result.smells]
8696

87-
return result
88-
except ImportError:
89-
logger.warning("code2llm not available, using basic analysis")
97+
return {
98+
'functions': functions_info,
99+
'classes': classes_info,
100+
'modules': list(project_result.modules),
101+
'total_lines': len(code_path.read_text().split('\n')),
102+
'source': code_path.read_text(),
103+
'complexity': 'Available in code2llm analysis',
104+
'smells': smells_info,
105+
'issues': [] # Will be filled by vallm validation
106+
}
107+
except Exception as e:
108+
logger.warning(f"code2llm analysis failed: {e}, using basic analysis")
90109
# Fallback analysis
91110
code = code_path.read_text()
92111
lines = code.split('\n')
93112

94113
functions = [l for l in lines if l.strip().startswith('def ')]
95114
classes = [l for l in lines if l.strip().startswith('class ')]
96115

97-
print(f"{Colors.YELLOW}⚠ code2llm not installed, using basic analysis{Colors.END}")
116+
print(f"{Colors.YELLOW}⚠ code2llm analysis failed, using basic analysis{Colors.END}")
98117
print(f" Functions found: {len(functions)}")
99118
print(f" Classes found: {len(classes)}")
100119
print(f" Total lines: {len(lines)}")
@@ -103,7 +122,8 @@ def analyze_with_code2llm(code_path: Path) -> dict:
103122
'functions': functions,
104123
'classes': classes,
105124
'total_lines': len(lines),
106-
'source': code
125+
'source': code,
126+
'issues': []
107127
}
108128

109129

examples/10_mcp_ollama_demo/refactored_output.py

Lines changed: 73 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -14,80 +14,114 @@ class OrderManager:
1414

1515
def __init__(self):
1616
self.orders: List[Dict] = []
17-
self.cache: Dict[str, any] = {}
17+
self.cache: Dict[str, Any] = {}
1818
self.logger = None
1919

2020
def add_order(self, order: Dict) -> None:
21-
"""Add order with validation and sanitization."""
22-
if not validate_order(order):
21+
"""Add order with validation."""
22+
if not self.validate_order(order):
2323
raise ValueError("Invalid order data")
2424
self.orders.append(order)
2525
query = f"INSERT INTO orders VALUES ({order['id']}, '{order['name']}')"
2626
self.execute_query(query)
2727

28-
def execute_query(self, query: str) -> bool:
28+
def validate_order(self, order: Dict) -> bool:
29+
"""Validate order data."""
30+
return 'id' in order and 'name' in order
31+
32+
def execute_query(self, query: str) -> None:
2933
"""Execute SQL query with sanitization."""
3034
print(f"Executing: {query}")
31-
return True
3235

3336
def process_payment(self, amount: float, card_number: str) -> bool:
34-
"""Process payment securely using environment variables for credentials."""
35-
api_key = os.getenv("API_KEY", API_KEY)
36-
# No encryption
37+
"""Process payment securely."""
38+
# Use a secure payment gateway API
3739
print(f"Charging {amount} to card {card_number}")
3840
return True
3941

40-
def send_email(self, to: str, subject: str, body: str) -> bool:
41-
"""Send email securely using environment variables for credentials."""
42-
mail_command = f"echo '{body}' | mail -s '{subject}' {to}"
43-
subprocess.run(mail_command, shell=True)
44-
return True
42+
def send_email(self, to: str, subject: str, body: str) -> None:
43+
"""Send email safely using a library."""
44+
import smtplib
45+
from email.mime.text import MIMEText
46+
47+
msg = MIMEText(body)
48+
msg['Subject'] = subject
49+
msg['From'] = 'your-email@example.com'
50+
msg['To'] = to
51+
52+
with smtplib.SMTP('smtp.example.com', 587) as server:
53+
server.starttls()
54+
server.login('your-email@example.com', 'your-password')
55+
server.sendmail('your-email@example.com', to, msg.as_string())
4556

4657
def get_stats(self) -> Dict[str, int]:
4758
"""Calculate stats efficiently."""
4859
return {'total_orders': len(self.orders)}
4960

50-
def validate_order(order: Dict) -> bool:
51-
"""Validate order data."""
52-
if 'id' not in order or 'name' not in order:
53-
return False
54-
return True
61+
def validate_email(email: str) -> bool:
62+
"""Email validation using regex."""
63+
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
64+
return re.match(pattern, email) is not None
5565

5666
def calculate_shipping(weight: float) -> float:
57-
"""Calculate shipping cost based on weight."""
67+
"""Calculate shipping cost with constants."""
5868
if weight < 10:
5969
return 5.99
6070
elif weight < 50:
6171
return 10.99
6272
else:
6373
return 25.99
6474

65-
def load_config() -> Dict[str, any]:
66-
"""Load config securely using environment variables."""
67-
config_str = os.getenv('CONFIG', json.dumps(DEFAULT_CONFIG))
68-
try:
69-
return json.loads(config_str)
70-
except json.JSONDecodeError:
71-
return DEFAULT_CONFIG
75+
def load_config() -> Dict[str, Any]:
76+
"""Load config securely using json.loads."""
77+
config_str = os.environ.get('CONFIG', json.dumps(DEFAULT_CONFIG))
78+
return json.loads(config_str)
7279

73-
def save_data(data: Dict[str, any], filename: str) -> None:
74-
"""Save data safely using JSON serialization."""
80+
def save_data(data: Dict[str, Any], filename: str) -> None:
81+
"""Save data safely using json.dump."""
7582
with open(filename, 'w') as f:
7683
json.dump(data, f)
7784

78-
def process_order(data: Dict[str, any]) -> float:
85+
def process_order(data: Dict[str, Any]) -> float:
7986
"""Process order data with proper error handling and validation."""
8087
if not data or 'items' not in data:
8188
return 0
82-
items = data['items']
83-
total = sum(item.get('price', 0) * item.get('quantity', 0) for item in items)
84-
if total > 100:
85-
discount = total * 0.1
86-
final = total - discount
87-
return final
89+
90+
total = 0
91+
for item in data['items']:
92+
if 'price' in item and 'quantity' in item:
93+
price = item['price']
94+
quantity = item['quantity']
95+
if price > 0 and quantity > 0:
96+
item_total = price * quantity
97+
if item_total > 100:
98+
discount = item_total * 0.1
99+
total += item_total - discount
100+
else:
101+
total += item_total
102+
88103
return total
89104

90-
def validate_email(email: str) -> bool:
91-
"""Validate email address using regex."""
92-
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
93-
return re.match(pattern, email) is not None
105+
def main():
106+
config = load_config()
107+
order_manager = OrderManager()
108+
109+
# Example usage
110+
order_data = {
111+
'id': 1,
112+
'name': 'Sample Order',
113+
'items': [
114+
{'price': 50, 'quantity': 2},
115+
{'price': 30, 'quantity': 1}
116+
]
117+
}
118+
119+
final_price = process_order(order_data)
120+
print(f"Final price: {final_price}")
121+
122+
order_manager.add_order(order_data)
123+
stats = order_manager.get_stats()
124+
print(stats)
125+
126+
if __name__ == "__main__":
127+
main()

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
44

55
[project]
66
name = "vallm"
7-
version = "0.1.6"
7+
version = "0.1.7"
88
description = "A complete toolkit for validating LLM-generated code"
99
readme = "README.md"
1010
license = "Apache-2.0"

src/vallm/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@
1616
"detect_language",
1717
]
1818

19-
__version__ = "0.1.6"
19+
__version__ = "0.1.7"

0 commit comments

Comments
 (0)