building.py 23.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#
# File      : building.py
# This file is part of RT-Thread RTOS
# COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Change Logs:
# Date           Author       Notes
# 2015-01-20     Bernard      Add copyright information
#

G
goprife@gmail.com 已提交
25 26 27 28 29
import os
import sys
import string

from SCons.Script import *
30
from utils import _make_path_relative
G
goprife@gmail.com 已提交
31 32 33 34 35 36 37 38

BuildOptions = {}
Projects = []
Rtt_Root = ''
Env = None

class Win32Spawn:
    def spawn(self, sh, escape, cmd, args, env):
G
Grissiom 已提交
39 40 41 42 43 44 45 46 47 48 49
        # deal with the cmd build-in commands which cannot be used in
        # subprocess.Popen
        if cmd == 'del':
            for f in args[1:]:
                try:
                    os.remove(f)
                except Exception as e:
                    print 'Error removing file: %s' % e
                    return -1
            return 0

G
goprife@gmail.com 已提交
50 51 52 53
        import subprocess

        newargs = string.join(args[1:], ' ')
        cmdline = cmd + " " + newargs
G
Grissiom 已提交
54 55

        # Make sure the env is constructed by strings
56
        _e = dict([(k, str(v)) for k, v in env.items()])
G
Grissiom 已提交
57 58 59 60 61 62

        # Windows(tm) CreateProcess does not use the env passed to it to find
        # the executables. So we have to modify our own PATH to make Popen
        # work.
        old_path = os.environ['PATH']
        os.environ['PATH'] = _e['PATH']
63

G
Grissiom 已提交
64
        try:
65
            proc = subprocess.Popen(cmdline, env=_e, shell=False)
G
Grissiom 已提交
66
        except Exception as e:
67 68 69
            print 'Error in calling:\n%s' % cmdline
            print 'Exception: %s: %s' % (e, os.strerror(e.errno))
            return e.errno
G
Grissiom 已提交
70 71
        finally:
            os.environ['PATH'] = old_path
72

G
Grissiom 已提交
73
        return proc.wait()
G
goprife@gmail.com 已提交
74

75
def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
G
goprife@gmail.com 已提交
76 77 78 79 80 81 82 83 84 85 86
    import SCons.cpp
    import rtconfig

    global BuildOptions
    global Projects
    global Env
    global Rtt_Root

    Env = env
    Rtt_Root = root_directory

87 88 89 90 91
    # add compability with Keil MDK 4.6 which changes the directory of armcc.exe
    if rtconfig.PLATFORM == 'armcc':
        if not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
            if rtconfig.EXEC_PATH.find('bin40') > 0:
                rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
P
prife 已提交
92
                Env['LINKFLAGS']=Env['LINKFLAGS'].replace('RV31', 'armcc')
93

B
Bright Pan 已提交
94
        # reset AR command flags
B
bernard 已提交
95 96
        env['ARCOM'] = '$AR --create $TARGET $SOURCES'
        env['LIBPREFIX']   = ''
B
bernard 已提交
97
        env['LIBSUFFIX']   = '.lib'
B
bernard 已提交
98
        env['LIBLINKPREFIX'] = ''
B
bernard 已提交
99
        env['LIBLINKSUFFIX']   = '.lib'
B
bernard 已提交
100
        env['LIBDIRPREFIX'] = '--userlibpath '
B
bernard 已提交
101

G
goprife@gmail.com 已提交
102
    # patch for win32 spawn
G
Grissiom 已提交
103
    if env['PLATFORM'] == 'win32':
G
goprife@gmail.com 已提交
104 105 106
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn
G
Grissiom 已提交
107

108
    if env['PLATFORM'] == 'win32':
109 110 111
        os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
    else:
        os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
G
goprife@gmail.com 已提交
112 113 114 115

    # add program path
    env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

B
bernard 已提交
116 117 118 119 120
    # add library build action
    act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
    bld = Builder(action = act)
    Env.Append(BUILDERS = {'BuildLib': bld})

