eclipse.py 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
#
# Copyright (c) 2006-2019, RT-Thread Development Team
#
# SPDX-License-Identifier: Apache-2.0
#
# Change Logs:
# Date           Author       Notes
# 2019-03-21     Bernard      the first version
# 2019-04-15     armink       fix project update error
#

B
Bernard Xiong 已提交
12 13 14 15 16 17 18 19 20 21 22
import os
import sys
import glob

from utils import *
from utils import _make_path_relative
from utils import xml_indent

import xml.etree.ElementTree as etree
from xml.etree.ElementTree import SubElement

23 24
from building import *

25
MODULE_VER_NUM = 1
26

B
Bernard Xiong 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
source_pattern = ['*.c', '*.cpp', '*.cxx', '*.s', '*.S', '*.asm']

def OSPath(path):
    import platform

    if type(path) == type('str'):
        if platform.system() == 'Windows':
            return path.replace('/', '\\')
        else:
            return path.replace('\\', '/')
    else:
        if platform.system() == 'Windows':
            return [item.replace('/', '\\') for item in path]
        else:
            return [item.replace('\\', '/') for item in path]

43 44

# collect the build source code path and parent path
B
Bernard Xiong 已提交
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
def CollectPaths(paths):
    all_paths = []

    def ParentPaths(path):
        ret = os.path.dirname(path)
        if ret == path or ret == '':
            return []

        return [ret] + ParentPaths(ret)

    for path in paths:
        # path = os.path.abspath(path)
        path = path.replace('\\', '/')
        all_paths = all_paths + [path] + ParentPaths(path)

    all_paths = list(set(all_paths))
    return sorted(all_paths)

'''
Collect all of files under paths
'''
def CollectFiles(paths, pattern):
    files = []
    for path in paths:
        if type(pattern) == type(''):
            files = files + glob.glob(path + '/' + pattern)
        else:
            for item in pattern:
                # print('--> %s' % (path + '/' + item))
                files = files + glob.glob(path + '/' + item)

    return sorted(files)

def CollectAllFilesinPath(path, pattern):
    files = []

    for item in pattern:
        files += glob.glob(path + '/' + item)

    list = os.listdir(path)
    if len(list):
        for item in list:
            if item.startswith('.'):
                continue
            if item == 'bsp':
                continue

            if os.path.isdir(os.path.join(path, item)):
                files = files + CollectAllFilesinPath(os.path.join(path, item), pattern)
    return files

'''
Exclude files from infiles
'''
def ExcludeFiles(infiles, files):
    in_files  = set([OSPath(file) for file in infiles])
    exl_files = set([OSPath(file) for file in files])

    exl_files = in_files - exl_files

    return exl_files

107 108

# caluclate the exclude path for project
109
def ExcludePaths(rootpath, paths):
B
Bernard Xiong 已提交
110 111
    ret = []

112
    files = os.listdir(rootpath)
B
Bernard Xiong 已提交
113 114 115 116
    for file in files:
        if file.startswith('.'):
            continue

117
        fullname = os.path.join(rootpath, file)
B
Bernard Xiong 已提交
118 119 120 121 122 123 124 125 126 127

        if os.path.isdir(fullname):
            # print(fullname)
            if not fullname in paths:
                ret = ret + [fullname]
            else:
                ret = ret + ExcludePaths(fullname, paths)

    return ret

128

129 130 131 132 133 134 135 136 137 138 139 140
rtt_path_prefix = '"${workspace_loc://${ProjName}//'


def ConverToRttEclipsePathFormat(path):
    return rtt_path_prefix + path + '}"'


def IsRttEclipsePathFormat(path):
    if path.startswith(rtt_path_prefix):
        return True
    else :
        return False
141 142 143
    
    
def IsCppProject():
144
    return GetDepend('RT_USING_CPLUSPLUS')
145 146

        
147
def HandleToolOption(tools, env, project, reset):
148
    is_cpp_prj = IsCppProject()
B
Bernard Xiong 已提交
149 150 151
    BSP_ROOT = os.path.abspath(env['BSP_ROOT'])

    CPPDEFINES = project['CPPDEFINES']
152
    paths = [ConverToRttEclipsePathFormat(RelativeProjectPath(env, os.path.normpath(i)).replace('\\', '/')) for i in project['CPPPATH']]
B
Bernard Xiong 已提交
153

154 155 156
    compile_include_paths_options = []
    compile_include_files_options = []
    compile_defs_options = []
157 158 159 160 161
    linker_scriptfile_option = None
    linker_script_option = None
    linker_nostart_option = None
    linker_libs_option = None
    linker_paths_option = None
