Initial commit

This commit is contained in:
2025-04-09 09:34:15 +02:00
commit c19fb93ec5
47 changed files with 5174 additions and 0 deletions
+324
View File
@@ -0,0 +1,324 @@
# Code Structure
This document provides a detailed overview of Edison's code organization and file structure.
## Directory Structure
```
edison/
├── __init__.py # Package initialization
├── __main__.py # Entry point for module execution
├── cli.py # Command-line interface
├── edison.prompt # Prompt template for command generation
├── edison.yaml # Default configuration file
├── config/ # Configuration management
│ ├── __init__.py
│ └── config_manager.py
├── core/ # Core business logic
│ ├── __init__.py
│ ├── api_client.py # OpenAI API integration
│ ├── command_executor.py # Command execution
│ └── prompt_manager.py # Prompt handling
├── logs/ # Log files directory
├── ui/ # User interface components
│ ├── __init__.py
│ ├── console.py # Console output formatting
│ └── interactive.py # Interactive shell mode
└── utils/ # Utility functions
├── __init__.py
├── logging_utils.py # Logging configuration
├── os_utils.py # OS-specific utilities
└── validation.py # Command validation
```
## Key Files and Their Functions
```mermaid
classDiagram
cli <|-- config_manager
cli <|-- api_client
cli <|-- console
cli <|-- interactive
api_client <|-- prompt_manager
interactive <|-- api_client
interactive <|-- command_executor
class cli {
+main()
+parse_arguments()
}
class config_manager {
+load_config()
+print_config()
}
class api_client {
+create_client()
+generate_command()
+call_api()
+get_api_key()
}
class prompt_manager {
+get_full_prompt()
+load_prompt_template()
}
class command_executor {
+execute_command()
}
class console {
+print_command()
+prompt_user_input()
+handle_command_execution()
+handle_user_input()
}
class interactive {
+interactive_mode()
+get_command_explanation()
+show_help()
}
class logging_utils {
+setup_logging()
+get_logger()
}
class os_utils {
+get_default_shell()
+missing_posix_display()
}
class validation {
+check_for_issue()
+check_for_markdown()
+is_dangerous_command()
}
```
### Core Modules
#### cli.py
The main entry point and command-line interface for Edison:
- Parses command-line arguments
- Initializes logging
- Loads configuration
- Handles user interaction flow
- Manages error handling
```python
def main():
"""Main entry point for the application."""
# Parse arguments, set up logging, load config, etc.
def parse_arguments():
"""Parse command line arguments."""
# Define and parse command-line arguments
```
#### config/config_manager.py
Handles configuration loading and management:
- Loads settings from edison.yaml
- Provides default values
- Validates configuration
```python
def load_config():
"""Load configuration from the YAML file."""
# Find and load the configuration file
def print_config(config):
"""Print the current configuration."""
# Display configuration settings
```
#### core/api_client.py
Manages interaction with the OpenAI API:
- Creates and initializes the API client
- Handles API key management
- Formats queries and processes responses
- Implements retry logic
- Supports both streaming and non-streaming command generation
```python
def create_client(config):
"""Create and initialize an OpenAI client."""
# Initialize API client with key
def generate_command(client, config, query, max_retries=3):
"""Generate a command using the OpenAI API with retry logic."""
# Send query to API and handle response
def generate_command_streaming(client, config, query, callback):
"""Generate a command using the OpenAI API with streaming output.
Args:
client: The OpenAI client
config: The configuration dictionary
query: The user query
callback: Function to call with each token
"""
# Stream response tokens and call the callback for each one
```
#### core/command_executor.py
Executes shell commands:
- Runs commands in the appropriate shell
- Handles command output and errors
- Implements safety checks
```python
def execute_command(shell, command):
"""Execute a shell command."""
# Run command and handle result
```
#### core/prompt_manager.py
Manages prompt templates and formatting:
- Loads prompt templates
- Formats user queries for optimal results
- Adapts prompts based on shell and OS
```python
def get_full_prompt(query, shell="bash"):
"""Get the full prompt for the given query and shell."""
# Format prompt with query and shell info
```
### UI Modules
#### ui/console.py
Handles console output and user interaction:
- Formats and displays text
- Presents command options
- Handles user input
- Supports direct command modification
- Controls display of generating prefix
```python
def print_command(command, show_generating_prefix=True):
"""Print a command to the console."""
# Display command with formatting, optionally showing the generating prefix
def handle_command_execution(client, config, command, explain=False):
"""Handle the execution of a command."""
# Manage command execution flow
def handle_direct_modification(command):
"""Handle direct modification of a command.
Args:
command: The command to modify
Returns:
The modified command
"""
# Present interactive editor for direct command modification
```
#### ui/interactive.py
Provides an interactive shell mode:
- Manages continuous interaction
- Handles command history
- Processes special commands
```python
def interactive_mode(client, config):
"""Start an interactive shell."""
# Run interactive loop
def get_command_explanation(client, command):
"""Get an explanation for a command."""
# Generate explanation
```
### Utility Modules
#### utils/logging_utils.py
Configures and manages logging:
- Sets up log files and formats
- Controls log levels
- Provides access to loggers
```python
def setup_logging(verbose=False):
"""Configure logging for the application."""
# Set up logging with appropriate levels
```
#### utils/os_utils.py
Provides OS-specific functionality:
- Detects platform information
- Manages environment-specific behavior
- Determines default shell
```python
def get_default_shell():
"""Get the default shell for the current OS."""
# Determine system shell
```
#### utils/validation.py
Validates and checks commands:
- Detects potentially dangerous commands
- Checks for markdown formatting
- Identifies command issues
```python
def is_dangerous_command(command):
"""Check if a command is potentially dangerous."""
# Analyze command for dangerous patterns
```
## Static Files
- **edison.prompt**: Template for generating prompts sent to the OpenAI API
- **edison.yaml**: Default configuration file with settings
## Dependencies and Imports
The project uses these key dependencies:
1. **Core Python Libraries**:
- `argparse`: For command-line argument parsing
- `logging`: For log management
- `subprocess`: For command execution
- `os`, `sys`: For system interaction
2. **External Libraries**:
- `openai`: For API interaction
- `termcolor`: For colored terminal output
- `python-dotenv`: For environment variable loading
- `pyyaml`: For configuration parsing
- `pyperclip`: For clipboard operations
- `prompt_toolkit`: For interactive shell functionality
- `colorama`: For cross-platform color support
## Code Style and Conventions
Edison follows these coding conventions:
1. **PEP 8**: Standard Python style guide
2. **Docstrings**: All functions and classes have docstrings in the Google style
3. **Error Handling**: Comprehensive try/except blocks with detailed logging
4. **Modularity**: Functions and classes have single responsibilities
5. **Type Hints**: Not currently used but planned for future versions
## Special Considerations
1. **Cross-Platform Support**: Code includes handling for different operating systems
2. **API Key Security**: Multiple secure methods for handling API keys
3. **Command Safety**: Validation to prevent dangerous command execution