G
goprife@gmail.com 已提交
121 122 123 124 125 126 127 128
    # parse rtconfig.h to get used component
    PreProcessor = SCons.cpp.PreProcessor()
    f = file('rtconfig.h', 'r')
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

B
Bright Pan 已提交
129
    # add copy option
130 131 132 133 134
    AddOption('--copy',
                      dest='copy',
                      action='store_true',
                      default=False,
                      help='copy rt-thread directory to local.')
135 136 137 138 139
    AddOption('--copy-header',
                      dest='copy-header',
                      action='store_true',
                      default=False,
                      help='copy header of rt-thread directory to local.')
140 141 142 143 144
    AddOption('--cscope',
                      dest='cscope',
                      action='store_true',
                      default=False,
                      help='Build Cscope cross reference database. Requires cscope installed.')
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    AddOption('--clang-analyzer',
                      dest='clang-analyzer',
                      action='store_true',
                      default=False,
                      help='Perform static analyze with Clang-analyzer. '+\
                           'Requires Clang installed.\n'+\
                           'It is recommended to use with scan-build like this:\n'+\
                           '`scan-build scons --clang-analyzer`\n'+\
                           'If things goes well, scan-build will instruct you to invoke scan-view.')

    if GetOption('clang-analyzer'):
        # perform what scan-build does
        env.Replace(
                CC   = 'ccc-analyzer',
                CXX  = 'c++-analyzer',
                # skip as and link
                LINK = 'true',
                AS   = 'true',)
        env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
        # only check, don't compile. ccc-analyzer use CCC_CC as the CC.
165 166 167 168 169
        # fsyntax-only will give us some additional warning messages
        env['ENV']['CCC_CC']  = 'clang'
        env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
        env['ENV']['CCC_CXX'] = 'clang++'
        env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
170 171 172
        # remove the POST_ACTION as it will cause meaningless errors(file not
        # found or something like that).
        rtconfig.POST_ACTION = ''
173

174
    # add build library option
B
Bright Pan 已提交
175 176
    AddOption('--buildlib',
                      dest='buildlib',
177 178
                      type='string',
                      help='building library of a component')
B
Bright Pan 已提交
179 180
    AddOption('--cleanlib',
                      dest='cleanlib',
B
bernard 已提交
181 182 183
                      action='store_true',
                      default=False,
                      help='clean up the library by --buildlib')
184

G
goprife@gmail.com 已提交
185 186 187 188
    # add target option
    AddOption('--target',
                      dest='target',
                      type='string',
B
bernard 已提交
189
                      help='set target project: mdk/iar/vs/ua')
G
goprife@gmail.com 已提交
190 191 192 193

    #{target_name:(CROSS_TOOL, PLATFORM)}
    tgt_dict = {'mdk':('keil', 'armcc'),
                'mdk4':('keil', 'armcc'),
B
Bright Pan 已提交
194
                'mdk5':('keil', 'armcc'),
195
                'iar':('iar', 'iar'),
wuyangyong's avatar
wuyangyong 已提交
196
                'vs':('msvc', 'cl'),
197
                'vs2012':('msvc', 'cl'),
B
bernard 已提交
198 199
                'cb':('keil', 'armcc'),
                'ua':('keil', 'armcc')}
G
goprife@gmail.com 已提交
200 201
    tgt_name = GetOption('target')
    if tgt_name:
202 203 204 205 206 207
        # --target will change the toolchain settings which clang-analyzer is
        # depend on
        if GetOption('clang-analyzer'):
            print '--clang-analyzer cannot be used with --target'
            sys.exit(1)

G
goprife@gmail.com 已提交
208 209 210 211 212 213 214 215
        SetOption('no_exec', 1)
        try:
            rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
        except KeyError:
            print 'Unknow target: %s. Avaible targets: %s' % \
                    (tgt_name, ', '.join(tgt_dict.keys()))
            sys.exit(1)
    elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
216
        and rtconfig.PLATFORM == 'gcc':
G
goprife@gmail.com 已提交
217 218
        AddDepend('RT_USING_MINILIBC')

219
    # add comstr option
