summaryrefslogtreecommitdiff
path: root/tools/ng/adapter.py
blob: 64a2a17dfc9e23c33d9b0b2c8c05f8675edb3dad (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# -*- coding: utf-8 -*-
"""
Adapter module to integrate new OOP implementation with existing building.py.

This module provides the bridge between the legacy function-based API and the new
object-oriented implementation, ensuring backward compatibility.
"""

import os
from typing import List, Dict, Any, Optional

from .core import BuildContext
from .environment import RTEnv
from .generator import GeneratorConfig, GeneratorRegistry


# Global variables for compatibility
_context: Optional[BuildContext] = None


def init_build_context(root_directory: str) -> BuildContext:
    """
    Initialize the build context.
    
    This function should be called early in PrepareBuilding.
    
    Args:
        root_directory: RT-Thread root directory
        
    Returns:
        BuildContext instance
    """
    global _context
    _context = BuildContext(root_directory)
    return _context


def get_build_context() -> Optional[BuildContext]:
    """Get the current build context."""
    return _context


def inject_environment_methods(env) -> None:
    """
    Inject RT-Thread methods into SCons Environment.
    
    This should be called in PrepareBuilding after environment setup.
    
    Args:
        env: SCons Environment object
    """
    RTEnv.inject_methods(env)
    
    # Also set the environment in context
    if _context:
        _context.prepare_environment(env)


def load_rtconfig(config_file: str = 'rtconfig.h') -> Dict[str, Any]:
    """
    Load configuration from rtconfig.h.
    
    Args:
        config_file: Configuration file name
        
    Returns:
        Dictionary of build options
    """
    if _context:
        _context.load_configuration(config_file)
        return _context.build_options
    return {}


def DefineGroup(name: str, src: List[str], depend: Any = None, **kwargs) -> List:
    """
    Legacy DefineGroup function for backward compatibility.
    
    This function delegates to the environment method.
    
    Args:
        name: Group name
        src: Source files
        depend: Dependencies
        **kwargs: Additional parameters
        
    Returns:
        List of build objects
    """
    if _context and _context.environment:
        return _context.environment.DefineGroup(name, src, depend, **kwargs)
    else:
        # Fallback behavior
        print(f"Warning: DefineGroup called before environment setup for group '{name}'")
        return []


def GetDepend(depend: Any) -> bool:
    """
    Legacy GetDepend function for backward compatibility.
    
    Args:
        depend: Dependency to check
        
    Returns:
        True if dependency is satisfied
    """
    if _context:
        return _context.get_dependency(depend)
    return False


def GetCurrentDir() -> str:
    """
    Get current directory.
    
    Returns:
        Current directory path
    """
    return os.path.abspath('.')


def SrcRemove(src: List[str], remove: List[str]) -> None:
    """
    Remove files from source list.
    
    Args:
        src: Source list (modified in place)
        remove: Files to remove
    """
    if not isinstance(remove, list):
        remove = [remove]
        
    for item in remove:
        if item in src:
            src.remove(item)


def GetBuildOptions() -> Dict[str, Any]:
    """
    Get build options.
    
    Returns:
        Dictionary of build options
    """
    if _context:
        return _context.build_options
    return {}


def MergeGroups() -> List:
    """
    Merge all registered groups.
    
    Returns:
        List of all build objects
    """
    if _context:
        return _context.merge_groups()
    return []


def GenerateProject(target: str, env, projects: List) -> None:
    """
    Generate IDE project files.
    
    Args:
        target: Target type (mdk5, iar, vscode, etc.)
        env: SCons Environment
        projects: Project list
    """
    if not _context:
        print("Error: Build context not initialized")
        return
        
    # Get project info from registry
    project_info = _context.project_registry.get_project_info()
    
    # Create generator config
    config = GeneratorConfig(
        output_dir=os.getcwd(),
        project_name=os.path.basename(os.getcwd()),
        target_name="rtthread.elf"
    )
    
    # Create and run generator
    try:
        generator = _context.generator_registry.create_generator(target, config)
        if generator.generate(_context, project_info):
            print(f"Successfully generated {target} project files")
        else:
            print(f"Failed to generate {target} project files")
    except Exception as e:
        print(f"Error generating {target} project: {e}")


def PrepareModuleBuilding(env, root_directory, bsp_directory) -> None:
    """
    Prepare for building a module.
    
    This is a simplified version of PrepareBuilding for module compilation.
    
    Args:
        env: SCons Environment
        root_directory: RT-Thread root directory
        bsp_directory: BSP directory
    """
    # Initialize context
    context = init_build_context(root_directory)
    context.bsp_directory = bsp_directory
    
    # Inject methods
    inject_environment_methods(env)
    
    # Load configuration
    config_path = os.path.join(bsp_directory, 'rtconfig.h')
    if os.path.exists(config_path):
        load_rtconfig(config_path)