162

163 164
    linker_newlib_nano_option = None

B
Bernard Xiong 已提交
165
    for tool in tools:
166

167
        if tool.get('id').find('compile') != 1:
B
Bernard Xiong 已提交
168
            options = tool.findall('option')
169
            # find all compile options
B
Bernard Xiong 已提交
170
            for option in options:
171 172 173 174 175 176 177 178
                if option.get('id').find('compiler.include.paths') != -1 or option.get('id').find('compiler.option.includepaths') != -1:
                    compile_include_paths_options += [option]
                elif option.get('id').find('compiler.include.files') != -1 or option.get('id').find('compiler.option.includefiles') != -1 :
                    compile_include_files_options += [option]
                elif option.get('id').find('compiler.defs') != -1 or option.get('id').find('compiler.option.definedsymbols') != -1:
                    compile_defs_options += [option]

        if tool.get('id').find('linker') != -1:
179 180 181
            options = tool.findall('option')
            # find all linker options
            for option in options:
182 183 184 185 186
                # the project type and option type must equal
                if is_cpp_prj != (option.get('id').find('cpp.linker') != -1):
                    continue

                if option.get('id').find('linker.scriptfile') != -1:
187
                    linker_scriptfile_option = option
188
                elif option.get('id').find('linker.option.script') != -1:
189
                    linker_script_option = option
190
                elif option.get('id').find('linker.nostart') != -1:
191
                    linker_nostart_option = option
192
                elif option.get('id').find('linker.libs') != -1 and env.has_key('LIBS'):
193
                    linker_libs_option = option
194
                elif option.get('id').find('linker.paths') != -1 and env.has_key('LIBPATH'):
195
                    linker_paths_option = option
196
                elif option.get('id').find('linker.usenewlibnano') != -1:
197 198 199
                    linker_newlib_nano_option = option

    # change the inclue path
200
    for option in compile_include_paths_options:
201 202 203 204 205 206 207 208 209 210 211
        # find all of paths in this project
        include_paths = option.findall('listOptionValue')
        for item in include_paths:
            if reset is True or IsRttEclipsePathFormat(item.get('value')) :
                # clean old configuration
                option.remove(item)
        # print('c.compiler.include.paths')
        paths = sorted(paths)
        for item in paths:
            SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
    # change the inclue files (default) or definitions
212
    for option in compile_include_files_options:
213 214 215 216 217
        # add '_REENT_SMALL' to CPPDEFINES when --specs=nano.specs has select
        if linker_newlib_nano_option is not None and linker_newlib_nano_option.get('value') == 'true' and '_REENT_SMALL' not in CPPDEFINES:
            CPPDEFINES += ['_REENT_SMALL']

        file_header = '''
218 219 220 221
#ifndef RTCONFIG_PREINC_H__
#define RTCONFIG_PREINC_H__

/* Automatically generated file; DO NOT EDIT. */
222
/* RT-Thread pre-include file */
223 224

'''
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        file_tail = '\n#endif /*RTCONFIG_PREINC_H__*/\n'
        rtt_pre_inc_item = '"${workspace_loc:/${ProjName}/rtconfig_preinc.h}"'
        # save the CPPDEFINES in to rtconfig_preinc.h
        with open('rtconfig_preinc.h', mode = 'w+') as f:
            f.write(file_header)
            for cppdef in CPPDEFINES:
                f.write("#define " + cppdef + '\n')
            f.write(file_tail)
        #  change the c.compiler.include.files
        files = option.findall('listOptionValue')
        find_ok = False
        for item in files:
            if item.get('value') == rtt_pre_inc_item:
                find_ok = True
                break
        if find_ok is False:
            SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': rtt_pre_inc_item})
242 243 244 245 246 247 248 249 250 251 252 253
    if len(compile_include_files_options) == 0:
        for option in compile_defs_options:
            defs = option.findall('listOptionValue')
            project_defs = []
            for item in defs:
                if reset is True:
                    # clean all old configuration
                    option.remove(item)
                else:
                    project_defs += [item.get('value')]
            if len(project_defs) > 0:
                cproject_defs = set(CPPDEFINES) - set(project_defs)
254
            else:
255
                cproject_defs = CPPDEFINES
256

