summaryrefslogtreecommitdiff
path: root/abs
blob: 52f7a26b689f9be33c8ece1e59f4d6f67aa4f530 (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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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
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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
# Copyright (c) 2014, 2015, 2016 Samsung Electronics.Co.Ltd.
#
# 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; version 2 of the License
#
# 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.
#

import sys
import os
import subprocess
import re
import argparse
from argparse import ArgumentParser
import ConfigParser
import glob
import fnmatch
import shutil
import zipfile
import errno

g_home = os.path.dirname(os.path.realpath(__file__))
class LocalError(Exception):
    """Local error exception."""

    pass

class Executor(object):
    """Subprocess wrapper"""

    def __init__(self, checker=None):
        self.stdout = subprocess.PIPE
        self.stderr = subprocess.STDOUT
        self.checker = checker

    def run(self, cmdline_or_args, show=False, checker=False):
        """Execute external command"""

        out = ''
        try:
            process = subprocess.Popen(cmdline_or_args, \
                                       stdout=self.stdout, \
                                       stderr=self.stderr, \
                                       shell=True)
            while True:
                line = process.stdout.readline()
                if show:
                    print line.rstrip()
                out = out + '\n' + line.rstrip()
                if not line:
                    break
        except:
            raise LocalError('Running process failed')

        return out

def list_files(path, ext=None):

    f_list = []
    for root, dirnames, filenames in os.walk(path):
        if ext is None:
            for filename in filenames:
                f_list.append(os.path.join(root, filename))
        else:
            for filename in fnmatch.filter(filenames, '*.'+ext):
                f_list.append(os.path.join(root, filename))
    return f_list

class FakeSecHead(object):

    def __init__(self, fp):

        self.fp = fp
        self.sechead = '[ascection]\n'

    def readline(self):

        if self.sechead:
            try:
                return self.sechead
            finally:
                self.sechead = None
        else:
            return self.fp.readline()

class ErrorParser(object):
    """Inspect specific error string"""

    parsers = []

    def __init__(self):

        ErrorParser = {'GNU_LINKER':['(.*?):?\(\.\w+\+.*\): (.*)', \
                                     '(.*[/\\\])?ld(\.exe)?: (.*)'], \
                       'GNU_GCC':['(.*?):(\d+):(\d+:)? [Ee]rror: ([`\'"](.*)[\'"] undeclared .*)', \
                                  '(.*?):(\d+):(\d+:)? [Ee]rror: (conflicting types for .*[`\'"](.*)[\'"].*)', \
                                  '(.*?):(\d+):(\d+:)? (parse error before.*[`\'"](.*)[\'"].*)', \
                                  '(.*?):(\d+):(\d+:)?\s*(([Ee]rror)|(ERROR)): (.*)'], \
#                                  '(.*?):(\d+):(\d+:)? (.*)'], \
                       'GNU_GMAKE':['(.*):(\d*): (\*\*\* .*)', \
                                    '.*make.*: \*\*\* .*', \
                                    '.*make.*: Target (.*) not remade because of errors.', \
                                    '.*[Cc]ommand not found.*', \
                                    'Error:\s*(.*)'], \
                       'TIZEN_NATIVE':['.*ninja: build stopped.*', \
                                       'edje_cc: Error..(.*):(\d).*', \
                                       'edje_cc: Error.*']}

        for parser in ErrorParser:
            parser_env = os.getenv('SDK_ERROR_'+parser)
            if parser_env:
                self.parsers.append(parser_env)
            else:
                for msg in ErrorParser[parser]:
                    self.parsers.append(msg)

    def check(self, full_log):
        """Check error string line by line"""

        #snipset_text = full_log[:full_log.rfind('PLATFORM_VER\t')].split('\n')
        for line in full_log.split('\n'):
            errline = re.search('|'.join(self.parsers), line[:1024])
            if errline:
                return errline.string #Errors
        return None #No error

class _Rootstrap(object):
    """Tizen SDK rootstrap info.
       Used only in Sdk class"""

    rootstrap_list = None
    sdk_path = None

    def __init__(self, sdk_path=None, config=None, rootstrap_search=None):

        self.tizen = sdk_path
        self.list_rootstrap(rootstrap_search)
        self.config_file = config

    def list_rootstrap(self, rootstrap_search=None):
        """List all the rootstraps"""

        rs_prefix = 'mobile|wearable'
        if rootstrap_search is not None:
            rs_prefix = rootstrap_search
        print 'Set rs_prefix: %s' % rs_prefix

        if self.rootstrap_list != None:
            return self.rootstrap_list

        cmdline = self.tizen + ' list rootstrap'
        ret = Executor().run(cmdline, show=False)
        for x in ret.splitlines():
            if re.search('(%s)-(2.4|3.0|4.0|5.0)-(device|emulator|device64|emulator64).core.*' % rs_prefix, x):
                if self.rootstrap_list == None:
                    self.rootstrap_list = []
                self.rootstrap_list.append(x.split(' ')[0])
            else:
                print 'No search result for %s' % '(%s)-(2.4|3.0|4.0|5.0)-(device|emulator|device64|emulator64).core.*' % rs_prefix
        return self.rootstrap_list

    def check_rootstrap(self, rootstrap, show=True):
        """Specific rootstrap is in the SDK
           Otherwise use default"""

        if rootstrap == None:
            rootstrap = 'mobile-3.0-emulator.core' #default
        if rootstrap in self.rootstrap_list:
            return rootstrap
        else:
            if show == True:
                print '  ERROR: Rootstrap [%s] does not exist' % rootstrap
                print '  Update your rootstrap or use one of:\n    %s' \
                       % '\n    '.join(self.list_rootstrap())
            return None

class Sdk(object):
    """Tizen SDK related job"""

    rs = None #_Rootstrap class instance
    rootstrap_list = None
    sdk_to_search = ['tizen-studio/tools/ide/bin/tizen', \
                     'tizen-sdk/tools/ide/bin/tizen', \
                     'tizen-sdk-ux/tools/ide/bin/tizen', \
                     'tizen-sdk-cli/tools/ide/bin/tizen']

    def __init__(self, sdkpath=None, rootstrap_search=None):

        self.error_parser = ErrorParser()
        self.runtool = Executor(checker=self.error_parser)

        self.home = os.getenv('HOME')
        self.config_file = os.path.join(g_home, '.abs')

        if sdkpath is None:
            self.tizen = self.get_user_root()
            if self.tizen is None or self.tizen == '':
                for i in self.sdk_to_search:
                    if os.path.isfile(os.path.join(self.home, i)):
                        self.tizen = os.path.join(self.home, i)
                        break
        else:
            self.tizen = os.path.join(sdkpath, 'tools/ide/bin/tizen')
            self.update_user_root(self.tizen)

        if not os.path.isfile(self.tizen):
            print 'Cannot locate cli tool'
            raise LocalError('Fail to locate cli tool')

        self.rs = _Rootstrap(sdk_path=self.tizen, config=self.config_file, rootstrap_search=rootstrap_search)

    def get_user_root(self):

        if os.path.isfile(self.config_file):
            config = ConfigParser.RawConfigParser()
            config.read(self.config_file)
            return config.get('Global', 'tizen')
        return None

    def update_user_root(self, path):

        if not os.path.isfile(self.config_file):
            with open(self.config_file, 'w') as f:
                f.write('[Global]\n')
                f.write('tizen = %s\n' % path)
            return

        config = ConfigParser.RawConfigParser()
        config.read(self.config_file)
        config.set('Global', 'tizen', path)
        with open(self.config_file, 'wb') as cf:
            config.write(cf)

    def list_rootstrap(self):
        return self.rs.list_rootstrap()

    def check_rootstrap(self, rootstrap):
        return self.rs.check_rootstrap(rootstrap)

    def _run(self, command, args, show=True, checker=False):
        """Run a tizen command"""

        cmd = [self.tizen, command] + args
        print '\nRunning command:\n    %s' % ' '.join(cmd)
        return self.runtool.run(' '.join(cmd), show=show, checker=checker)

    def copytree2(self, src, dst, symlinks=False, ignore=None):
        """Copy with Ignore & Overwrite"""
        names = os.listdir(src)
        if ignore is not None:
            ignored_names = ignore(src, names)
        else:
            ignored_names = set()

        try:
            os.makedirs(dst)
        except:
            pass

        errors = []
        for name in names:
            if name in ignored_names:
                continue
            srcname = os.path.join(src, name)
            dstname = os.path.join(dst, name)
            try:
                if symlinks and os.path.islink(srcname):
                    linkto = os.readlink(srcname)
                    os.symlink(linkto, dstname)
                elif os.path.isdir(srcname):
                    self.copytree2(srcname, dstname, symlinks, ignore)
                else:
                    # Will raise a SpecialFileError for unsupported file types
                    shutil.copy2(srcname, dstname)
            # catch the Error from the recursive copytree so that we can
            # continue with other files
            except shutil.Error, err:
                errors.extend(err.args[0])
            except EnvironmentError, why:
                errors.append((srcname, dstname, str(why)))
        try:
            shutil.copystat(src, dst)
        except OSError, why:
            if WindowsError is not None and isinstance(why, WindowsError):
                # Copying file access times may fail on Windows
                pass
            else:
                errors.append((src, dst, str(why)))
        #if errors:
         #   raise shutil.Error, errors

    def _copy_build_output(self, src, dst):
        if not os.path.isdir(src) :
            return
        try:
            self.copytree2(src, dst, ignore=shutil.ignore_patterns('*.edc', '*.po', 'objs', '*.info', '*.so', 'CMakeLists.txt', '*.h', '*.c'))
        except OSError as exc:
            # File already exist
            if exc.errno == errno.EEXIST:
                shutil.copy(src, dst)
            if exc.errno == errno.ENOENT:
                shutil.copy(src, dst)
            else:
                raise

    def _package_sharedlib(self, project_path, conf, app_name):
        """If -r option used for packaging, make zip file from copied files"""
        #project_path=project['path']
        project_build_output_path=os.path.join(project_path, conf)
        package_path=os.path.join(project_build_output_path, '.pkg')

        if os.path.isdir(package_path):
            shutil.rmtree(package_path)
        os.makedirs(package_path)
        os.makedirs(os.path.join(package_path, 'lib'))

        #Copy project resource
        self._copy_build_output(os.path.join(project_path, 'lib'), os.path.join(package_path, 'lib'))
        self._copy_build_output(os.path.join(project_path, 'res'), os.path.join(package_path, 'res'))

        #Copy built res resource
        self._copy_build_output(os.path.join(project_build_output_path, 'res'), os.path.join(package_path, 'res'))

        #Copy so library file
        for filename in list_files(project_build_output_path, 'so'):
            shutil.copy(filename, os.path.join(package_path, 'lib'))

        # Copy so library file
        zipname=app_name + '.zip'
        rsrc_zip = os.path.join(project_build_output_path, zipname)
        myZipFile = zipfile.ZipFile(rsrc_zip, 'w')
        for filename in list_files(package_path):
            try:
                myZipFile.write(filename, filename.replace(package_path, ''))
            except Exception, e:
                print str(e)
        myZipFile.close()
        return rsrc_zip

    def build_tizen(self, source, rootstrap=None, arch=None, conf='Debug', jobs=None):
        """SDK CLI build command"""

        _rootstrap = self.check_rootstrap(rootstrap)
        if _rootstrap == None:
            raise LocalError('Rootstrap %s not exist' % rootstrap)

        if rootstrap is None and arch is None:
            rootstrap = _rootstrap
            self.arch = 'x86'
        elif arch is None:
            if 'emulator64' in rootstrap: self.arch = 'x86_64'
            elif 'device64' in rootstrap: self.arch = 'aarch64'
            elif 'emulator' in rootstrap: self.arch = 'x86'
            elif 'device' in rootstrap: self.arch = 'arm'
        elif rootstrap is None:
            if arch not in ['x86', 'arm', 'aarch64', 'x86_64']:
                raise LocalError('Architecture and rootstrap mismatch')

            rootstrap = _rootstrap
            if arch == 'x86_64': rootstrap = rootstrap.replace('emulator', 'emulator64')
            elif arch == 'aarch64': rootstrap = rootstrap.replace('emulator', 'device64')
            elif arch == 'arm': rootstrap = rootstrap.replace('emulator', 'device')

        for x in source.project_list:
            b_args = []
            if x['web_app'] == True:
                print '\n\n BUILD WEB\n'
                b_args.extend(['--', x['path']])
                out = self._run('build-web ', b_args, checker=True)
            else:
                print '\n\n BUILD NATIVE\n'
                if jobs is not None:
                    b_args.extend(['-j', jobs])
                b_args.extend(['-r', rootstrap, '-a', self.arch, '-C', conf, '-c', 'gcc'])
                b_args.extend(['--', x['path']])
                out = self._run('build-native', b_args, checker=True)
            logpath = os.path.join(source.output_dir, \
                                  'build_%s_%s' % (rootstrap, os.path.basename(x['path'])))
            if not os.path.isdir(source.output_dir):
                os.makedirs(source.output_dir)
            with open(logpath, 'w') as lf:
                lf.write(out)
            ret = self.error_parser.check(out)
            if True:
                with open(logpath+'.log', 'w') as lf:
                    lf.write(out)
            if ret:
                raise LocalError(ret)

    def package(self, source, cert=None, pkg_type=None, conf='Debug', manual_strip=False):
        """SDK CLI package command
            IF Debug + Manual Strip off then generate package-name-debug.tpk
            IF Debug + Manual Strip on then generate package-name.tpk with custom strip
            IF Release then generate package-name.tpk with strip option
        """
        if cert is None: cert = 'ABS'
        if pkg_type is None: pkg_type = 'tpk'
        if conf is None: conf = 'Debug'

        final_app = ''
        main_args = ['-t', pkg_type, '-s', cert]
        main_args_web = ['-t', 'wgt', '-s', cert]
        out = '' #logfile

        # remove tpk or zip file on project path
        package_list = []
        for i, x in enumerate(source.project_list):
            package_list.extend(list_files(os.path.join(x['path'], conf), ext='tpk'))
            package_list.extend(list_files(os.path.join(x['path'], conf), ext='zip'))
            package_list.extend(list_files(x['path'], ext='wgt'))

        for k in package_list :
            print ' package list ' + k;
            os.remove(k)

        # Manual strip
        if manual_strip == True :
            strip_cmd='';
            if self.arch == None:
                raise LocalError('Architecture is None')

            for i, x in enumerate(source.project_list):
                dir = os.path.join(x['path'], conf)
                if not os.path.isdir(dir):
                    continue
                files = [os.path.join(dir,f) for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f))]

                # dir must be "project/Debug directory"
                info_path = os.path.join(dir, "build.info")
                # Default Strip gcc version is 6.2
                gcc_version = "6.2"
                # Parsing GCC version from build.info inside Debug directory in Project to each project
                if os.path.exists(info_path) :
                    with open(info_path) as fp :
                        for line in fp :
                            if line.startswith("toolchain=") :
                                line = line.strip()
                                gcc_version = re.findall("\d+\.\d+", line)[0]
                else :
                    print "Cannot find Debug/build.info. The default gcc will strip tpk"

                print "gcc version:" + gcc_version

                if self.arch == 'x86' :
                    if(gcc_version == "4.9"):
                        strip_cmd = os.path.join(os.path.dirname(self.tizen), '../../i386-linux-gnueabi-gcc-' + gcc_version + '/bin/i386-linux-gnueabi-strip')
                    else:
                        strip_cmd = os.path.join(os.path.dirname(self.tizen), '../../i586-linux-gnueabi-gcc-' + gcc_version + '/bin/i586-linux-gnueabi-strip')
                elif self.arch == 'arm' :
                    strip_cmd = os.path.join(os.path.dirname(self.tizen), '../../arm-linux-gnueabi-gcc-' + gcc_version + '/bin/arm-linux-gnueabi-strip')
                elif self.arch == 'x86_64' :
                    strip_cmd = os.path.join(os.path.dirname(self.tizen), '../../x86_64-linux-gnu-gcc-' + gcc_version + '/bin/x86_64-linux-gnu-strip')
                elif self.arch == 'aarch64' :
                    strip_cmd = os.path.join(os.path.dirname(self.tizen), '../../aarch64-linux-gnu-gcc-' + gcc_version + '/bin/aarch64-linux-gnu-strip')

                print strip_cmd

                for k in files:
                    cmdline = strip_cmd + ' ' + k;
                    Executor().run(cmdline, show=False)

        elif conf == 'Release':
            main_args.extend(['--strip', 'on'])

        for i, x in enumerate(source.project_list):
            if x['web_app'] == False:
                if x['type'] == 'app':
                    print '\n\n PACKAGE NATIVE\n'
                    out = '%s\n%s' % (out, \
                          self._run('package', main_args + ['--',os.path.join(x['path'],conf)]))
                    try:
                        final_app = list_files(os.path.join(x['path'], conf), ext='tpk')[0]
                    except:
                        raise LocalError('TPK file not generated for %s.' % x['APPNAME'])
                    x['out_package'] = final_app
                elif x['type'] == 'sharedLib':
                    self._package_sharedlib(x['path'], conf, x['APPNAME'])
                    x['out_package'] = list_files(os.path.join(x['path'], conf), ext='zip')[0]
                else:
                    raise LocalError('Not supported project type %s' % x['type'])
            elif x['web_app'] == True:
                print '\n\n PACKAGE WEB\n'
                out = '%s\n%s' % (out, \
                      self._run('package', main_args_web + ['--', os.path.join(x['path'], '.buildResult')]))
                try:
                    final_app = list_files(os.path.join(x['path'], '.buildResult'), ext='wgt')[0]
                except:
                    raise LocalError('WGT file not generated for %s.' % x['APPNAME'])
                x['out_package'] = final_app

        if source.b_multi == True:
            extra_args=[]
            print 'THIS IS MULTI PROJECT'
            for i, x in enumerate(source.project_list):
                if x['out_package'] != final_app and x.get('type') == 'app':
                    extra_args.extend(['-r', '"%s"' % x['out_package']])
                elif x.get('type') == 'sharedLib':
                    extra_args.extend(['-r', '"%s"' % x['out_package']])

            extra_args.extend(['--', '"%s"' % final_app])
            if final_app.endswith('.tpk'):
                out = self._run('package', main_args + extra_args)
            elif final_app.endswith('.wgt'):
                out = self._run('package', main_args_web + extra_args)

        #TODO: signature validation check failed : Invalid file reference. An unsigned file was found.
        if final_app.endswith('.tpk'):
            print 'Packaging final step again!'
            out = self._run('package', main_args + ['--', '"%s"' % final_app])

        #Append arch to web binary
        if final_app.endswith('.wgt'):
            final_app_with_arch = final_app.replace('.wgt', '-%s.wgt' % self.arch)
            os.rename(final_app, final_app_with_arch)
            final_app = final_app_with_arch

        #Copy tpk to output directory
        if conf == 'Debug' and manual_strip == False :
            basename = os.path.splitext(final_app)[0]
            if final_app.endswith('.tpk'):
                newname = basename +'-debug.tpk'
            elif final_app.endswith('.wgt'):
                newname = basename +'-debug.wgt'
            os.rename(final_app, newname)
            shutil.copy(newname, source.output_dir)
        else :
            shutil.copy(final_app, source.output_dir)

    def clean(self, source):
        """SDK CLI clean command"""

        if os.path.isdir(source.multizip_path):
            shutil.rmtree(source.multizip_path)

        if os.path.isfile(os.path.join(source.multizip_path, '.zip')):
            os.remove(os.path.join(source.multizip_path, '.zip'))

        for x in source.project_list:
            self._run('clean', ['--', x['path']], show=False)

