Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / build / scripts / in_file.py
1 # Copyright (C) 2013 Google Inc. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
5 # met:
6 #
7 #     * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 #     * Redistributions in binary form must reproduce the above
10 # copyright notice, this list of conditions and the following disclaimer
11 # in the documentation and/or other materials provided with the
12 # distribution.
13 #     * Neither the name of Google Inc. nor the names of its
14 # contributors may be used to endorse or promote products derived from
15 # this software without specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 import copy
30 import os
31
32 # NOTE: This has only been used to parse
33 # core/page/RuntimeEnabledFeatures.in and may not be capable
34 # of parsing other .in files correctly.
35
36 # .in file format is:
37 # // comment
38 # name1 arg=value, arg2=value2, arg2=value3
39 #
40 # InFile must be passed a dictionary of default values
41 # with which to validate arguments against known names.
42 # Sequence types as default values will produce sequences
43 # as parse results.
44 # Bare arguments (no '=') are treated as names with value True.
45 # The first field will always be labeled 'name'.
46 #
47 # InFile.load_from_files(['file.in'], {'arg': None, 'arg2': []})
48 #
49 # Parsing produces an array of dictionaries:
50 # [ { 'name' : 'name1', 'arg' :' value', arg2=['value2', 'value3'] }
51
52 def _is_comment(line):
53     return line.startswith("//") or line.startswith("#")
54
55 class InFile(object):
56     def __init__(self, lines, defaults, valid_values=None, default_parameters=None):
57         self.name_dictionaries = []
58         self.parameters = copy.deepcopy(default_parameters if default_parameters else {})
59         self._defaults = defaults
60         self._valid_values = copy.deepcopy(valid_values if valid_values else {})
61         self._parse(map(str.strip, lines))
62
63     @classmethod
64     def load_from_files(self, file_paths, defaults, valid_values, default_parameters):
65         lines = []
66         for path in file_paths:
67             assert path.endswith(".in")
68             with open(os.path.abspath(path)) as in_file:
69                 lines += in_file.readlines()
70         return InFile(lines, defaults, valid_values, default_parameters)
71
72     def _is_sequence(self, arg):
73         return (not hasattr(arg, "strip")
74                 and hasattr(arg, "__getitem__")
75                 or hasattr(arg, "__iter__"))
76
77     def _parse(self, lines):
78         parsing_parameters = True
79         indices = {}
80         for line in lines:
81             if _is_comment(line):
82                 continue
83             if not line:
84                 parsing_parameters = False
85                 continue
86             if parsing_parameters:
87                 self._parse_parameter(line)
88             else:
89                 entry = self._parse_line(line)
90                 name = entry['name']
91                 if name in indices:
92                     entry = self._merge_entries(entry, self.name_dictionaries[indices[name]])
93                     entry['name'] = name
94                     self.name_dictionaries[indices[name]] = entry
95                 else:
96                     indices[name] = len(self.name_dictionaries)
97                     self.name_dictionaries.append(entry)
98
99
100     def _merge_entries(self, one, two):
101         merged = {}
102         for key in one:
103             if key not in two:
104                 self._fatal("Expected key '%s' not found in entry: %s" % (key, two))
105             if one[key] and two[key]:
106                 val_one = one[key]
107                 val_two = two[key]
108                 if isinstance(val_one, list) and isinstance(val_two, list):
109                     val = val_one + val_two
110                 elif isinstance(val_one, list):
111                     val = val_one + [val_two]
112                 elif isinstance(val_two, list):
113                     val = [val_one] + val_two
114                 else:
115                     val = [val_one, val_two]
116                 merged[key] = val
117             elif one[key]:
118                 merged[key] = one[key]
119             else:
120                 merged[key] = two[key]
121         return merged
122
123
124     def _parse_parameter(self, line):
125         if '=' in line:
126             name, value = line.split('=')
127         else:
128             name, value = line, True
129         if not name in self.parameters:
130             self._fatal("Unknown parameter: '%s' in line:\n%s\nKnown parameters: %s" % (name, line, self.parameters.keys()))
131         self.parameters[name] = value
132
133     def _parse_line(self, line):
134         args = copy.deepcopy(self._defaults)
135         parts = line.split(' ')
136         args['name'] = parts[0]
137         # re-join the rest of the line and split on ','
138         args_list = ' '.join(parts[1:]).strip().split(',')
139         for arg_string in args_list:
140             arg_string = arg_string.strip()
141             if not arg_string: # Ignore empty args
142                 continue
143             if '=' in arg_string:
144                 arg_name, arg_value = arg_string.split('=')
145             else:
146                 arg_name, arg_value = arg_string, True
147             if arg_name not in self._defaults:
148                 self._fatal("Unknown argument: '%s' in line:\n%s\nKnown arguments: %s" % (arg_name, line, self._defaults.keys()))
149             valid_values = self._valid_values.get(arg_name)
150             if valid_values and arg_value not in valid_values:
151                 self._fatal("Unknown value: '%s' in line:\n%s\nKnown values: %s" % (arg_value, line, valid_values))
152             if self._is_sequence(args[arg_name]):
153                 args[arg_name].append(arg_value)
154             else:
155                 args[arg_name] = arg_value
156         return args
157
158     def _fatal(self, message):
159         # FIXME: This should probably raise instead of exit(1)
160         print message
161         exit(1)