building.py 16.2 KB
Newer Older
G
goprife@gmail.com 已提交
1 2 3 4 5
import os
import sys
import string

from SCons.Script import *
6
from utils import _make_path_relative
G
goprife@gmail.com 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19

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

class Win32Spawn:
    def spawn(self, sh, escape, cmd, args, env):
        import subprocess

        newargs = string.join(args[1:], ' ')
        cmdline = cmd + " " + newargs
        startupinfo = subprocess.STARTUPINFO()
20

G
goprife@gmail.com 已提交
21
        proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
22
            stderr=subprocess.PIPE, startupinfo=startupinfo, shell = False)
G
goprife@gmail.com 已提交
23 24
        data, err = proc.communicate()
        rv = proc.wait()
25 26
        if data:
            print data
27
        if err:
G
goprife@gmail.com 已提交
28
            print err
29

30
        if rv:
G
goprife@gmail.com 已提交
31 32 33
            return rv
        return 0

34
def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
G
goprife@gmail.com 已提交
35 36 37 38 39 40 41 42 43 44 45
    import SCons.cpp
    import rtconfig

    global BuildOptions
    global Projects
    global Env
    global Rtt_Root

    Env = env
    Rtt_Root = root_directory

46 47 48 49 50
    # 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 已提交
51
                Env['LINKFLAGS']=Env['LINKFLAGS'].replace('RV31', 'armcc')
52

G
goprife@gmail.com 已提交
53 54 55 56 57
    # patch for win32 spawn
    if env['PLATFORM'] == 'win32' and rtconfig.PLATFORM == 'gcc':
        win32_spawn = Win32Spawn()
        win32_spawn.env = env
        env['SPAWN'] = win32_spawn.spawn
58 59
    
    if env['PLATFORM'] == 'win32':
60 61 62
        os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
    else:
        os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
G
goprife@gmail.com 已提交
63 64 65 66 67 68 69 70 71 72 73 74

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

    # 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

75 76 77 78 79 80
    # add copy option 
    AddOption('--copy',
                      dest='copy',
                      action='store_true',
                      default=False,
                      help='copy rt-thread directory to local.')
81 82 83 84 85
    AddOption('--copy-header',
                      dest='copy-header',
                      action='store_true',
                      default=False,
                      help='copy header of rt-thread directory to local.')
86 87 88 89 90
    AddOption('--cscope',
                      dest='cscope',
                      action='store_true',
                      default=False,
                      help='Build Cscope cross reference database. Requires cscope installed.')
91

92 93 94 95 96 97
    # add build library option
    AddOption('--buildlib', 
                      dest='buildlib', 
                      type='string',
                      help='building library of a component')

G
goprife@gmail.com 已提交
98 99 100 101 102 103 104 105 106
    # add target option
    AddOption('--target',
                      dest='target',
                      type='string',
                      help='set target project: mdk')

    #{target_name:(CROSS_TOOL, PLATFORM)}
    tgt_dict = {'mdk':('keil', 'armcc'),
                'mdk4':('keil', 'armcc'),
107
                'iar':('iar', 'iar'),
wuyangyong's avatar
wuyangyong 已提交
108 109
                'vs':('msvc', 'cl'),
                'cb':('keil', 'armcc')}
G
goprife@gmail.com 已提交
110 111 112 113 114 115 116 117 118 119
    tgt_name = GetOption('target')
    if tgt_name:
        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) \
120
        and rtconfig.PLATFORM == 'gcc':
G
goprife@gmail.com 已提交
121 122
        AddDepend('RT_USING_MINILIBC')

123
    # add comstr option
124 125
    AddOption('--verbose',
                dest='verbose',
126 127
                action='store_true',
                default=False,
128
                help='print verbose information during build')
129

130 131
    if not GetOption('verbose'):
        # override the default verbose command string
132
        env.Replace(
R
Rogerz Zhang 已提交
133
            ARCOMSTR = 'AR $TARGET',
134
            ASCOMSTR = 'AS $TARGET',
R
Rogerz Zhang 已提交
135
            ASPPCOMSTR = 'AS $TARGET',
136 137 138 139
            CCCOMSTR = 'CC $TARGET',
            CXXCOMSTR = 'CXX $TARGET',
            LINKCOMSTR = 'LINK $TARGET'
        )
G
goprife@gmail.com 已提交
140 141

    # board build script
142
    objs = SConscript('SConscript', variant_dir='build', duplicate=0)
G
goprife@gmail.com 已提交
143 144
    Repository(Rtt_Root)
    # include kernel
145
    objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir='build/src', duplicate=0))
G
goprife@gmail.com 已提交
146 147
    # include libcpu
    if not has_libcpu:
148
        objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript', variant_dir='build/libcpu', duplicate=0))