class Source(object):
    """Project source related job"""

    workspace = '' #Project root directory
    project_list = []
    b_multi = False
    multi_conf_file = 'WORKSPACE' #Assume multi-project if this file exist.
    multizip_path = '' #For multi-project packaging -r option
    property_dict = {}
    output_dir = '_abs_out_'

    def __init__(self, src=None):

        if src == None:
            self.workspace = os.getcwd()
        else:
            self.workspace = os.path.abspath(src)
        self.output_dir = os.path.join(self.workspace, self.output_dir)

        os.environ['workspace_loc']=str(os.path.realpath(self.workspace))

        self.multizip_path = os.path.join(self.workspace, 'multizip')
        self.pre_process()

    def set_properties(self, path):
        """Fetch all properties from project_def.prop"""

        mydict = {}
        cp = ConfigParser.SafeConfigParser()
        cp.optionxform = str
        if self.is_web_app(path):
            mydict['web_app'] = True
        else:
            mydict['web_app'] = False
            cp.readfp(FakeSecHead(open(os.path.join(path, 'project_def.prop'))))
            for x in cp.items('ascection'):
                mydict[x[0]] = x[1]
        mydict['path'] = path
        return mydict

    def set_user_options(self, c_opts=None, cpp_opts=None, link_opts=None):
        if c_opts is not None:
            os.environ['USER_C_OPTS'] = c_opts
            print 'Set USER_C_OPTS=[%s]' % os.getenv('USER_C_OPTS')
        if cpp_opts is not None:
            os.environ['USER_CPP_OPTS'] = cpp_opts
            print 'Set USER_CPP_OPTS=[%s]' % os.getenv('USER_CPP_OPTS')
        if link_opts is not None:
            os.environ['USER_LINK_OPTS'] = link_opts
            print 'Set USER_LINK_OPTS=[%s]' % os.getenv('USER_LINK_OPTS')

    def is_web_app(self, project_directory):
        if os.path.isfile(os.path.join(project_directory, 'config.xml')):
            return True
        return False

    def pre_process(self):

        if os.path.isfile(os.path.join(self.workspace, self.multi_conf_file)):
            self.b_multi = True
            with open(os.path.join(self.workspace, self.multi_conf_file)) as f:
                for line in f:
                    if not line.strip():
                        continue
                    file_path = os.path.join(self.workspace, line.rstrip())
                    self.project_list.append(self.set_properties(file_path))
        else:
            self.b_multi = False
            file_path = os.path.join(self.workspace)
            self.project_list.append(self.set_properties(file_path))

