mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 14:16:34 +09:00
background tasks
This commit is contained in:
1 parent
e1afe444d4
commit
9811b78b5b
215 files changed
+39531
-2917
No files matched your search
@@ -0,0 +1,191 @@
|
||||
# Complex Hello World Application
|
||||
|
||||
A sophisticated multi-file Python hello world application demonstrating advanced software engineering practices including modular architecture, configuration management, logging, testing, and multiple output styles.
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-language support**: English, Spanish, French, German, Italian, and Japanese
|
||||
- **Multiple greeting styles**: Simple, Fancy, Banner, and ASCII art
|
||||
- **Configurable settings**: JSON file or environment variables
|
||||
- **Advanced logging**: Colored console output with multiple log levels
|
||||
- **Comprehensive testing**: Unit tests with pytest
|
||||
- **Modular architecture**: Separated concerns with core, utils, and config modules
|
||||
- **CLI interface**: Full command-line argument support
|
||||
- **Decorators**: Timer, validation, retry, memoization, and more
|
||||
- **Multiple formatting options**: Progress bars, tables, and styled messages
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
python-hello-complex-4/
|
||||
├── main.py # Main entry point
|
||||
├── config.py # Configuration management
|
||||
├── core/ # Core business logic
|
||||
│ ├── __init__.py
|
||||
│ ├── greeting_generator.py # Multi-language greeting generation
|
||||
│ └── message_formatter.py # Message formatting with styles
|
||||
├── utils/ # Utility modules
|
||||
│ ├── __init__.py
|
||||
│ ├── logger.py # Custom logging with colors
|
||||
│ └── decorators.py # Helpful decorators
|
||||
├── tests/ # Unit tests
|
||||
│ ├── __init__.py
|
||||
│ └── test_greeting.py # Comprehensive test suite
|
||||
├── requirements.txt # Python dependencies
|
||||
├── config.json # Sample configuration file
|
||||
└── README.md # This file
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
1. Clone or download this directory
|
||||
2. Install dependencies (optional, for development):
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```bash
|
||||
# Simple hello world
|
||||
python main.py
|
||||
|
||||
# Greet a specific person
|
||||
python main.py --name "Alice"
|
||||
|
||||
# Use a different language
|
||||
python main.py --name "Carlos" --language spanish
|
||||
|
||||
# Use fancy formatting
|
||||
python main.py --name "Marie" --language french --style fancy
|
||||
|
||||
# Enable debug logging
|
||||
python main.py --debug
|
||||
```
|
||||
|
||||
### Command Line Options
|
||||
|
||||
- `--name, -n`: Name to greet (default: "World")
|
||||
- `--language, -l`: Language for greeting (choices: english, spanish, french, german, italian, japanese)
|
||||
- `--style, -s`: Message style (choices: simple, fancy, banner, ascii)
|
||||
- `--debug, -d`: Enable debug logging
|
||||
- `--config, -c`: Path to custom configuration file
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
# ASCII art style
|
||||
python main.py --name "World" --style ascii
|
||||
|
||||
# Spanish greeting with banner style
|
||||
python main.py --name "Amigo" --language spanish --style banner
|
||||
|
||||
# Japanese greeting
|
||||
python main.py --name "Tanaka" --language japanese
|
||||
|
||||
# Using custom configuration
|
||||
python main.py --config custom_config.json
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Configuration File (config.json)
|
||||
|
||||
```json
|
||||
{
|
||||
"default_name": "World",
|
||||
"default_language": "english",
|
||||
"default_style": "simple",
|
||||
"log_level": "INFO",
|
||||
"enable_emoji": true,
|
||||
"enable_colors": true,
|
||||
"max_line_length": 80
|
||||
}
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
- `HELLO_DEFAULT_NAME`: Default name to greet
|
||||
- `HELLO_DEFAULT_LANGUAGE`: Default language
|
||||
- `HELLO_DEFAULT_STYLE`: Default formatting style
|
||||
- `HELLO_LOG_LEVEL`: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
||||
- `HELLO_ENABLE_EMOJI`: Enable emoji support (true/false)
|
||||
- `HELLO_ENABLE_COLORS`: Enable colored output (true/false)
|
||||
|
||||
## Development
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
python -m pytest tests/
|
||||
|
||||
# Run with coverage
|
||||
python -m pytest tests/ --cov=. --cov-report=html
|
||||
|
||||
# Run specific test file
|
||||
python tests/test_greeting.py
|
||||
```
|
||||
|
||||
### Code Style
|
||||
|
||||
```bash
|
||||
# Format code with black
|
||||
black .
|
||||
|
||||
# Check style with flake8
|
||||
flake8 .
|
||||
|
||||
# Type checking with mypy
|
||||
mypy .
|
||||
```
|
||||
|
||||
## API Documentation
|
||||
|
||||
### GreetingGenerator
|
||||
|
||||
Generates greetings in multiple languages with various styles.
|
||||
|
||||
```python
|
||||
from core.greeting_generator import GreetingGenerator
|
||||
from config import Config
|
||||
|
||||
config = Config()
|
||||
generator = GreetingGenerator(config)
|
||||
|
||||
# Generate a greeting
|
||||
greeting = generator.generate("Alice", "english", style="formal")
|
||||
|
||||
# Get random greeting
|
||||
random_greeting = generator.get_random_greeting("Bob", "spanish")
|
||||
```
|
||||
|
||||
### MessageFormatter
|
||||
|
||||
Formats messages with different visual styles.
|
||||
|
||||
```python
|
||||
from core.message_formatter import MessageFormatter
|
||||
from config import Config
|
||||
|
||||
config = Config()
|
||||
formatter = MessageFormatter(config)
|
||||
|
||||
# Format with style
|
||||
formatted = formatter.format("Hello, World!", style="banner")
|
||||
|
||||
# Create progress bar
|
||||
progress = formatter.create_progress_bar(50, 100)
|
||||
|
||||
# Create table
|
||||
table = formatter.create_table(
|
||||
["Name", "Language"],
|
||||
[["Alice", "English"], ["Carlos", "Spanish"]]
|
||||
)
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
This is a demonstration project created for educational purposes.
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Complex Hello World Application Package"""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
__author__ = "Claude Code"
|
||||
__description__ = "A complex multi-file Python hello world application"
|
||||
Binary file not shown.
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"default_name": "World",
|
||||
"default_language": "english",
|
||||
"default_style": "simple",
|
||||
"log_level": "INFO",
|
||||
"enable_emoji": true,
|
||||
"enable_colors": true,
|
||||
"enable_sound": false,
|
||||
"max_line_length": 80,
|
||||
"indent_size": 4
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
Configuration module for Hello World application
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass, asdict
|
||||
from typing import Dict, Any
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
"""Configuration class for Hello World application"""
|
||||
|
||||
# Default values
|
||||
default_name: str = "World"
|
||||
default_language: str = "english"
|
||||
default_style: str = "simple"
|
||||
log_level: str = "INFO"
|
||||
|
||||
# Feature flags
|
||||
enable_emoji: bool = True
|
||||
enable_colors: bool = True
|
||||
enable_sound: bool = False
|
||||
|
||||
# Formatting options
|
||||
max_line_length: int = 80
|
||||
indent_size: int = 4
|
||||
|
||||
# Language settings
|
||||
supported_languages: tuple = (
|
||||
"english", "spanish", "french",
|
||||
"german", "italian", "japanese"
|
||||
)
|
||||
|
||||
# Style settings
|
||||
supported_styles: tuple = (
|
||||
"simple", "fancy", "banner", "ascii"
|
||||
)
|
||||
|
||||
def __init__(self, config_file: str = None):
|
||||
"""Initialize configuration from file or defaults"""
|
||||
if config_file and Path(config_file).exists():
|
||||
self._load_from_file(config_file)
|
||||
else:
|
||||
self._load_from_env()
|
||||
|
||||
def _load_from_file(self, config_file: str):
|
||||
"""Load configuration from JSON file"""
|
||||
try:
|
||||
with open(config_file, 'r') as f:
|
||||
config_data = json.load(f)
|
||||
self._update_from_dict(config_data)
|
||||
except Exception as e:
|
||||
print(f"Warning: Could not load config file {config_file}: {e}")
|
||||
|
||||
def _load_from_env(self):
|
||||
"""Load configuration from environment variables"""
|
||||
env_mappings = {
|
||||
'HELLO_DEFAULT_NAME': 'default_name',
|
||||
'HELLO_DEFAULT_LANGUAGE': 'default_language',
|
||||
'HELLO_DEFAULT_STYLE': 'default_style',
|
||||
'HELLO_LOG_LEVEL': 'log_level',
|
||||
'HELLO_ENABLE_EMOJI': 'enable_emoji',
|
||||
'HELLO_ENABLE_COLORS': 'enable_colors',
|
||||
}
|
||||
|
||||
for env_var, attr in env_mappings.items():
|
||||
value = os.environ.get(env_var)
|
||||
if value is not None:
|
||||
# Handle boolean conversion
|
||||
if attr.startswith('enable_'):
|
||||
value = value.lower() in ('true', '1', 'yes')
|
||||
setattr(self, attr, value)
|
||||
|
||||
def _update_from_dict(self, data: Dict[str, Any]):
|
||||
"""Update configuration from dictionary"""
|
||||
for key, value in data.items():
|
||||
if hasattr(self, key):
|
||||
setattr(self, key, value)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert configuration to dictionary"""
|
||||
return asdict(self)
|
||||
|
||||
def save(self, config_file: str):
|
||||
"""Save configuration to JSON file"""
|
||||
with open(config_file, 'w') as f:
|
||||
json.dump(self.to_dict(), f, indent=2)
|
||||
|
||||
def validate(self) -> bool:
|
||||
"""Validate configuration values"""
|
||||
validations = [
|
||||
self.default_language in self.supported_languages,
|
||||
self.default_style in self.supported_styles,
|
||||
self.log_level in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"),
|
||||
self.max_line_length > 0,
|
||||
self.indent_size > 0
|
||||
]
|
||||
return all(validations)
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""String representation of configuration"""
|
||||
return json.dumps(self.to_dict(), indent=2)
|
||||
|
||||
|
||||
# Create default configuration instance
|
||||
default_config = Config()
|
||||
@@ -0,0 +1,8 @@
|
||||
"""Core package for Hello World application"""
|
||||
from .greeting_generator import GreetingGenerator
|
||||
from .message_formatter import MessageFormatter
|
||||
|
||||
__all__ = [
|
||||
'GreetingGenerator',
|
||||
'MessageFormatter'
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
Greeting generator module for Hello World application
|
||||
"""
|
||||
import random
|
||||
from typing import Dict, List, Optional
|
||||
from dataclasses import dataclass
|
||||
from utils.decorators import memoize, timer
|
||||
from config import Config
|
||||
|
||||
|
||||
@dataclass
|
||||
class GreetingTemplate:
|
||||
"""Template for a greeting in a specific language"""
|
||||
language: str
|
||||
formal: str
|
||||
informal: str
|
||||
casual: str
|
||||
time_based: Dict[str, str]
|
||||
special: Dict[str, str]
|
||||
|
||||
|
||||
class GreetingGenerator:
|
||||
"""Generate greetings in multiple languages with various styles"""
|
||||
|
||||
def __init__(self, config: Config):
|
||||
self.config = config
|
||||
self.templates = self._initialize_templates()
|
||||
self.emoji_map = self._initialize_emoji_map()
|
||||
|
||||
def _initialize_templates(self) -> Dict[str, GreetingTemplate]:
|
||||
"""Initialize greeting templates for all supported languages"""
|
||||
return {
|
||||
"english": GreetingTemplate(
|
||||
language="english",
|
||||
formal="Good day, {name}!",
|
||||
informal="Hello, {name}!",
|
||||
casual="Hey {name}!",
|
||||
time_based={
|
||||
"morning": "Good morning, {name}!",
|
||||
"afternoon": "Good afternoon, {name}!",
|
||||
"evening": "Good evening, {name}!",
|
||||
"night": "Good night, {name}!"
|
||||
},
|
||||
special={
|
||||
"welcome": "Welcome, {name}!",
|
||||
"greeting": "Greetings, {name}!",
|
||||
"salutation": "Salutations, {name}!"
|
||||
}
|
||||
),
|
||||
"spanish": GreetingTemplate(
|
||||
language="spanish",
|
||||
formal="Buenos días, {name}!",
|
||||
informal="¡Hola, {name}!",
|
||||
casual="¡Ey {name}!",
|
||||
time_based={
|
||||
"morning": "¡Buenos días, {name}!",
|
||||
"afternoon": "¡Buenas tardes, {name}!",
|
||||
"evening": "¡Buenas tardes, {name}!",
|
||||
"night": "¡Buenas noches, {name}!"
|
||||
},
|
||||
special={
|
||||
"welcome": "¡Bienvenido, {name}!",
|
||||
"greeting": "¡Saludos, {name}!",
|
||||
"salutation": "¡Saludos cordiales, {name}!"
|
||||
}
|
||||
),
|
||||
"french": GreetingTemplate(
|
||||
language="french",
|
||||
formal="Bonjour, {name}!",
|
||||
informal="Salut, {name}!",
|
||||
casual="Coucou {name}!",
|
||||
time_based={
|
||||
"morning": "Bonjour, {name}!",
|
||||
"afternoon": "Bon après-midi, {name}!",
|
||||
"evening": "Bonsoir, {name}!",
|
||||
"night": "Bonne nuit, {name}!"
|
||||
},
|
||||
special={
|
||||
"welcome": "Bienvenue, {name}!",
|
||||
"greeting": "Salutations, {name}!",
|
||||
"salutation": "Mes salutations, {name}!"
|
||||
}
|
||||
),
|
||||
"german": GreetingTemplate(
|
||||
language="german",
|
||||
formal="Guten Tag, {name}!",
|
||||
informal="Hallo, {name}!",
|
||||
casual="Hey {name}!",
|
||||
time_based={
|
||||
"morning": "Guten Morgen, {name}!",
|
||||
"afternoon": "Guten Tag, {name}!",
|
||||
"evening": "Guten Abend, {name}!",
|
||||
"night": "Gute Nacht, {name}!"
|
||||
},
|
||||
special={
|
||||
"welcome": "Willkommen, {name}!",
|
||||
"greeting": "Grüße, {name}!",
|
||||
"salutation": "Herzliche Grüße, {name}!"
|
||||
}
|
||||
),
|
||||
"italian": GreetingTemplate(
|
||||
language="italian",
|
||||
formal="Buongiorno, {name}!",
|
||||
informal="Ciao, {name}!",
|
||||
casual="Ehi {name}!",
|
||||
time_based={
|
||||
"morning": "Buongiorno, {name}!",
|
||||
"afternoon": "Buon pomeriggio, {name}!",
|
||||
"evening": "Buonasera, {name}!",
|
||||
"night": "Buonanotte, {name}!"
|
||||
},
|
||||
special={
|
||||
"welcome": "Benvenuto, {name}!",
|
||||
"greeting": "Saluti, {name}!",
|
||||
"salutation": "Cordiali saluti, {name}!"
|
||||
}
|
||||
),
|
||||
"japanese": GreetingTemplate(
|
||||
language="japanese",
|
||||
formal="こんにちは、{name}さん!",
|
||||
informal="やあ、{name}!",
|
||||
casual="よー、{name}!",
|
||||
time_based={
|
||||
"morning": "おはようございます、{name}さん!",
|
||||
"afternoon": "こんにちは、{name}さん!",
|
||||
"evening": "こんばんは、{name}さん!",
|
||||
"night": "おやすみなさい、{name}さん!"
|
||||
},
|
||||
special={
|
||||
"welcome": "ようこそ、{name}さん!",
|
||||
"greeting": "ご挨拶、{name}さん!",
|
||||
"salutation": "よろしく、{name}さん!"
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
def _initialize_emoji_map(self) -> Dict[str, str]:
|
||||
"""Initialize emoji map for different languages"""
|
||||
return {
|
||||
"english": "👋",
|
||||
"spanish": "🇪🇸",
|
||||
"french": "🇫🇷",
|
||||
"german": "🇩🇪",
|
||||
"italian": "🇮🇹",
|
||||
"japanese": "🇯🇵"
|
||||
}
|
||||
|
||||
@timer
|
||||
@memoize
|
||||
def generate(self, name: str, language: str = None,
|
||||
style: str = "informal", variation: str = None) -> str:
|
||||
"""Generate a greeting for the given name and language"""
|
||||
# Use default language if not specified
|
||||
language = language or self.config.default_language
|
||||
|
||||
# Validate language
|
||||
if language not in self.templates:
|
||||
raise ValueError(
|
||||
f"Unsupported language: {language}. "
|
||||
f"Supported languages: {list(self.templates.keys())}"
|
||||
)
|
||||
|
||||
template = self.templates[language]
|
||||
|
||||
# Select greeting based on style and variation
|
||||
if variation and variation in template.time_based:
|
||||
greeting = template.time_based[variation]
|
||||
elif variation and variation in template.special:
|
||||
greeting = template.special[variation]
|
||||
elif style == "formal":
|
||||
greeting = template.formal
|
||||
elif style == "casual":
|
||||
greeting = template.casual
|
||||
else:
|
||||
greeting = template.informal
|
||||
|
||||
# Format greeting with name
|
||||
formatted_greeting = greeting.format(name=name)
|
||||
|
||||
# Add emoji if enabled
|
||||
if self.config.enable_emoji and language in self.emoji_map:
|
||||
formatted_greeting = f"{self.emoji_map[language]} {formatted_greeting}"
|
||||
|
||||
return formatted_greeting
|
||||
|
||||
def get_random_greeting(self, name: str, language: str = None) -> str:
|
||||
"""Get a random greeting variation"""
|
||||
language = language or self.config.default_language
|
||||
template = self.templates[language]
|
||||
|
||||
# Collect all available greetings
|
||||
all_greetings = [
|
||||
template.formal,
|
||||
template.informal,
|
||||
template.casual
|
||||
] + list(template.time_based.values()) + list(template.special.values())
|
||||
|
||||
# Select random greeting
|
||||
greeting = random.choice(all_greetings)
|
||||
formatted_greeting = greeting.format(name=name)
|
||||
|
||||
# Add emoji if enabled
|
||||
if self.config.enable_emoji and language in self.emoji_map:
|
||||
formatted_greeting = f"{self.emoji_map[language]} {formatted_greeting}"
|
||||
|
||||
return formatted_greeting
|
||||
|
||||
def get_available_styles(self) -> List[str]:
|
||||
"""Get list of available greeting styles"""
|
||||
return ["formal", "informal", "casual"]
|
||||
|
||||
def get_available_variations(self, language: str = None) -> Dict[str, List[str]]:
|
||||
"""Get available variations for a language"""
|
||||
language = language or self.config.default_language
|
||||
|
||||
if language not in self.templates:
|
||||
return {}
|
||||
|
||||
template = self.templates[language]
|
||||
return {
|
||||
"time_based": list(template.time_based.keys()),
|
||||
"special": list(template.special.keys())
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
"""
|
||||
Message formatter module for Hello World application
|
||||
"""
|
||||
import textwrap
|
||||
from datetime import datetime
|
||||
from typing import Optional, Dict, Any
|
||||
from config import Config
|
||||
from utils.decorators import timer
|
||||
|
||||
|
||||
class MessageFormatter:
|
||||
"""Format messages in various styles"""
|
||||
|
||||
def __init__(self, config: Config):
|
||||
self.config = config
|
||||
self.styles = self._initialize_styles()
|
||||
|
||||
def _initialize_styles(self) -> Dict[str, Any]:
|
||||
"""Initialize formatting styles"""
|
||||
return {
|
||||
"simple": self._format_simple,
|
||||
"fancy": self._format_fancy,
|
||||
"banner": self._format_banner,
|
||||
"ascii": self._format_ascii
|
||||
}
|
||||
|
||||
@timer
|
||||
def format(self, message: str, style: str = None,
|
||||
timestamp: Optional[datetime] = None,
|
||||
additional_info: Optional[Dict[str, Any]] = None) -> str:
|
||||
"""Format a message in the specified style"""
|
||||
style = style or self.config.default_style
|
||||
|
||||
if style not in self.styles:
|
||||
raise ValueError(
|
||||
f"Unsupported style: {style}. "
|
||||
f"Supported styles: {list(self.styles.keys())}"
|
||||
)
|
||||
|
||||
# Apply color if enabled
|
||||
if self.config.enable_colors:
|
||||
message = self._apply_colors(message, style)
|
||||
|
||||
# Format message
|
||||
formatted = self.styles[style](message, timestamp, additional_info)
|
||||
|
||||
# Wrap text if needed
|
||||
if self.config.max_line_length > 0:
|
||||
lines = formatted.split('\n')
|
||||
wrapped_lines = []
|
||||
for line in lines:
|
||||
if len(line) > self.config.max_line_length:
|
||||
wrapped = textwrap.fill(
|
||||
line,
|
||||
width=self.config.max_line_length,
|
||||
break_long_words=False
|
||||
)
|
||||
wrapped_lines.extend(wrapped.split('\n'))
|
||||
else:
|
||||
wrapped_lines.append(line)
|
||||
formatted = '\n'.join(wrapped_lines)
|
||||
|
||||
return formatted
|
||||
|
||||
def _format_simple(self, message: str, timestamp: Optional[datetime],
|
||||
additional_info: Optional[Dict[str, Any]]) -> str:
|
||||
"""Simple format: just the message"""
|
||||
return message
|
||||
|
||||
def _format_fancy(self, message: str, timestamp: Optional[datetime],
|
||||
additional_info: Optional[Dict[str, Any]]) -> str:
|
||||
"""Fancy format with decorations"""
|
||||
lines = []
|
||||
|
||||
# Top border
|
||||
lines.append("╔" + "═" * (len(message) + 2) + "╗")
|
||||
|
||||
# Message
|
||||
lines.append(f"║ {message} ║")
|
||||
|
||||
# Timestamp if provided
|
||||
if timestamp:
|
||||
time_str = timestamp.strftime("%Y-%m-%d %H:%M:%S")
|
||||
lines.append("╠" + "═" * (len(message) + 2) + "╣")
|
||||
lines.append(f"║ {time_str.center(len(message))} ║")
|
||||
|
||||
# Additional info if provided
|
||||
if additional_info:
|
||||
lines.append("╠" + "═" * (len(message) + 2) + "╣")
|
||||
for key, value in additional_info.items():
|
||||
info_line = f"{key}: {value}"
|
||||
lines.append(f"║ {info_line.center(len(message))} ║")
|
||||
|
||||
# Bottom border
|
||||
lines.append("╚" + "═" * (len(message) + 2) + "╝")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def _format_banner(self, message: str, timestamp: Optional[datetime],
|
||||
additional_info: Optional[Dict[str, Any]]) -> str:
|
||||
"""Banner format with ASCII art"""
|
||||
banner_width = max(len(message) + 20, 60)
|
||||
lines = []
|
||||
|
||||
# Top banner
|
||||
lines.append("*" * banner_width)
|
||||
lines.append("*" + " " * (banner_width - 2) + "*")
|
||||
|
||||
# Message centered
|
||||
lines.append("*" + message.center(banner_width - 2) + "*")
|
||||
|
||||
# Timestamp if provided
|
||||
if timestamp:
|
||||
lines.append("*" + " " * (banner_width - 2) + "*")
|
||||
time_str = timestamp.strftime("%Y-%m-%d %H:%M:%S")
|
||||
lines.append("*" + time_str.center(banner_width - 2) + "*")
|
||||
|
||||
# Additional info if provided
|
||||
if additional_info:
|
||||
lines.append("*" + " " * (banner_width - 2) + "*")
|
||||
for key, value in additional_info.items():
|
||||
info_line = f"{key}: {value}"
|
||||
lines.append("*" + info_line.center(banner_width - 2) + "*")
|
||||
|
||||
# Bottom banner
|
||||
lines.append("*" + " " * (banner_width - 2) + "*")
|
||||
lines.append("*" * banner_width)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def _format_ascii(self, message: str, timestamp: Optional[datetime],
|
||||
additional_info: Optional[Dict[str, Any]]) -> str:
|
||||
"""ASCII art format"""
|
||||
lines = []
|
||||
|
||||
# ASCII art header
|
||||
lines.extend([
|
||||
" _ _ _ _ __ __ _ _ _ ",
|
||||
" | | | | | | | \\ \\ / / | | | | |",
|
||||
" | |__| | ___| | | ___ \\ \\ / /__ _ __| | __| | |",
|
||||
" | __ |/ _ \\ | |/ _ \\ \\ \\ / / _ \\| '__| |/ _` | |",
|
||||
" | | | | __/ | | (_) | \\ \\/ / (_) | | | | (_| |_|",
|
||||
" |_| |_|\\___|_|_|\\___/ \\__/ \\___/|_| |_|\\__,_(_)",
|
||||
""
|
||||
])
|
||||
|
||||
# Message
|
||||
lines.append(message.center(57))
|
||||
|
||||
# Timestamp if provided
|
||||
if timestamp:
|
||||
lines.append("")
|
||||
time_str = timestamp.strftime("%Y-%m-%d %H:%M:%S")
|
||||
lines.append(time_str.center(57))
|
||||
|
||||
# Additional info if provided
|
||||
if additional_info:
|
||||
lines.append("")
|
||||
for key, value in additional_info.items():
|
||||
info_line = f"{key}: {value}"
|
||||
lines.append(info_line.center(57))
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def _apply_colors(self, message: str, style: str) -> str:
|
||||
"""Apply ANSI color codes to message"""
|
||||
color_map = {
|
||||
"simple": "\033[0m", # Default
|
||||
"fancy": "\033[1;36m", # Bold Cyan
|
||||
"banner": "\033[1;33m", # Bold Yellow
|
||||
"ascii": "\033[1;35m" # Bold Magenta
|
||||
}
|
||||
|
||||
reset = "\033[0m"
|
||||
color = color_map.get(style, "\033[0m")
|
||||
|
||||
return f"{color}{message}{reset}"
|
||||
|
||||
def create_progress_bar(self, current: int, total: int,
|
||||
width: int = 50, fill_char: str = "█") -> str:
|
||||
"""Create a progress bar"""
|
||||
if total == 0:
|
||||
return "[" + " " * width + "]"
|
||||
|
||||
filled = int(width * current / total)
|
||||
empty = width - filled
|
||||
|
||||
bar = "[" + fill_char * filled + " " * empty + "]"
|
||||
percentage = f" {current}/{total} ({100 * current / total:.1f}%)"
|
||||
|
||||
return bar + percentage
|
||||
|
||||
def create_table(self, headers: list, rows: list) -> str:
|
||||
"""Create a simple ASCII table"""
|
||||
if not headers or not rows:
|
||||
return ""
|
||||
|
||||
# Calculate column widths
|
||||
col_widths = [len(str(h)) for h in headers]
|
||||
for row in rows:
|
||||
for i, cell in enumerate(row):
|
||||
col_widths[i] = max(col_widths[i], len(str(cell)))
|
||||
|
||||
# Create separator
|
||||
separator = "+" + "+".join(["-" * (w + 2) for w in col_widths]) + "+"
|
||||
|
||||
# Format header
|
||||
header_row = "|" + "|".join([
|
||||
f" {str(h).ljust(w)} " for h, w in zip(headers, col_widths)
|
||||
]) + "|"
|
||||
|
||||
# Format rows
|
||||
data_rows = []
|
||||
for row in rows:
|
||||
data_row = "|" + "|".join([
|
||||
f" {str(cell).ljust(w)} "
|
||||
for cell, w in zip(row, col_widths)
|
||||
]) + "|"
|
||||
data_rows.append(data_row)
|
||||
|
||||
# Combine all parts
|
||||
table_parts = [separator, header_row, separator]
|
||||
table_parts.extend(data_rows)
|
||||
table_parts.append(separator)
|
||||
|
||||
return "\n".join(table_parts)
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Complex Hello World Application
|
||||
Main entry point for the application
|
||||
"""
|
||||
import sys
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# Add project root to path
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
|
||||
from config import Config
|
||||
from core.greeting_generator import GreetingGenerator
|
||||
from core.message_formatter import MessageFormatter
|
||||
from utils.logger import Logger
|
||||
from utils.decorators import timer, validate_args
|
||||
|
||||
|
||||
class HelloWorldApp:
|
||||
"""Main application class for Hello World"""
|
||||
|
||||
def __init__(self, config: Config):
|
||||
self.config = config
|
||||
self.logger = Logger(config.log_level)
|
||||
self.greeting_generator = GreetingGenerator(config)
|
||||
self.message_formatter = MessageFormatter(config)
|
||||
|
||||
@timer
|
||||
@validate_args
|
||||
def run(self, name: str = None, language: str = None, style: str = None):
|
||||
"""Run the Hello World application"""
|
||||
self.logger.info("Starting Hello World application")
|
||||
|
||||
# Use provided values or defaults from config
|
||||
name = name or self.config.default_name
|
||||
language = language or self.config.default_language
|
||||
style = style or self.config.default_style
|
||||
|
||||
try:
|
||||
# Generate greeting
|
||||
greeting = self.greeting_generator.generate(name, language)
|
||||
|
||||
# Format message
|
||||
formatted_message = self.message_formatter.format(
|
||||
greeting,
|
||||
style=style,
|
||||
timestamp=datetime.now()
|
||||
)
|
||||
|
||||
# Display message
|
||||
print(formatted_message)
|
||||
|
||||
# Log success
|
||||
self.logger.info(f"Successfully generated greeting for {name} in {language}")
|
||||
|
||||
return formatted_message
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error generating greeting: {str(e)}")
|
||||
raise
|
||||
|
||||
|
||||
def parse_arguments():
|
||||
"""Parse command line arguments"""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Complex Hello World Application",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
python main.py
|
||||
python main.py --name "Alice"
|
||||
python main.py --name "Bob" --language "spanish"
|
||||
python main.py --name "Charlie" --language "french" --style "fancy"
|
||||
python main.py --debug
|
||||
"""
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--name", "-n",
|
||||
type=str,
|
||||
help="Name to greet (default: from config)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--language", "-l",
|
||||
type=str,
|
||||
choices=["english", "spanish", "french", "german", "italian", "japanese"],
|
||||
help="Language for greeting (default: from config)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--style", "-s",
|
||||
type=str,
|
||||
choices=["simple", "fancy", "banner", "ascii"],
|
||||
help="Message style (default: from config)"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--debug", "-d",
|
||||
action="store_true",
|
||||
help="Enable debug logging"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--config", "-c",
|
||||
type=str,
|
||||
help="Path to custom configuration file"
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point"""
|
||||
args = parse_arguments()
|
||||
|
||||
# Load configuration
|
||||
config = Config(args.config)
|
||||
|
||||
# Override log level if debug flag is set
|
||||
if args.debug:
|
||||
config.log_level = "DEBUG"
|
||||
|
||||
# Create and run application
|
||||
app = HelloWorldApp(config)
|
||||
|
||||
try:
|
||||
app.run(
|
||||
name=args.name,
|
||||
language=args.language,
|
||||
style=args.style
|
||||
)
|
||||
sys.exit(0)
|
||||
except Exception as e:
|
||||
print(f"Error: {str(e)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
# Complex Hello World Application Requirements
|
||||
# Python 3.8+
|
||||
|
||||
# Core dependencies (none required for basic functionality)
|
||||
|
||||
# Development dependencies
|
||||
pytest>=7.0.0
|
||||
pytest-cov>=4.0.0
|
||||
black>=22.0.0
|
||||
flake8>=5.0.0
|
||||
mypy>=0.990
|
||||
|
||||
# Optional dependencies for enhanced features
|
||||
colorama>=0.4.6 # Cross-platform colored terminal text
|
||||
python-dotenv>=0.21.0 # Load environment variables from .env file
|
||||
|
||||
# Documentation
|
||||
sphinx>=5.0.0
|
||||
sphinx-rtd-theme>=1.0.0
|
||||
@@ -0,0 +1 @@
|
||||
"""Test package for Hello World application"""
|
||||
@@ -0,0 +1,285 @@
|
||||
"""
|
||||
Unit tests for the Hello World application
|
||||
"""
|
||||
import sys
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
# Add parent directory to path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from config import Config
|
||||
from core.greeting_generator import GreetingGenerator
|
||||
from core.message_formatter import MessageFormatter
|
||||
from utils.logger import Logger
|
||||
from main import HelloWorldApp
|
||||
|
||||
|
||||
class TestConfig:
|
||||
"""Test configuration module"""
|
||||
|
||||
def test_default_config(self):
|
||||
"""Test default configuration values"""
|
||||
config = Config()
|
||||
assert config.default_name == "World"
|
||||
assert config.default_language == "english"
|
||||
assert config.default_style == "simple"
|
||||
assert config.log_level == "INFO"
|
||||
|
||||
def test_config_validation(self):
|
||||
"""Test configuration validation"""
|
||||
config = Config()
|
||||
assert config.validate() is True
|
||||
|
||||
# Test invalid language
|
||||
config.default_language = "klingon"
|
||||
assert config.validate() is False
|
||||
|
||||
|
||||
class TestGreetingGenerator:
|
||||
"""Test greeting generator module"""
|
||||
|
||||
def setup_method(self):
|
||||
"""Set up test fixtures"""
|
||||
self.config = Config()
|
||||
self.generator = GreetingGenerator(self.config)
|
||||
|
||||
def test_english_greeting(self):
|
||||
"""Test English greeting generation"""
|
||||
greeting = self.generator.generate("Alice", "english")
|
||||
assert "Alice" in greeting
|
||||
assert "Hello" in greeting or "Hi" in greeting
|
||||
|
||||
def test_spanish_greeting(self):
|
||||
"""Test Spanish greeting generation"""
|
||||
greeting = self.generator.generate("Carlos", "spanish")
|
||||
assert "Carlos" in greeting
|
||||
assert "Hola" in greeting or "Buenos" in greeting
|
||||
|
||||
def test_french_greeting(self):
|
||||
"""Test French greeting generation"""
|
||||
greeting = self.generator.generate("Marie", "french")
|
||||
assert "Marie" in greeting
|
||||
assert "Bonjour" in greeting or "Salut" in greeting
|
||||
|
||||
def test_formal_greeting(self):
|
||||
"""Test formal greeting style"""
|
||||
greeting = self.generator.generate("Dr. Smith", "english", style="formal")
|
||||
assert "Dr. Smith" in greeting
|
||||
assert "Good day" in greeting
|
||||
|
||||
def test_casual_greeting(self):
|
||||
"""Test casual greeting style"""
|
||||
greeting = self.generator.generate("Bob", "english", style="casual")
|
||||
assert "Bob" in greeting
|
||||
assert "Hey" in greeting
|
||||
|
||||
def test_time_based_greeting(self):
|
||||
"""Test time-based greeting variation"""
|
||||
greeting = self.generator.generate("Alice", "english", variation="morning")
|
||||
assert "Alice" in greeting
|
||||
assert "Good morning" in greeting
|
||||
|
||||
def test_invalid_language(self):
|
||||
"""Test invalid language handling"""
|
||||
with pytest.raises(ValueError):
|
||||
self.generator.generate("Test", "klingon")
|
||||
|
||||
def test_emoji_support(self):
|
||||
"""Test emoji support when enabled"""
|
||||
self.config.enable_emoji = True
|
||||
greeting = self.generator.generate("Test", "english")
|
||||
assert "👋" in greeting
|
||||
|
||||
def test_random_greeting(self):
|
||||
"""Test random greeting generation"""
|
||||
greetings = set()
|
||||
for _ in range(10):
|
||||
greeting = self.generator.get_random_greeting("Test", "english")
|
||||
greetings.add(greeting)
|
||||
|
||||
# Should have at least 2 different greetings
|
||||
assert len(greetings) >= 2
|
||||
|
||||
|
||||
class TestMessageFormatter:
|
||||
"""Test message formatter module"""
|
||||
|
||||
def setup_method(self):
|
||||
"""Set up test fixtures"""
|
||||
self.config = Config()
|
||||
self.formatter = MessageFormatter(self.config)
|
||||
|
||||
def test_simple_format(self):
|
||||
"""Test simple formatting style"""
|
||||
message = "Hello, World!"
|
||||
formatted = self.formatter.format(message, style="simple")
|
||||
assert formatted == message
|
||||
|
||||
def test_fancy_format(self):
|
||||
"""Test fancy formatting style"""
|
||||
message = "Hello, World!"
|
||||
formatted = self.formatter.format(message, style="fancy")
|
||||
assert "╔" in formatted
|
||||
assert "╗" in formatted
|
||||
assert message in formatted
|
||||
|
||||
def test_banner_format(self):
|
||||
"""Test banner formatting style"""
|
||||
message = "Hello, World!"
|
||||
formatted = self.formatter.format(message, style="banner")
|
||||
assert "*" in formatted
|
||||
assert message in formatted
|
||||
lines = formatted.split('\n')
|
||||
assert len(lines) >= 5
|
||||
|
||||
def test_ascii_format(self):
|
||||
"""Test ASCII art formatting style"""
|
||||
message = "Hello, World!"
|
||||
formatted = self.formatter.format(message, style="ascii")
|
||||
assert message in formatted
|
||||
assert "_ _" in formatted # Part of ASCII art
|
||||
|
||||
def test_format_with_timestamp(self):
|
||||
"""Test formatting with timestamp"""
|
||||
message = "Hello, World!"
|
||||
timestamp = datetime.now()
|
||||
formatted = self.formatter.format(
|
||||
message,
|
||||
style="fancy",
|
||||
timestamp=timestamp
|
||||
)
|
||||
assert message in formatted
|
||||
assert timestamp.strftime("%Y-%m-%d") in formatted
|
||||
|
||||
def test_invalid_style(self):
|
||||
"""Test invalid style handling"""
|
||||
with pytest.raises(ValueError):
|
||||
self.formatter.format("Test", style="invalid")
|
||||
|
||||
def test_progress_bar(self):
|
||||
"""Test progress bar creation"""
|
||||
progress = self.formatter.create_progress_bar(50, 100)
|
||||
assert "[" in progress
|
||||
assert "]" in progress
|
||||
assert "50.0%" in progress
|
||||
|
||||
def test_table_creation(self):
|
||||
"""Test table creation"""
|
||||
headers = ["Name", "Language", "Style"]
|
||||
rows = [
|
||||
["Alice", "English", "Formal"],
|
||||
["Bob", "Spanish", "Casual"]
|
||||
]
|
||||
table = self.formatter.create_table(headers, rows)
|
||||
assert "Name" in table
|
||||
assert "Alice" in table
|
||||
assert "+" in table
|
||||
assert "|" in table
|
||||
|
||||
|
||||
class TestHelloWorldApp:
|
||||
"""Test main application"""
|
||||
|
||||
def setup_method(self):
|
||||
"""Set up test fixtures"""
|
||||
self.config = Config()
|
||||
self.app = HelloWorldApp(self.config)
|
||||
|
||||
def test_app_initialization(self):
|
||||
"""Test app initialization"""
|
||||
assert self.app.config is not None
|
||||
assert self.app.logger is not None
|
||||
assert self.app.greeting_generator is not None
|
||||
assert self.app.message_formatter is not None
|
||||
|
||||
def test_run_default(self):
|
||||
"""Test running app with defaults"""
|
||||
result = self.app.run()
|
||||
assert result is not None
|
||||
assert "World" in result
|
||||
|
||||
def test_run_with_name(self):
|
||||
"""Test running app with custom name"""
|
||||
result = self.app.run(name="Alice")
|
||||
assert "Alice" in result
|
||||
|
||||
def test_run_with_language(self):
|
||||
"""Test running app with custom language"""
|
||||
result = self.app.run(name="Carlos", language="spanish")
|
||||
assert "Carlos" in result
|
||||
|
||||
def test_run_with_style(self):
|
||||
"""Test running app with custom style"""
|
||||
result = self.app.run(name="Test", style="banner")
|
||||
assert "Test" in result
|
||||
assert "*" in result # Banner style marker
|
||||
|
||||
|
||||
class TestDecorators:
|
||||
"""Test utility decorators"""
|
||||
|
||||
def test_timer_decorator(self):
|
||||
"""Test timer decorator functionality"""
|
||||
from utils.decorators import timer
|
||||
|
||||
@timer
|
||||
def slow_function():
|
||||
import time
|
||||
time.sleep(0.1)
|
||||
return "done"
|
||||
|
||||
result = slow_function()
|
||||
assert result == "done"
|
||||
|
||||
def test_validate_args_decorator(self):
|
||||
"""Test validate_args decorator"""
|
||||
from utils.decorators import validate_args
|
||||
|
||||
@validate_args
|
||||
def test_function(self, name=None):
|
||||
return f"Hello, {name}!"
|
||||
|
||||
# Valid call
|
||||
result = test_function(None, name="Alice")
|
||||
assert result == "Hello, Alice!"
|
||||
|
||||
# Invalid name type
|
||||
with pytest.raises(TypeError):
|
||||
test_function(None, name=123)
|
||||
|
||||
# Name too long
|
||||
with pytest.raises(ValueError):
|
||||
test_function(None, name="A" * 51)
|
||||
|
||||
def test_memoize_decorator(self):
|
||||
"""Test memoize decorator"""
|
||||
from utils.decorators import memoize
|
||||
|
||||
call_count = 0
|
||||
|
||||
@memoize
|
||||
def expensive_function(x):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
return x * 2
|
||||
|
||||
# First call
|
||||
result1 = expensive_function(5)
|
||||
assert result1 == 10
|
||||
assert call_count == 1
|
||||
|
||||
# Second call with same argument (should use cache)
|
||||
result2 = expensive_function(5)
|
||||
assert result2 == 10
|
||||
assert call_count == 1 # Should not increment
|
||||
|
||||
# Call with different argument
|
||||
result3 = expensive_function(10)
|
||||
assert result3 == 20
|
||||
assert call_count == 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Utils package for Hello World application"""
|
||||
from .logger import Logger, get_logger
|
||||
from .decorators import timer, validate_args, retry, memoize, singleton, deprecated
|
||||
|
||||
__all__ = [
|
||||
'Logger',
|
||||
'get_logger',
|
||||
'timer',
|
||||
'validate_args',
|
||||
'retry',
|
||||
'memoize',
|
||||
'singleton',
|
||||
'deprecated'
|
||||
]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
Utility decorators for Hello World application
|
||||
"""
|
||||
import functools
|
||||
import time
|
||||
from typing import Callable, Any
|
||||
from utils.logger import get_logger
|
||||
|
||||
|
||||
def timer(func: Callable) -> Callable:
|
||||
"""Decorator to measure function execution time"""
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
logger = get_logger()
|
||||
start_time = time.time()
|
||||
|
||||
logger.debug(f"Starting {func.__name__}...")
|
||||
result = func(*args, **kwargs)
|
||||
|
||||
end_time = time.time()
|
||||
execution_time = end_time - start_time
|
||||
|
||||
logger.debug(
|
||||
f"Completed {func.__name__} in {execution_time:.4f} seconds"
|
||||
)
|
||||
|
||||
return result
|
||||
return wrapper
|
||||
|
||||
|
||||
def validate_args(func: Callable) -> Callable:
|
||||
"""Decorator to validate function arguments"""
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
logger = get_logger()
|
||||
|
||||
# Log function call with arguments
|
||||
logger.debug(
|
||||
f"Calling {func.__name__} with args={args[1:]} kwargs={kwargs}"
|
||||
)
|
||||
|
||||
# Basic validation example
|
||||
if 'name' in kwargs and kwargs['name']:
|
||||
if not isinstance(kwargs['name'], str):
|
||||
raise TypeError(f"Name must be a string, got {type(kwargs['name'])}")
|
||||
if len(kwargs['name']) > 50:
|
||||
raise ValueError("Name must be 50 characters or less")
|
||||
|
||||
return func(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, delay: float = 1.0):
|
||||
"""Decorator to retry function on failure"""
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
logger = get_logger()
|
||||
attempts = 0
|
||||
last_error = None
|
||||
|
||||
while attempts < max_attempts:
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
attempts += 1
|
||||
last_error = e
|
||||
|
||||
if attempts < max_attempts:
|
||||
logger.warning(
|
||||
f"Attempt {attempts} failed for {func.__name__}: {str(e)}. "
|
||||
f"Retrying in {delay} seconds..."
|
||||
)
|
||||
time.sleep(delay)
|
||||
else:
|
||||
logger.error(
|
||||
f"All {max_attempts} attempts failed for {func.__name__}"
|
||||
)
|
||||
|
||||
raise last_error
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
def memoize(func: Callable) -> Callable:
|
||||
"""Decorator to cache function results"""
|
||||
cache = {}
|
||||
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
# Create a cache key from arguments
|
||||
cache_key = str(args) + str(sorted(kwargs.items()))
|
||||
|
||||
if cache_key not in cache:
|
||||
cache[cache_key] = func(*args, **kwargs)
|
||||
|
||||
return cache[cache_key]
|
||||
|
||||
# Add method to clear cache
|
||||
wrapper.clear_cache = lambda: cache.clear()
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def singleton(cls):
|
||||
"""Decorator to make a class a singleton"""
|
||||
instances = {}
|
||||
|
||||
@functools.wraps(cls)
|
||||
def get_instance(*args, **kwargs):
|
||||
if cls not in instances:
|
||||
instances[cls] = cls(*args, **kwargs)
|
||||
return instances[cls]
|
||||
|
||||
return get_instance
|
||||
|
||||
|
||||
def deprecated(message: str = ""):
|
||||
"""Decorator to mark functions as deprecated"""
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
logger = get_logger()
|
||||
warning_msg = f"{func.__name__} is deprecated"
|
||||
if message:
|
||||
warning_msg += f": {message}"
|
||||
logger.warning(warning_msg)
|
||||
return func(*args, **kwargs)
|
||||
return wrapper
|
||||
return decorator
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
Logger module for Hello World application
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class ColoredFormatter(logging.Formatter):
|
||||
"""Custom formatter with color support"""
|
||||
|
||||
COLORS = {
|
||||
'DEBUG': '\033[36m', # Cyan
|
||||
'INFO': '\033[32m', # Green
|
||||
'WARNING': '\033[33m', # Yellow
|
||||
'ERROR': '\033[31m', # Red
|
||||
'CRITICAL': '\033[35m', # Magenta
|
||||
}
|
||||
RESET = '\033[0m'
|
||||
|
||||
def __init__(self, fmt: str = None, enable_colors: bool = True):
|
||||
super().__init__(fmt)
|
||||
self.enable_colors = enable_colors
|
||||
|
||||
def format(self, record):
|
||||
if self.enable_colors and record.levelname in self.COLORS:
|
||||
record.levelname = (
|
||||
f"{self.COLORS[record.levelname]}"
|
||||
f"{record.levelname}"
|
||||
f"{self.RESET}"
|
||||
)
|
||||
return super().format(record)
|
||||
|
||||
|
||||
class Logger:
|
||||
"""Custom logger class for Hello World application"""
|
||||
|
||||
def __init__(self, level: str = "INFO", log_file: Optional[str] = None):
|
||||
self.logger = logging.getLogger("HelloWorld")
|
||||
self.logger.setLevel(getattr(logging, level.upper()))
|
||||
|
||||
# Remove existing handlers
|
||||
self.logger.handlers.clear()
|
||||
|
||||
# Console handler
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_formatter = ColoredFormatter(
|
||||
fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
enable_colors=sys.stdout.isatty()
|
||||
)
|
||||
console_handler.setFormatter(console_formatter)
|
||||
self.logger.addHandler(console_handler)
|
||||
|
||||
# File handler (optional)
|
||||
if log_file:
|
||||
file_handler = logging.FileHandler(log_file)
|
||||
file_formatter = logging.Formatter(
|
||||
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
file_handler.setFormatter(file_formatter)
|
||||
self.logger.addHandler(file_handler)
|
||||
|
||||
def debug(self, message: str, *args, **kwargs):
|
||||
"""Log debug message"""
|
||||
self.logger.debug(message, *args, **kwargs)
|
||||
|
||||
def info(self, message: str, *args, **kwargs):
|
||||
"""Log info message"""
|
||||
self.logger.info(message, *args, **kwargs)
|
||||
|
||||
def warning(self, message: str, *args, **kwargs):
|
||||
"""Log warning message"""
|
||||
self.logger.warning(message, *args, **kwargs)
|
||||
|
||||
def error(self, message: str, *args, **kwargs):
|
||||
"""Log error message"""
|
||||
self.logger.error(message, *args, **kwargs)
|
||||
|
||||
def critical(self, message: str, *args, **kwargs):
|
||||
"""Log critical message"""
|
||||
self.logger.critical(message, *args, **kwargs)
|
||||
|
||||
def log_separator(self, char: str = "-", length: int = 50):
|
||||
"""Log a separator line"""
|
||||
self.info(char * length)
|
||||
|
||||
def log_banner(self, message: str, char: str = "="):
|
||||
"""Log a banner message"""
|
||||
padding = 2
|
||||
banner_length = len(message) + (padding * 2)
|
||||
|
||||
self.info(char * banner_length)
|
||||
self.info(f"{char}{' ' * padding}{message}{' ' * padding}{char}")
|
||||
self.info(char * banner_length)
|
||||
|
||||
|
||||
# Singleton logger instance
|
||||
_logger_instance = None
|
||||
|
||||
|
||||
def get_logger(level: str = "INFO", log_file: Optional[str] = None) -> Logger:
|
||||
"""Get or create logger instance"""
|
||||
global _logger_instance
|
||||
if _logger_instance is None:
|
||||
_logger_instance = Logger(level, log_file)
|
||||
return _logger_instance
|
||||
Reference in new issue
Block a user