220 221
    AddOption('--verbose',
                dest='verbose',
222 223
                action='store_true',
                default=False,
224
                help='print verbose information during build')
225

226 227
    if not GetOption('verbose'):
        # override the default verbose command string
228
        env.Replace(
R
Rogerz Zhang 已提交
229
            ARCOMSTR = 'AR $TARGET',
230
            ASCOMSTR = 'AS $TARGET',
R
Rogerz Zhang 已提交
231
            ASPPCOMSTR = 'AS $TARGET',
232 233 234 235
            CCCOMSTR = 'CC $TARGET',
            CXXCOMSTR = 'CXX $TARGET',
            LINKCOMSTR = 'LINK $TARGET'
        )
G
goprife@gmail.com 已提交
236

237 238 239 240 241 242 243
    # we need to seperate the variant_dir for BSPs and the kernels. BSPs could
    # have their own components etc. If they point to the same folder, SCons
    # would find the wrong source code to compile.
    bsp_vdir = 'build/bsp'
    kernel_vdir = 'build/kernel'
    # board build script
    objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
G
goprife@gmail.com 已提交
244
    # include kernel
245
    objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
G
goprife@gmail.com 已提交
246 247
    # include libcpu
    if not has_libcpu:
248 249
        objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
                    variant_dir=kernel_vdir + '/libcpu', duplicate=0))
250

G
goprife@gmail.com 已提交
251
    # include components
252
    objs.extend(SConscript(Rtt_Root + '/components/SConscript',
253
                           variant_dir=kernel_vdir + '/components',
254 255
                           duplicate=0,
                           exports='remove_components'))
G
goprife@gmail.com 已提交
256 257 258

    return objs

B
Bernard Xiong 已提交
259
def PrepareModuleBuilding(env, root_directory, bsp_directory):
G
goprife@gmail.com 已提交
260 261 262 263 264 265 266 267
    import rtconfig

    global Env
    global Rtt_Root

    Env = env
    Rtt_Root = root_directory

B
Bernard Xiong 已提交
268 269 270 271 272 273 274 275
    # parse bsp rtconfig.h to get used component
    PreProcessor = SCons.cpp.PreProcessor()
    f = file(bsp_directory + '/rtconfig.h', 'r')
    contents = f.read()
    f.close()
    PreProcessor.process_contents(contents)
    BuildOptions = PreProcessor.cpp_namespace

B
Bright Pan 已提交
276 277 278
    # add build/clean library option for library checking
    AddOption('--buildlib',
              dest='buildlib',
B
bernard 已提交
279 280
              type='string',
              help='building library of a component')
B
Bright Pan 已提交
281 282
    AddOption('--cleanlib',
              dest='cleanlib',
B
bernard 已提交
283 284 285 286
              action='store_true',
              default=False,
              help='clean up the library by --buildlib')

G
goprife@gmail.com 已提交
287 288 289
    # add program path
    env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

wuyangyong's avatar
wuyangyong 已提交
290 291 292 293 294 295 296
def GetConfigValue(name):
    assert type(name) == str, 'GetConfigValue: only string parameter is valid'
    try:
        return BuildOptions[name]
    except:
        return ''

G
goprife@gmail.com 已提交
297 298 299 300 301 302 303
def GetDepend(depend):
    building = True
    if type(depend) == type('str'):
        if not BuildOptions.has_key(depend) or BuildOptions[depend] == 0:
            building = False
        elif BuildOptions[depend] != '':
            return BuildOptions[depend]
B
Bright Pan 已提交
304

G
goprife@gmail.com 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317
        return building

    # for list type depend
    for item in depend:
        if item != '':
            if not BuildOptions.has_key(item) or BuildOptions[item] == 0:
                building = False

    return building