def argument_parsing(argv):
    """Any arguments passed from user"""

    parser = argparse.ArgumentParser(description='ABS command line interface')

    subparsers = parser.add_subparsers(dest='subcommands')

    #### [subcommand - BUILD] ####
    build = subparsers.add_parser('build')
    build.add_argument('-w', '--workspace', action='store', dest='workspace', \
                        help='source directory')
    build.add_argument('-r', '--rootstrap', action='store', dest='rootstrap', \
                        help='(ex, mobile-3.0-device.core) rootstrap name')
    build.add_argument('-a', '--arch', action='store', dest='arch', \
                        help='(x86|arm|x86_64|aarch64) Architecture to build')
    build.add_argument('-t', '--type', action='store', dest='type', \
                        help='(tpk|wgt) Packaging type')
    build.add_argument('-s', '--cert', action='store', dest='cert', \
                        help='(ex, ABS) Certificate profile name')
    build.add_argument('-c', '--conf', action='store',default='Release', dest='conf', \
                        help='(ex, Debug|Release) Build Configuration')
    build.add_argument('-j', '--jobs', action='store', dest='jobs', \
                        help='(number of jobs) The number of parallel builds')
    build.add_argument('--sdkpath', action='store', dest='sdkpath', \
                        help='Specify Tizen SDK installation root (one time init).' \
                             ' ex) /home/yours/tizen-sdk/')
    build.add_argument('--profile-to-search', action='store', dest='profiletosearch', \
                        help='Rootstrap profile prefix.' \
                             ' ex) (mobile|wearable|da-hfp)')
    build.add_argument('--c-opts', action='store', dest='c_opts', \
                        help='Extra compile options USER_C_OPTS')
    build.add_argument('--cpp-opts', action='store', dest='cpp_opts', \
                        help='Extra compile options USER_CPP_OPTS')
    build.add_argument('--link-opts', action='store', dest='link_opts', \
                        help='Extra linking options USER_LINK_OPTS')

    return parser.parse_args(argv[1:])