257 258 259 260
            # print('c.compiler.defs')
            cproject_defs = sorted(cproject_defs)
            for item in cproject_defs:
                SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': item})
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

    # update linker script config
    if linker_scriptfile_option is not None :
        option = linker_scriptfile_option
        linker_script = 'link.lds'
        items = env['LINKFLAGS'].split(' ')
        if '-T' in items:
            linker_script = items[items.index('-T') + 1]
            linker_script = ConverToRttEclipsePathFormat(linker_script)

        listOptionValue = option.find('listOptionValue')
        if listOptionValue != None:
            listOptionValue.set('value', linker_script)
        else:
            SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': linker_script})
    # scriptfile in stm32cubeIDE
    if linker_script_option is not None :
        option = linker_script_option
        items = env['LINKFLAGS'].split(' ')
        if '-T' in items:
            linker_script = ConverToRttEclipsePathFormat(items[items.index('-T') + 1]).strip('"')
            option.set('value', linker_script)
    # update nostartfiles config
    if linker_nostart_option is not None :
        option = linker_nostart_option
        if env['LINKFLAGS'].find('-nostartfiles') != -1:
            option.set('value', 'true')
        else:
            option.set('value', 'false')
    # update libs
    if linker_libs_option is not None :
        option = linker_libs_option
        # remove old libs
        for item in option.findall('listOptionValue'):
            option.remove(item)
        # add new libs
        for lib in env['LIBS']:
            SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': lib})
    # update lib paths
    if linker_paths_option is not None :
        option = linker_paths_option
        # remove old lib paths
        for item in option.findall('listOptionValue'):
304 305 306
            if IsRttEclipsePathFormat(item.get('value')):
                # clean old configuration
                option.remove(item)
307 308
        # add new old lib paths
        for path in env['LIBPATH']:
309
            SubElement(option, 'listOptionValue', {'builtIn': 'false', 'value': ConverToRttEclipsePathFormat(RelativeProjectPath(env, path).replace('\\', '/'))})
310

B
Bernard Xiong 已提交
311 312
    return

313 314

def UpdateProjectStructure(env, prj_name):
B
Bernard Xiong 已提交
315 316 317
    bsp_root = env['BSP_ROOT']
    rtt_root = env['RTT_ROOT']

318 319
    project = etree.parse('.project')
    root = project.getroot()
B
Bernard Xiong 已提交
320

321 322 323 324
    if rtt_root.startswith(bsp_root):
        linkedResources = root.find('linkedResources')
        if linkedResources == None:
            linkedResources = SubElement(root, 'linkedResources')
B
Bernard Xiong 已提交
325

326 327 328 329 330
        links = linkedResources.findall('link')
        # delete all RT-Thread folder links
        for link in links:
            if link.find('name').text.startswith('rt-thread'):
                linkedResources.remove(link)
331

332 333 334 335 336 337 338 339 340 341 342
    if prj_name:
        name = root.find('name')
        if name == None:
            name = SubElement(root, 'name')
        name.text = prj_name

    out = open('.project', 'w')
    out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    xml_indent(root)
    out.write(etree.tostring(root, encoding = 'utf-8'))
    out.close()
B
Bernard Xiong 已提交
343 344 345

    return

346 347

def GenExcluding(env, project):
348
    rtt_root = os.path.abspath(env['RTT_ROOT'])
349
    bsp_root = os.path.abspath(env['BSP_ROOT'])
350 351
    coll_dirs = CollectPaths(project['DIRS'])
    all_paths = [OSPath(path) for path in coll_dirs]
B
Bernard Xiong 已提交
352

353 354 355 356 357
    # remove unused path
    for path in all_paths:
        if not path.startswith(rtt_root) and not path.startswith(bsp_root):
            all_paths.remove(path)

358 359 360 361 362
    if bsp_root.startswith(rtt_root):
        # bsp folder is in the RT-Thread root folder, such as the RT-Thread source code on GitHub
        exclude_paths = ExcludePaths(rtt_root, all_paths)
    elif rtt_root.startswith(bsp_root):
        # RT-Thread root folder is in the bsp folder, such as project folder which generate by 'scons --dist' cmd
363 364 365 366 367 368 369 370 371 372 373
        check_path = []
        exclude_paths = []
        # analyze the primary folder which relative to BSP_ROOT and in all_paths
        for path in all_paths :
            if path.startswith(bsp_root) :
                folders = RelativeProjectPath(env, path).split('\\')
                if folders[0] != '.' and '\\' + folders[0] not in check_path:
                    check_path += ['\\' + folders[0]]
        # exclue the folder which has managed by scons
        for path in check_path:
            exclude_paths += ExcludePaths(bsp_root + path, all_paths)
374 375 376
    else:
        exclude_paths = ExcludePaths(rtt_root, all_paths)
        exclude_paths += ExcludePaths(bsp_root, all_paths)