149

G
goprife@gmail.com 已提交
150
    # include components
151
    objs.extend(SConscript(Rtt_Root + '/components/SConscript',
152 153 154
                           variant_dir='build/components',
                           duplicate=0,
                           exports='remove_components'))
G
goprife@gmail.com 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

    return objs

def PrepareModuleBuilding(env, root_directory):
    import SCons.cpp
    import rtconfig

    global BuildOptions
    global Projects
    global Env
    global Rtt_Root

    Env = env
    Rtt_Root = root_directory

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

wuyangyong's avatar
wuyangyong 已提交
173 174 175 176 177 178 179
def GetConfigValue(name):
    assert type(name) == str, 'GetConfigValue: only string parameter is valid'
    try:
        return BuildOptions[name]
    except:
        return ''

G
goprife@gmail.com 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
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]
          
        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

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
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']
223 224 225
    if group.has_key('LIBS'):
        if src_group.has_key('LIBS'):
            src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
226
        else:
227 228 229 230 231 232
            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']
233

G
goprife@gmail.com 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
def DefineGroup(name, src, depend, **parameters):
    global Env
    if not GetDepend(depend):
        return []

    group = parameters
    group['name'] = name
    if type(src) == type(['src1', 'str2']):
        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'])
254 255 256 257
    if group.has_key('LIBS'):
        Env.Append(LIBS = group['LIBS'])
    if group.has_key('LIBPATH'):
        Env.Append(LIBPATH = group['LIBPATH'])
G
goprife@gmail.com 已提交
258 259 260 261 262 263

    objs = Env.Object(group['src'])

    if group.has_key('LIBRARY'):
        objs = Env.Library(name, objs)

264 265 266 267 268 269 270 271 272 273
    # merge group 
    for g in Projects:
        if g['name'] == name:
            # merge to this group
            MergeGroup(g, group)
            return objs

    # add a new group 
    Projects.append(group)

G
goprife@gmail.com 已提交
274 275 276 277 278 279 280 281 282
    return objs

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

283 284 285 286 287 288 289 290 291 292 293
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()

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
def DoBuilding(target, objects):
    program = None
    # check whether special buildlib option
    lib_name = GetOption('buildlib')
    if lib_name:
        print lib_name
        # build library with special component
        for Group in Projects:
            if Group['name'] == lib_name:
                objects = Env.Object(Group['src'])
                program = Env.Library(lib_name, objects)
                break
    else:
        program = Env.Program(target, objects)

    EndBuilding(target, program)

311
def EndBuilding(target, program = None):
G
goprife@gmail.com 已提交
312
    import rtconfig
313 314 315
    from keil import MDKProject
    from keil import MDK4Project
    from iar import IARProject
316
    from vs import VSProject
wuyangyong's avatar
wuyangyong 已提交
317
    from codeblocks import CBProject
318

G
goprife@gmail.com 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    Env.AddPostAction(target, rtconfig.POST_ACTION)

    if GetOption('target') == 'mdk':
        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:
                print 'No template project file found.'

    if GetOption('target') == 'mdk4':
        MDK4Project('project.uvproj', Projects)

    if GetOption('target') == 'iar':
        IARProject('project.ewp', Projects) 
337

338
    if GetOption('target') == 'vs':
339
        VSProject('project.vcproj', Projects, program)
340

wuyangyong's avatar
wuyangyong 已提交
341 342 343
    if GetOption('target') == 'cb':
        CBProject('project.cbp', Projects, program)

344 345
    if GetOption('copy') and program != None:
        MakeCopy(program)
346 347
    if GetOption('copy-header') and program != None:
        MakeCopyHeader(program)
348

349 350 351 352
    if GetOption('cscope'):
        from cscope import CscopeDatabase
        CscopeDatabase(Projects)

G
goprife@gmail.com 已提交
353
def SrcRemove(src, remove):
354 355 356 357 358 359 360 361 362
    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)
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

def GetVersion():
    import SCons.cpp
    import string

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

    # parse rtdef.h to get RT-Thread version 
    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)
386

387 388 389 390
def GlobSubDir(sub_dir, ext_name):
    import os
    import glob

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    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
406

407
def do_copy_file(src, dst):
408 409 410 411 412 413 414 415 416 417 418 419 420 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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    import shutil
    # check source file 
    if not os.path.exists(src):
        return 

    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
    # check source directory 
    if not os.path.exists(src_dir):
        return
    
    if os.path.exists(dst_dir):
        shutil.rmtree(dst_dir)
    
    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
    
    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
465

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    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
    # get source path 
    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)
            if full_path not in src_dir: 
                src_dir.append(full_path)

    for item in src_dir: 
        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)

    # copy tools directory 
    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'))
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

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)

    # copy tools directory 
    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'))