summaryrefslogtreecommitdiff
path: root/tools/ng/core.py
blob: c1960862d8a672268776a6dd02d90b808f99d210 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# -*- coding: utf-8 -*-
"""
Core module for RT-Thread build system.

This module provides the central BuildContext class that manages the build state
and coordinates between different components.
"""

import os
import logging
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field

from .config import ConfigManager
from .project import ProjectRegistry
from .toolchain import ToolchainManager
from .generator import GeneratorRegistry
from .utils import PathService


class BuildContext:
    """
    Central build context that manages all build-related state.
    
    This class replaces the global variables in building.py with a proper
    object-oriented design while maintaining compatibility.
    """
    
    # Class variable to store the current context (for backward compatibility)
    _current_context: Optional['BuildContext'] = None
    
    def __init__(self, root_directory: str):
        """
        Initialize build context.
        
        Args:
            root_directory: RT-Thread root directory path
        """
        self.root_directory = os.path.abspath(root_directory)
        self.bsp_directory = os.getcwd()
        
        # Initialize managers
        self.config_manager = ConfigManager()
        self.project_registry = ProjectRegistry()
        self.toolchain_manager = ToolchainManager()
        self.generator_registry = GeneratorRegistry()
        self.path_service = PathService(self.bsp_directory)
        
        # Build environment
        self.environment = None
        self.build_options = {}
        
        # Logging
        self.logger = self._setup_logger()
        
        # Set as current context
        BuildContext._current_context = self
        
    @classmethod
    def get_current(cls) -> Optional['BuildContext']:
        """Get the current build context."""
        return cls._current_context
        
    @classmethod
    def set_current(cls, context: Optional['BuildContext']) -> None:
        """Set the current build context."""
        cls._current_context = context
        
    def _setup_logger(self) -> logging.Logger:
        """Setup logger for build system."""
        logger = logging.getLogger('rtthread.build')
        if not logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter('[%(levelname)s] %(message)s')
            handler.setFormatter(formatter)
            logger.addHandler(handler)
            logger.setLevel(logging.INFO)
        return logger
        
    def prepare_environment(self, env) -> None:
        """
        Prepare the build environment.
        
        Args:
            env: SCons Environment object
        """
        self.environment = env
        
        # Set environment variables
        env['RTT_ROOT'] = self.root_directory
        env['BSP_ROOT'] = self.bsp_directory
        
        # Add to Python path
        import sys
        tools_path = os.path.join(self.root_directory, 'tools')
        if tools_path not in sys.path:
            sys.path.insert(0, tools_path)
            
        self.logger.debug(f"Prepared environment with RTT_ROOT={self.root_directory}")
        
    def load_configuration(self, config_file: str = 'rtconfig.h') -> None:
        """
        Load configuration from rtconfig.h.
        
        Args:
            config_file: Path to configuration file
        """
        config_path = os.path.join(self.bsp_directory, config_file)
        if os.path.exists(config_path):
            self.config_manager.load_from_file(config_path)
            self.build_options = self.config_manager.get_all_options()
            self.logger.info(f"Loaded configuration from {config_file}")
        else:
            self.logger.warning(f"Configuration file {config_file} not found")
            
    def get_dependency(self, depend: Any) -> bool:
        """
        Check if dependency is satisfied.
        
        Args:
            depend: Dependency name or list of names
            
        Returns:
            True if dependency is satisfied
        """
        return self.config_manager.get_dependency(depend)
        
    def register_project_group(self, group) -> None:
        """
        Register a project group.
        
        Args:
            group: ProjectGroup instance
        """
        self.project_registry.register_group(group)
        
    def merge_groups(self) -> List:
        """
        Merge all registered project groups.
        
        Returns:
            List of build objects
        """
        return self.project_registry.merge_groups(self.environment)


@dataclass
class BuildOptions:
    """Build options container."""
    verbose: bool = False
    strict: bool = False
    target: Optional[str] = None
    jobs: int = 1
    clean: bool = False
    
    
@dataclass 
class ProjectInfo:
    """Project information for generators."""
    name: str = "rtthread"
    target_name: str = "rtthread.elf"
    
    # File collections
    source_files: List[str] = field(default_factory=list)
    include_paths: List[str] = field(default_factory=list)
    defines: Dict[str, str] = field(default_factory=dict)
    
    # Compiler options
    cflags: str = ""
    cxxflags: str = ""
    asflags: str = ""
    ldflags: str = ""
    
    # Libraries
    libs: List[str] = field(default_factory=list)
    lib_paths: List[str] = field(default_factory=list)