def AddDepend(option):
    BuildOptions[option] = 1

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
def MergeGroup(src_group, group):
    src_group['src'] = src_group['src'] + group['src']
    if group.has_key('CCFLAGS'):
        if src_group.has_key('CCFLAGS'):
            src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
        else:
            src_group['CCFLAGS'] = group['CCFLAGS']
    if group.has_key('CPPPATH'):
        if src_group.has_key('CPPPATH'):
            src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
        else:
            src_group['CPPPATH'] = group['CPPPATH']
    if group.has_key('CPPDEFINES'):
        if src_group.has_key('CPPDEFINES'):
            src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
        else:
            src_group['CPPDEFINES'] = group['CPPDEFINES']
    if group.has_key('LINKFLAGS'):
        if src_group.has_key('LINKFLAGS'):
            src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
        else:
            src_group['LINKFLAGS'] = group['LINKFLAGS']
340 341 342
    if group.has_key('LIBS'):
        if src_group.has_key('LIBS'):
            src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
343
        else:
344 345 346 347 348 349
            src_group['LIBS'] = group['LIBS']
    if group.has_key('LIBPATH'):
        if src_group.has_key('LIBPATH'):
            src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
        else:
            src_group['LIBPATH'] = group['LIBPATH']
350

G
goprife@gmail.com 已提交
351 352 353 354 355
def DefineGroup(name, src, depend, **parameters):
    global Env
    if not GetDepend(depend):
        return []

356 357 358 359 360 361 362 363
    # find exist group and get path of group
    group_path = ''
    for g in Projects:
        if g['name'] == name:
            group_path = g['path']
    if group_path == '':
        group_path = GetCurrentDir()

G
goprife@gmail.com 已提交
364 365
    group = parameters
    group['name'] = name
366
    group['path'] = group_path
B
bernard 已提交
367
    if type(src) == type(['src1']):
G
goprife@gmail.com 已提交
368 369 370 371 372 373 374 375 376 377 378 379
        group['src'] = File(src)
    else:
        group['src'] = src

    if group.has_key('CCFLAGS'):
        Env.Append(CCFLAGS = group['CCFLAGS'])
    if group.has_key('CPPPATH'):
        Env.Append(CPPPATH = group['CPPPATH'])
    if group.has_key('CPPDEFINES'):
        Env.Append(CPPDEFINES = group['CPPDEFINES'])
    if group.has_key('LINKFLAGS'):
        Env.Append(LINKFLAGS = group['LINKFLAGS'])
B
bernard 已提交
380

B
Bright Pan 已提交
381
    # check whether to clean up library
B
bernard 已提交
382
    if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
B
bernard 已提交
383
        if group['src'] != []:
B
bernard 已提交
384 385
            print 'Remove library:', GroupLibFullName(name, Env)
            do_rm_file(os.path.join(group['path'], GroupLibFullName(name, Env)))
B
bernard 已提交
386 387

    # check whether exist group library
