refactor: simplify Component architecture and move shared logic to base class

* Component Base Class:
  * Add constructor parameter for component subdirectory
  * Move file discovery utilities to base class to avoid repetition in subclasses
  * Same for validate_prerequisites, get_files_to_install, get_settings_modifications methods
  * Split install method into _install and _post_install for better separation of concerns
  * Add error handling wrapper around _install method

* All Component Subclasses:
  * Remove duplicate code now handled by base class
  * Use shared file discovery and installation logic
  * Simplify metadata updates using base class methods
  * Leverage base class file handling and validation

* Hooks Component:
  * Fix the logic for handling both placeholder and actual hooks scenarios

* MCP Component:
  * Fix npm package names and installation commands
This commit is contained in:
Andrew Low
2025-07-22 18:27:34 +08:00
parent fff47ec1b7
commit f7311bf480
5 changed files with 491 additions and 714 deletions

View File

@@ -2,25 +2,18 @@
Hooks component for Claude Code hooks integration (future-ready)
"""
from typing import Dict, List, Tuple, Any
from typing import Dict, List, Tuple, Optional, Any
from pathlib import Path
from ..base.component import Component
from ..core.file_manager import FileManager
from ..core.settings_manager import SettingsManager
from ..utils.security import SecurityValidator
from ..utils.logger import get_logger
class HooksComponent(Component):
"""Claude Code hooks integration component"""
def __init__(self, install_dir: Path = None):
def __init__(self, install_dir: Optional[Path] = None):
"""Initialize hooks component"""
super().__init__(install_dir)
self.logger = get_logger()
self.file_manager = FileManager()
self.settings_manager = SettingsManager(self.install_dir)
super().__init__(install_dir, Path("hooks"))
# Define hook files to install (when hooks are ready)
self.hook_files = [
@@ -39,59 +32,16 @@ class HooksComponent(Component):
"description": "Claude Code hooks integration (future-ready)",
"category": "integration"
}
def validate_prerequisites(self) -> Tuple[bool, List[str]]:
"""Check prerequisites"""
errors = []
# Check if source directory exists (when hooks are implemented)
source_dir = self._get_source_dir()
if not source_dir.exists():
# This is expected for now - hooks are future-ready
self.logger.debug(f"Hooks source directory not found: {source_dir} (expected for future implementation)")
# Check write permissions to install directory
hooks_dir = self.install_dir / "hooks"
has_perms, missing = SecurityValidator.check_permissions(
self.install_dir, {'write'}
)
if not has_perms:
errors.append(f"No write permissions to {self.install_dir}: {missing}")
# Validate installation target
is_safe, validation_errors = SecurityValidator.validate_installation_target(hooks_dir)
if not is_safe:
errors.extend(validation_errors)
return len(errors) == 0, errors
def get_files_to_install(self) -> List[Tuple[Path, Path]]:
"""Get files to install"""
source_dir = self._get_source_dir()
files = []
# Only include files that actually exist
for filename in self.hook_files:
source = source_dir / filename
if source.exists():
target = self.install_dir / "hooks" / filename
files.append((source, target))
return files
def get_settings_modifications(self) -> Dict[str, Any]:
"""Get settings modifications"""
hooks_dir = self.install_dir / "hooks"
def get_metadata_modifications(self) -> Dict[str, Any]:
# Build hooks configuration based on available files
hook_config = {}
for filename in self.hook_files:
hook_path = hooks_dir / filename
hook_path = self.install_component_subdir / filename
if hook_path.exists():
hook_name = filename.replace('.py', '')
hook_config[hook_name] = [str(hook_path)]
settings_mods = {
metadata_mods = {
"components": {
"hooks": {
"version": "3.0.0",
@@ -103,31 +53,31 @@ class HooksComponent(Component):
# Only add hooks configuration if we have actual hook files
if hook_config:
settings_mods["hooks"] = {
metadata_mods["hooks"] = {
"enabled": True,
**hook_config
}
return settings_mods
def install(self, config: Dict[str, Any]) -> bool:
return metadata_mods
def _install(self, config: Dict[str, Any]) -> bool:
"""Install hooks component"""
try:
self.logger.info("Installing SuperClaude hooks component...")
self.logger.info("Installing SuperClaude hooks component...")
# This component is future-ready - hooks aren't implemented yet
source_dir = self._get_source_dir()
if not source_dir.exists() or (source_dir / "PLACEHOLDER.py").exists :
self.logger.info("Hooks are not yet implemented - installing placeholder component")
# This component is future-ready - hooks aren't implemented yet
source_dir = self._get_source_dir()
if not source_dir.exists():
self.logger.info("Hooks are not yet implemented - installing placeholder component")
# Create placeholder hooks directory
hooks_dir = self.install_dir / "hooks"
if not self.file_manager.ensure_directory(hooks_dir):
self.logger.error(f"Could not create hooks directory: {hooks_dir}")
return False
# Create placeholder file
placeholder_content = '''"""
# Create placeholder hooks directory
if not self.file_manager.ensure_directory(self.install_component_subdir):
self.logger.error(f"Could not create hooks directory: {self.install_component_subdir}")
return False
# Create placeholder file
placeholder_content = '''"""
SuperClaude Hooks - Future Implementation
This directory is reserved for Claude Code hooks integration.
@@ -145,101 +95,95 @@ For more information, see SuperClaude documentation.
# Placeholder for future hooks implementation
def placeholder_hook():
"""Placeholder hook function"""
pass
"""Placeholder hook function"""
pass
'''
placeholder_path = hooks_dir / "PLACEHOLDER.py"
try:
with open(placeholder_path, 'w') as f:
f.write(placeholder_content)
self.logger.debug("Created hooks placeholder file")
except Exception as e:
self.logger.warning(f"Could not create placeholder file: {e}")
# Update settings with placeholder registration
try:
settings_mods = {
"components": {
"hooks": {
"version": "3.0.0",
"installed": True,
"status": "placeholder",
"files_count": 0
}
placeholder_path = self.install_component_subdir / "PLACEHOLDER.py"
try:
with open(placeholder_path, 'w') as f:
f.write(placeholder_content)
self.logger.debug("Created hooks placeholder file")
except Exception as e:
self.logger.warning(f"Could not create placeholder file: {e}")
# Update settings with placeholder registration
try:
metadata_mods = {
"components": {
"hooks": {
"version": "3.0.0",
"installed": True,
"status": "placeholder",
"files_count": 0
}
}
self.settings_manager.update_settings(settings_mods)
self.logger.info("Updated settings.json with hooks component registration")
except Exception as e:
self.logger.error(f"Failed to update settings.json: {e}")
return False
self.logger.success("Hooks component installed successfully (placeholder)")
return True
# If hooks source directory exists, install actual hooks
self.logger.info("Installing actual hook files...")
# Validate installation
success, errors = self.validate_prerequisites()
if not success:
for error in errors:
self.logger.error(error)
return False
# Get files to install
files_to_install = self.get_files_to_install()
if not files_to_install:
self.logger.warning("No hook files found to install")
return False
# Validate all files for security
hooks_dir = self.install_dir / "hooks"
is_safe, security_errors = SecurityValidator.validate_component_files(
files_to_install, source_dir, hooks_dir
)
if not is_safe:
for error in security_errors:
self.logger.error(f"Security validation failed: {error}")
return False
# Ensure hooks directory exists
if not self.file_manager.ensure_directory(hooks_dir):
self.logger.error(f"Could not create hooks directory: {hooks_dir}")
return False
# Copy hook files
success_count = 0
for source, target in files_to_install:
self.logger.debug(f"Copying {source.name} to {target}")
if self.file_manager.copy_file(source, target):
success_count += 1
self.logger.debug(f"Successfully copied {source.name}")
else:
self.logger.error(f"Failed to copy {source.name}")
if success_count != len(files_to_install):
self.logger.error(f"Only {success_count}/{len(files_to_install)} hook files copied successfully")
return False
# Update settings.json
try:
settings_mods = self.get_settings_modifications()
self.settings_manager.update_settings(settings_mods)
self.logger.info("Updated settings.json with hooks configuration")
}
self.settings_manager.update_metadata(metadata_mods)
self.logger.info("Updated metadata with hooks component registration")
except Exception as e:
self.logger.error(f"Failed to update settings.json: {e}")
self.logger.error(f"Failed to update metadata for hooks component: {e}")
return False
self.logger.success(f"Hooks component installed successfully ({success_count} hook files)")
self.logger.success("Hooks component installed successfully (placeholder)")
return True
except Exception as e:
self.logger.exception(f"Unexpected error during hooks installation: {e}")
# If hooks source directory exists, install actual hooks
self.logger.info("Installing actual hook files...")
# Validate installation
success, errors = self.validate_prerequisites(Path("hooks"))
if not success:
for error in errors:
self.logger.error(error)
return False
# Get files to install
files_to_install = self.get_files_to_install()
if not files_to_install:
self.logger.warning("No hook files found to install")
return False
# Copy hook files
success_count = 0
for source, target in files_to_install:
self.logger.debug(f"Copying {source.name} to {target}")
if self.file_manager.copy_file(source, target):
success_count += 1
self.logger.debug(f"Successfully copied {source.name}")
else:
self.logger.error(f"Failed to copy {source.name}")
if success_count != len(files_to_install):
self.logger.error(f"Only {success_count}/{len(files_to_install)} hook files copied successfully")
return False
self.logger.success(f"Hooks component installed successfully ({success_count} hook files)")
return self._post_install()
def _post_install(self):
# Update metadata
try:
metadata_mods = self.get_metadata_modifications()
self.settings_manager.update_metadata(metadata_mods)
self.logger.info("Updated metadata with hooks configuration")
# Add hook registration to metadata
self.settings_manager.add_component_registration("hooks", {
"version": "3.0.0",
"category": "commands",
"files_count": len(self.hook_files)
})
self.logger.info("Updated metadata with commands component registration")
except Exception as e:
self.logger.error(f"Failed to update metadata: {e}")
return False
return True
def uninstall(self) -> bool:
"""Uninstall hooks component"""
@@ -247,28 +191,27 @@ def placeholder_hook():
self.logger.info("Uninstalling SuperClaude hooks component...")
# Remove hook files and placeholder
hooks_dir = self.install_dir / "hooks"
removed_count = 0
# Remove actual hook files
for filename in self.hook_files:
file_path = hooks_dir / filename
file_path = self.install_component_subdir / filename
if self.file_manager.remove_file(file_path):
removed_count += 1
self.logger.debug(f"Removed {filename}")
# Remove placeholder file
placeholder_path = hooks_dir / "PLACEHOLDER.py"
placeholder_path = self.install_component_subdir / "PLACEHOLDER.py"
if self.file_manager.remove_file(placeholder_path):
removed_count += 1
self.logger.debug("Removed hooks placeholder")
# Remove hooks directory if empty
try:
if hooks_dir.exists():
remaining_files = list(hooks_dir.iterdir())
if self.install_component_subdir.exists():
remaining_files = list(self.install_component_subdir.iterdir())
if not remaining_files:
hooks_dir.rmdir()
self.install_component_subdir.rmdir()
self.logger.debug("Removed empty hooks directory")
except Exception as e:
self.logger.warning(f"Could not remove hooks directory: {e}")
@@ -315,12 +258,11 @@ def placeholder_hook():
self.logger.info(f"Updating hooks component from {current_version} to {target_version}")
# Create backup of existing hook files
hooks_dir = self.install_dir / "hooks"
backup_files = []
if hooks_dir.exists():
if self.install_component_subdir.exists():
for filename in self.hook_files + ["PLACEHOLDER.py"]:
file_path = hooks_dir / filename
file_path = self.install_component_subdir / filename
if file_path.exists():
backup_path = self.file_manager.backup_file(file_path)
if backup_path:
@@ -361,8 +303,7 @@ def placeholder_hook():
errors = []
# Check if hooks directory exists
hooks_dir = self.install_dir / "hooks"
if not hooks_dir.exists():
if not self.install_component_subdir.exists():
errors.append("Hooks directory not found")
return False, errors
@@ -377,8 +318,8 @@ def placeholder_hook():
errors.append(f"Version mismatch: installed {installed_version}, expected {expected_version}")
# Check if we have either actual hooks or placeholder
has_placeholder = (hooks_dir / "PLACEHOLDER.py").exists()
has_actual_hooks = any((hooks_dir / filename).exists() for filename in self.hook_files)
has_placeholder = (self.install_component_subdir / "PLACEHOLDER.py").exists()
has_actual_hooks = any((self.install_component_subdir / filename).exists() for filename in self.hook_files)
if not has_placeholder and not has_actual_hooks:
errors.append("No hook files or placeholder found")
@@ -422,4 +363,4 @@ def placeholder_hook():
"estimated_size": self.get_size_estimate(),
"install_directory": str(self.install_dir / "hooks"),
"dependencies": self.get_dependencies()
}
}