Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / native_client_sdk / src / build_tools / parse_dsc.py
1 #!/usr/bin/env python
2 # Copyright (c) 2013 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 import collections
7 import fnmatch
8 import optparse
9 import os
10 import sys
11
12 VALID_TOOLCHAINS = [
13   'bionic',
14   'newlib',
15   'glibc',
16   'pnacl',
17   'win',
18   'linux',
19   'mac',
20 ]
21
22 # 'KEY' : ( <TYPE>, [Accepted Values], <Required?>)
23 DSC_FORMAT = {
24     'DISABLE': (bool, [True, False], False),
25     'SEL_LDR': (bool, [True, False], False),
26     # Disable this project from being included in the NaCl packaged app.
27     'DISABLE_PACKAGE': (bool, [True, False], False),
28     # Don't generate the additional files to allow this project to run as a
29     # packaged app (i.e. manifest.json, background.js, etc.).
30     'NO_PACKAGE_FILES': (bool, [True, False], False),
31     'TOOLS' : (list, VALID_TOOLCHAINS, True),
32     'CONFIGS' : (list, ['Debug', 'Release'], False),
33     'PREREQ' : (list, '', False),
34     'TARGETS' : (list, {
35         'NAME': (str, '', True),
36         # main = nexe target
37         # lib = library target
38         # so = shared object target, automatically added to NMF
39         # so-standalone =  shared object target, not put into NMF
40         'TYPE': (str, ['main', 'lib', 'static-lib', 'so', 'so-standalone'],
41                  True),
42         'SOURCES': (list, '', True),
43         'CFLAGS': (list, '', False),
44         'CFLAGS_GCC': (list, '', False),
45         'CXXFLAGS': (list, '', False),
46         'DEFINES': (list, '', False),
47         'LDFLAGS': (list, '', False),
48         'INCLUDES': (list, '', False),
49         'LIBS' : (dict, VALID_TOOLCHAINS, False),
50         'DEPS' : (list, '', False)
51     }, False),
52     'HEADERS': (list, {
53         'FILES': (list, '', True),
54         'DEST': (str, '', True),
55     }, False),
56     'SEARCH': (list, '', False),
57     'POST': (str, '', False),
58     'PRE': (str, '', False),
59     'DEST': (str, ['getting_started', 'examples/api',
60                    'examples/demo', 'examples/tutorial',
61                    'src', 'tests'], True),
62     'NAME': (str, '', False),
63     'DATA': (list, '', False),
64     'TITLE': (str, '', False),
65     'GROUP': (str, '', False),
66     'EXPERIMENTAL': (bool, [True, False], False),
67     'PERMISSIONS': (list, '', False),
68     'SOCKET_PERMISSIONS': (list, '', False)
69 }
70
71
72 class ValidationError(Exception):
73   pass
74
75
76 def ValidateFormat(src, dsc_format):
77   # Verify all required keys are there
78   for key in dsc_format:
79     exp_type, exp_value, required = dsc_format[key]
80     if required and key not in src:
81       raise ValidationError('Missing required key %s.' % key)
82
83   # For each provided key, verify it's valid
84   for key in src:
85     # Verify the key is known
86     if key not in dsc_format:
87       raise ValidationError('Unexpected key %s.' % key)
88
89     exp_type, exp_value, required = dsc_format[key]
90     value = src[key]
91
92     # Verify the value is non-empty if required
93     if required and not value:
94       raise ValidationError('Expected non-empty value for %s.' % key)
95
96     # If the expected type is a dict, but the provided type is a list
97     # then the list applies to all keys of the dictionary, so we reset
98     # the expected type and value.
99     if exp_type is dict:
100       if type(value) is list:
101         exp_type = list
102         exp_value = ''
103
104     # Verify the key is of the expected type
105     if exp_type != type(value):
106       raise ValidationError('Key %s expects %s not %s.' % (
107           key, exp_type.__name__.upper(), type(value).__name__.upper()))
108
109     # If it's a bool, the expected values are always True or False.
110     if exp_type is bool:
111       continue
112
113     # If it's a string and there are expected values, make sure it matches
114     if exp_type is str:
115       if type(exp_value) is list and exp_value:
116         if value not in exp_value:
117           raise ValidationError("Value '%s' not expected for %s." %
118                                 (value, key))
119       continue
120
121     # if it's a list, then we need to validate the values
122     if exp_type is list:
123       # If we expect a dictionary, then call this recursively
124       if type(exp_value) is dict:
125         for val in value:
126           ValidateFormat(val, exp_value)
127         continue
128       # If we expect a list of strings
129       if type(exp_value) is str:
130         for val in value:
131           if type(val) is not str:
132             raise ValidationError('Value %s in %s is not a string.' %
133                                   (val, key))
134         continue
135       # if we expect a particular string
136       if type(exp_value) is list:
137         for val in value:
138           if val not in exp_value:
139             raise ValidationError('Value %s not expected in %s.' %
140                                   (val, key))
141         continue
142
143     # if we are expecting a dict, verify the keys are allowed
144     if exp_type is dict:
145       print "Expecting dict\n"
146       for sub in value:
147         if sub not in exp_value:
148           raise ValidationError('Sub key %s not expected in %s.' %
149                                 (sub, key))
150       continue
151
152     # If we got this far, it's an unexpected type
153     raise ValidationError('Unexpected type %s for key %s.' %
154                           (str(type(src[key])), key))
155
156
157 def LoadProject(filename):
158   with open(filename, 'r') as descfile:
159     try:
160       desc = eval(descfile.read(), {}, {})
161     except Exception as e:
162       raise ValidationError(e)
163   if desc.get('DISABLE', False):
164     return None
165   ValidateFormat(desc, DSC_FORMAT)
166   desc['FILEPATH'] = os.path.abspath(filename)
167   return desc
168
169
170 def LoadProjectTreeUnfiltered(srcpath):
171   # Build the tree
172   out = collections.defaultdict(list)
173   for root, _, files in os.walk(srcpath):
174     for filename in files:
175       if fnmatch.fnmatch(filename, '*.dsc'):
176         filepath = os.path.join(root, filename)
177         try:
178           desc = LoadProject(filepath)
179         except ValidationError as e:
180           raise ValidationError("Failed to validate: %s: %s" % (filepath, e))
181         if desc:
182           key = desc['DEST']
183           out[key].append(desc)
184   return out
185
186
187 def LoadProjectTree(srcpath, include, exclude=None):
188   out = LoadProjectTreeUnfiltered(srcpath)
189   return FilterTree(out, MakeDefaultFilterFn(include, exclude))
190
191
192 def GenerateProjects(tree):
193   for key in tree:
194     for val in tree[key]:
195       yield key, val
196
197
198 def FilterTree(tree, filter_fn):
199   out = collections.defaultdict(list)
200   for branch, desc in GenerateProjects(tree):
201     if filter_fn(desc):
202       out[branch].append(desc)
203   return out
204
205
206 def MakeDefaultFilterFn(include, exclude):
207   def DefaultFilterFn(desc):
208     matches_include = not include or DescMatchesFilter(desc, include)
209     matches_exclude = exclude and DescMatchesFilter(desc, exclude)
210
211     # Exclude list overrides include list.
212     if matches_exclude:
213       return False
214     return matches_include
215
216   return DefaultFilterFn
217
218
219 def DescMatchesFilter(desc, filters):
220   for key, expected in filters.iteritems():
221     # For any filtered key which is unspecified, assumed False
222     value = desc.get(key, False)
223
224     # If we provide an expected list, match at least one
225     if type(expected) != list:
226       expected = set([expected])
227     if type(value) != list:
228       value = set([value])
229
230     if not set(expected) & set(value):
231       return False
232
233   # If we fall through, then we matched the filters
234   return True
235
236
237 def PrintProjectTree(tree):
238   for key in tree:
239     print key + ':'
240     for val in tree[key]:
241       print '\t' + val['NAME']
242
243
244 def main(argv):
245   parser = optparse.OptionParser(usage='%prog [options] <dir>')
246   parser.add_option('-e', '--experimental',
247       help='build experimental examples and libraries', action='store_true')
248   parser.add_option('-t', '--toolchain',
249       help='Build using toolchain. Can be passed more than once.',
250       action='append')
251
252   options, args = parser.parse_args(argv[1:])
253   filters = {}
254
255   load_from_dir = '.'
256   if len(args) > 1:
257     parser.error('Expected 0 or 1 args, got %d.' % len(args))
258
259   if args:
260     load_from_dir = args[0]
261
262   if options.toolchain:
263     filters['TOOLS'] = options.toolchain
264
265   if not options.experimental:
266     filters['EXPERIMENTAL'] = False
267
268   try:
269     tree = LoadProjectTree(load_from_dir, include=filters)
270   except ValidationError as e:
271     sys.stderr.write(str(e) + '\n')
272     return 1
273
274   PrintProjectTree(tree)
275   return 0
276
277
278 if __name__ == '__main__':
279   sys.exit(main(sys.argv))