B
bernard 已提交
388
    if not GetOption('buildlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
B
bernard 已提交
389
        group['src'] = []
390 391 392 393
        if group.has_key('LIBS'): group['LIBS'] = group['LIBS'] + [GroupLibName(name, Env)]
        else : group['LIBS'] = [GroupLibName(name, Env)]
        if group.has_key('LIBPATH'): group['LIBPATH'] = group['LIBPATH'] + [GetCurrentDir()]
        else : group['LIBPATH'] = [GetCurrentDir()]
B
bernard 已提交
394

395 396 397 398
    if group.has_key('LIBS'):
        Env.Append(LIBS = group['LIBS'])
    if group.has_key('LIBPATH'):
        Env.Append(LIBPATH = group['LIBPATH'])
G
goprife@gmail.com 已提交
399 400

    if group.has_key('LIBRARY'):
401 402 403
        objs = Env.Library(name, group['src'])
    else:
        objs = group['src']
G
goprife@gmail.com 已提交
404

B
Bright Pan 已提交
405
    # merge group
406 407 408 409 410 411
    for g in Projects:
        if g['name'] == name:
            # merge to this group
            MergeGroup(g, group)
            return objs

B
Bright Pan 已提交
412
    # add a new group
413 414
    Projects.append(group)

G
goprife@gmail.com 已提交
415 416 417 418 419 420 421 422 423
    return objs

def GetCurrentDir():
    conscript = File('SConscript')
    fn = conscript.rfile()
    name = fn.name
    path = os.path.dirname(fn.abspath)
    return path

424 425 426 427 428 429 430 431 432 433 434
PREBUILDING = []
def RegisterPreBuildingAction(act):
    global PREBUILDING
    assert callable(act), 'Could only register callable objects. %s received' % repr(act)
    PREBUILDING.append(act)

def PreBuilding():
    global PREBUILDING
    for a in PREBUILDING:
        a()

B
bernard 已提交
435
def GroupLibName(name, env):
B
bernard 已提交
436 437 438 439 440 441 442 443 444 445
    import rtconfig
    if rtconfig.PLATFORM == 'armcc':
        return name + '_rvds'
    elif rtconfig.PLATFORM == 'gcc':
        return name + '_gcc'

    return name

def GroupLibFullName(name, env):
    return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
B
bernard 已提交
446 447 448 449 450

def BuildLibInstallAction(target, source, env):
    lib_name = GetOption('buildlib')
    for Group in Projects:
        if Group['name'] == lib_name:
B
bernard 已提交
451
            lib_name = GroupLibFullName(Group['name'], env)
B
bernard 已提交
452 453 454 455 456
            dst_name = os.path.join(Group['path'], lib_name)
            print 'Copy %s => %s' % (lib_name, dst_name)
            do_copy_file(lib_name, dst_name)
            break

457 458 459 460 461 462 463 464
def DoBuilding(target, objects):
    program = None
    # check whether special buildlib option
    lib_name = GetOption('buildlib')
    if lib_name:
        # build library with special component
        for Group in Projects:
            if Group['name'] == lib_name:
B
bernard 已提交
465
                lib_name = GroupLibName(Group['name'], Env)
466 467
                objects = Env.Object(Group['src'])
                program = Env.Library(lib_name, objects)
B
bernard 已提交
468 469 470 471

                # add library copy action
                Env.BuildLib(lib_name, program)

472 473 474 475 476 477
                break
    else:
        program = Env.Program(target, objects)

    EndBuilding(target, program)

478
def EndBuilding(target, program = None):
G
goprife@gmail.com 已提交
479
    import rtconfig
480

G
goprife@gmail.com 已提交
481 482 483
    Env.AddPostAction(target, rtconfig.POST_ACTION)

    if GetOption('target') == 'mdk':
B
bernard 已提交
484 485
        from keil import MDKProject
        from keil import MDK4Project
B
Bright Pan 已提交
486
        from keil import MDK5Project
B
bernard 已提交
487

G
goprife@gmail.com 已提交
488 489 490 491 492 493 494 495
        template = os.path.isfile('template.Uv2')
        if template:
            MDKProject('project.Uv2', Projects)
        else:
            template = os.path.isfile('template.uvproj')
            if template:
                MDK4Project('project.uvproj', Projects)
            else:
B
Bright Pan 已提交
496 497 498 499 500 501
                template = os.path.isfile('template.uvprojx')
                if template:
                    MDK5Project('project.uvprojx', Projects)
                else:
                    print 'No template project file found.'

G
goprife@gmail.com 已提交
502 503

    if GetOption('target') == 'mdk4':
B
bernard 已提交
504
        from keil import MDK4Project
G
goprife@gmail.com 已提交
505 506
        MDK4Project('project.uvproj', Projects)

B
Bright Pan 已提交
507 508 509 510
    if GetOption('target') == 'mdk5':
        from keil import MDK5Project
        MDK5Project('project.uvprojx', Projects)

G
goprife@gmail.com 已提交
511
    if GetOption('target') == 'iar':
B
bernard 已提交
512
        from iar import IARProject
B
Bright Pan 已提交
513
        IARProject('project.ewp', Projects)
514

515
    if GetOption('target') == 'vs':
B
bernard 已提交
516
        from vs import VSProject
517
        VSProject('project.vcproj', Projects, program)
518

519
    if GetOption('target') == 'vs2012':
B
bernard 已提交
520
        from vs2012 import VS2012Project
521 522
        VS2012Project('project.vcxproj', Projects, program)

wuyangyong's avatar
wuyangyong 已提交
523
    if GetOption('target') == 'cb':
B
bernard 已提交
524
        from codeblocks import CBProject
wuyangyong's avatar
wuyangyong 已提交
525 526
        CBProject('project.cbp', Projects, program)

B
bernard 已提交
527 528 529
    if GetOption('target') == 'ua':
        from ua import PrepareUA
        PrepareUA(Projects, Rtt_Root, str(Dir('#')))
B
Bright Pan 已提交
530

531 532
    if GetOption('copy') and program != None:
        MakeCopy(program)
533 534
    if GetOption('copy-header') and program != None:
        MakeCopyHeader(program)
535

536 537 538 539
    if GetOption('cscope'):
        from cscope import CscopeDatabase
        CscopeDatabase(Projects)

G
goprife@gmail.com 已提交
540
def SrcRemove(src, remove):
G
Grissiom 已提交
541 542 543
    if not src:
        return

544 545 546 547 548 549 550 551 552
    if type(src[0]) == type('str'):
        for item in src:
            if os.path.basename(item) in remove:
                src.remove(item)
        return

    for item in src:
        if os.path.basename(item.rstr()) in remove:
            src.remove(item)
553 554 555 556 557 558 559

def GetVersion():
    import SCons.cpp
    import string

    rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')

B
Bright Pan 已提交
560
    # parse rtdef.h to get RT-Thread version
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    prepcessor = SCons.cpp.PreProcessor()
    f = file(rtdef, 'r')
    contents = f.read()
    f.close()
    prepcessor.process_contents(contents)
    def_ns = prepcessor.cpp_namespace

    version = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_VERSION']))
    subversion = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_SUBVERSION']))

    if def_ns.has_key('RT_REVISION'):
        revision = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_REVISION']))
        return '%d.%d.%d' % (version, subversion, revision)

    return '0.%d.%d' % (version, subversion)
576

577 578 579 580
def GlobSubDir(sub_dir, ext_name):
    import os
    import glob

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
    def glob_source(sub_dir, ext_name):
        list = os.listdir(sub_dir)
        src = glob.glob(os.path.join(sub_dir, ext_name))

        for item in list:
            full_subdir = os.path.join(sub_dir, item)
            if os.path.isdir(full_subdir):
                src += glob_source(full_subdir, ext_name)
        return src

    dst = []
    src = glob_source(sub_dir, ext_name)
    for item in src:
        dst.append(os.path.relpath(item, sub_dir))
    return dst
596

597 598 599
def file_path_exist(path, *args):
    return os.path.exists(os.path.join(path, *args))

B
bernard 已提交
600 601 602 603
def do_rm_file(src):
    if os.path.exists(src):
       os.unlink(src)

604
def do_copy_file(src, dst):
605
    import shutil
B
Bright Pan 已提交
606
    # check source file
607
    if not os.path.exists(src):
B
Bright Pan 已提交
608
        return
609 610 611 612 613 614 615 616 617 618

    path = os.path.dirname(dst)
    # mkdir if path not exist
    if not os.path.exists(path):
        os.makedirs(path)

    shutil.copy2(src, dst)

def do_copy_folder(src_dir, dst_dir):
    import shutil
B
Bright Pan 已提交
619
    # check source directory
620 621
    if not os.path.exists(src_dir):
        return
B
Bright Pan 已提交
622

623 624
    if os.path.exists(dst_dir):
        shutil.rmtree(dst_dir)
B
Bright Pan 已提交
625

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    shutil.copytree(src_dir, dst_dir)

source_ext = ["c", "h", "s", "S", "cpp", "xpm"]
source_list = []

def walk_children(child):
    global source_list
    global source_ext

    # print child
    full_path = child.rfile().abspath
    file_type  = full_path.rsplit('.',1)[1]
    #print file_type
    if file_type in source_ext:
        if full_path not in source_list:
            source_list.append(full_path)

    children = child.all_children()
    if children != []:
        for item in children:
            walk_children(item)

def MakeCopy(program):
    global source_list
    global Rtt_Root
    global Env
B
Bright Pan 已提交
652

653
    target_path = os.path.join(Dir('#').abspath, 'rt-thread')
B
Bright Pan 已提交
654

655 656 657 658
    if Env['PLATFORM'] == 'win32':
        RTT_ROOT = Rtt_Root.lower()
    else:
        RTT_ROOT = Rtt_Root
B
Bright Pan 已提交
659

660 661
    if target_path.startswith(RTT_ROOT):
        return
662

663 664
    for item in program:
        walk_children(item)
B
Bright Pan 已提交
665

666
    source_list.sort()
B
Bright Pan 已提交
667

668 669 670 671 672 673 674 675 676 677
    # filte source file in RT-Thread
    target_list = []
    for src in source_list:
        if Env['PLATFORM'] == 'win32':
            src = src.lower()

        if src.startswith(RTT_ROOT):
            target_list.append(src)

    source_list = target_list
B
Bright Pan 已提交
678
    # get source path
679 680 681 682 683 684 685 686 687 688 689
    src_dir = []
    for src in source_list:
        src = src.replace(RTT_ROOT, '')
        if src[0] == os.sep or src[0] == '/':
            src = src[1:]

        path = os.path.dirname(src)
        sub_path = path.split(os.sep)
        full_path = RTT_ROOT
        for item in sub_path:
            full_path = os.path.join(full_path, item)
B
Bright Pan 已提交
690
            if full_path not in src_dir:
691 692
                src_dir.append(full_path)

B
Bright Pan 已提交
693
    for item in src_dir:
694 695 696 697 698 699 700 701 702 703
        source_list.append(os.path.join(item, 'SConscript'))

    for src in source_list:
        dst = src.replace(RTT_ROOT, '')
        if dst[0] == os.sep or dst[0] == '/':
            dst = dst[1:]
        print '=> ', dst
        dst = os.path.join(target_path, dst)
        do_copy_file(src, dst)

B
Bright Pan 已提交
704
    # copy tools directory
705 706 707 708
    print "=>  tools"
    do_copy_folder(os.path.join(RTT_ROOT, "tools"), os.path.join(target_path, "tools"))
    do_copy_file(os.path.join(RTT_ROOT, 'AUTHORS'), os.path.join(target_path, 'AUTHORS'))
    do_copy_file(os.path.join(RTT_ROOT, 'COPYING'), os.path.join(target_path, 'COPYING'))
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751

def MakeCopyHeader(program):
    global source_ext
    source_ext = []
    source_ext = ["h", "xpm"]
    global source_list
    global Rtt_Root
    global Env

    target_path = os.path.join(Dir('#').abspath, 'rt-thread')

    if Env['PLATFORM'] == 'win32':
        RTT_ROOT = Rtt_Root.lower()
    else:
        RTT_ROOT = Rtt_Root

    if target_path.startswith(RTT_ROOT):
        return

    for item in program:
        walk_children(item)

    source_list.sort()

    # filte source file in RT-Thread
    target_list = []
    for src in source_list:
        if Env['PLATFORM'] == 'win32':
            src = src.lower()

        if src.startswith(RTT_ROOT):
            target_list.append(src)

    source_list = target_list

    for src in source_list:
        dst = src.replace(RTT_ROOT, '')
        if dst[0] == os.sep or dst[0] == '/':
            dst = dst[1:]
        print '=> ', dst
        dst = os.path.join(target_path, dst)
        do_copy_file(src, dst)

B
Bright Pan 已提交
752
    # copy tools directory
753 754 755 756
    print "=>  tools"
    do_copy_folder(os.path.join(RTT_ROOT, "tools"), os.path.join(target_path, "tools"))
    do_copy_file(os.path.join(RTT_ROOT, 'AUTHORS'), os.path.join(target_path, 'AUTHORS'))
    do_copy_file(os.path.join(RTT_ROOT, 'COPYING'), os.path.join(target_path, 'COPYING'))