def build_main(args):
    """Command [build] entry point."""

    try:
        my_source = Source(src=args.workspace)

        my_source.set_user_options(c_opts=args.c_opts, cpp_opts=args.cpp_opts, link_opts=args.link_opts)
        print '-------------------'
        print '(%s)' % args.profiletosearch
        print '-------------------'
        my_sdk = Sdk(sdkpath=args.sdkpath, rootstrap_search=args.profiletosearch)
        my_sdk.clean(my_source)
        my_sdk.build_tizen(my_source, rootstrap=args.rootstrap, arch=args.arch, jobs=args.jobs)
        if args.conf == 'Debug' :
            my_sdk.package(my_source, pkg_type=args.type, cert=args.cert)
            my_sdk.package(my_source, pkg_type=args.type, cert=args.cert, manual_strip=True)
        else :
            my_sdk.package(my_source, pkg_type=args.type, cert=args.cert, manual_strip=True)

    except Exception as err:
        wrk = os.path.join(os.path.abspath(args.workspace), '_abs_out_')
        if not os.path.isdir(wrk):
            os.makedirs(wrk)
        with open(os.path.join(wrk, 'build_EXCEPTION.log'), 'w') as ef:
            ef.write('Exception %s' % str(err))
        raise err

def main(argv):
    """Script entry point."""

    args = argument_parsing(argv)

    if args.subcommands == 'build':
        return build_main(args)
    else:
        print 'Unsupported command %s' % args.subcommands
        raise LocalError('Command %s not supported' % args.subcommands)

if __name__ == '__main__':

    try:
        sys.exit(main(sys.argv))
    except Exception, e:
        print 'Exception %s' % str(e)
        #FIXME: Remove hard-coded output directory.
        if not os.path.isdir('_abs_out_'):
            os.makedirs('_abs_out_')
        with open(os.path.join('_abs_out_', 'build_EXCEPTION.log'), 'w') as ef:
            ef.write('Exception %s' % repr(e))
        sys.exit(1)