B
Bernard Xiong 已提交
377 378 379

    paths = exclude_paths
    exclude_paths = []
380
    # remove the folder which not has source code by source_pattern
B
Bernard Xiong 已提交
381 382 383 384 385 386 387 388 389 390
    for path in paths:
        # add bsp and libcpu folder and not collect source files (too more files)
        if path.endswith('rt-thread\\bsp') or path.endswith('rt-thread\\libcpu'):
            exclude_paths += [path]
            continue

        set = CollectAllFilesinPath(path, source_pattern)
        if len(set):
            exclude_paths += [path]

391
    exclude_paths = [RelativeProjectPath(env, path).replace('\\', '/') for path in exclude_paths]
B
Bernard Xiong 已提交
392 393 394 395 396

    all_files = CollectFiles(all_paths, source_pattern)
    src_files = project['FILES']

    exclude_files = ExcludeFiles(all_files, src_files)
397
    exclude_files = [RelativeProjectPath(env, file).replace('\\', '/') for file in exclude_files]
398

399 400
    env['ExPaths'] = exclude_paths
    env['ExFiles'] = exclude_files
401

402 403 404 405 406 407 408 409 410 411 412 413 414 415
    return  exclude_paths + exclude_files


def RelativeProjectPath(env, path):
    project_root = os.path.abspath(env['BSP_ROOT'])
    rtt_root = os.path.abspath(env['RTT_ROOT'])
    
    if path.startswith(project_root):
        return _make_path_relative(project_root, path)
    
    if path.startswith(rtt_root):
        return 'rt-thread/' + _make_path_relative(rtt_root, path)

    # TODO add others folder
416
    print('ERROR: the ' + path + ' not support')
417 418 419 420

    return path


421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
def HandleExcludingOption(entry, sourceEntries, excluding):
    old_excluding = []
    if entry != None:
        old_excluding = entry.get('excluding').split('|')
        sourceEntries.remove(entry)

    value = ''
    for item in old_excluding:
        if item.startswith('//') :
            old_excluding.remove(item)
        else :
            if value == '':
                value = item
            else:
                value += '|' + item

    for item in excluding:
        # add special excluding path prefix for RT-Thread
        item = '//' + item
        if value == '':
            value = item
        else:
            value += '|' + item

    SubElement(sourceEntries, 'entry', {'excluding': value, 'flags': 'VALUE_WORKSPACE_PATH|RESOLVED', 'kind':'sourcePath', 'name':""})


448
def UpdateCproject(env, project, excluding, reset, prj_name):
449
    excluding = sorted(excluding)
B
Bernard Xiong 已提交
450 451 452 453 454 455 456

    cproject = etree.parse('.cproject')

    root = cproject.getroot()
    cconfigurations = root.findall('storageModule/cconfiguration')
    for cconfiguration in cconfigurations:
        tools = cconfiguration.findall('storageModule/configuration/folderInfo/toolChain/tool')
457
        HandleToolOption(tools, env, project, reset)
B
Bernard Xiong 已提交
458 459 460

        sourceEntries = cconfiguration.find('storageModule/configuration/sourceEntries')
        entry = sourceEntries.find('entry')
461
        HandleExcludingOption(entry, sourceEntries, excluding)
462 463 464 465 466 467 468 469
    # update refreshScope
    if prj_name:
        prj_name = '/' + prj_name
        configurations = root.findall('storageModule/configuration')
        for configuration in configurations:
            resource = configuration.find('resource')
            configuration.remove(resource)
            SubElement(configuration, 'resource', {'resourceType': "PROJECT", 'workspacePath': prj_name})
B
Bernard Xiong 已提交
470 471 472 473 474 475 476 477 478

    # write back to .cproject
    out = open('.cproject', 'w')
    out.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
    out.write('<?fileVersion 4.0.0?>')
    xml_indent(root)
    out.write(etree.tostring(root, encoding='utf-8'))
    out.close()

479

480
def TargetEclipse(env, reset = False, prj_name = None):
481 482 483 484 485 486 487 488 489 490 491
    global source_pattern

    print('Update eclipse setting...')

    if not os.path.exists('.cproject'):
        print('no eclipse CDT project found!')
        return

    project = ProjectInfo(env)

    # update the project file structure info on '.project' file
492
    UpdateProjectStructure(env, prj_name)
493 494

    # generate the exclude paths and files
495
    excluding = GenExcluding(env, project)
496 497

    # update the project configuration on '.cproject' file
498
    UpdateCproject(env, project, excluding, reset, prj_name)
499

B
Bernard Xiong 已提交
500 501 502
    print('done!')

    return