1 # Copyright (C) 2013 Google Inc. All rights reserved.
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
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
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.
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.
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.
38 # name1 arg=value, arg2=value2, arg2=value3
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
44 # Bare arguments (no '=') are treated as names with value True.
45 # The first field will always be labeled 'name'.
47 # InFile.load_from_files(['file.in'], {'arg': None, 'arg2': []})
49 # Parsing produces an array of dictionaries:
50 # [ { 'name' : 'name1', 'arg' :' value', arg2=['value2', 'value3'] }
52 def _is_comment(line):
53 return line.startswith("//") or line.startswith("#")
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))
64 def load_from_files(self, file_paths, defaults, valid_values, default_parameters):
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)
72 def _is_sequence(self, arg):
73 return (not hasattr(arg, "strip")
74 and hasattr(arg, "__getitem__")
75 or hasattr(arg, "__iter__"))
77 def _parse(self, lines):
78 parsing_parameters = True
84 parsing_parameters = False
86 if parsing_parameters:
87 self._parse_parameter(line)
89 entry = self._parse_line(line)
92 entry = self._merge_entries(entry, self.name_dictionaries[indices[name]])
94 self.name_dictionaries[indices[name]] = entry
96 indices[name] = len(self.name_dictionaries)
97 self.name_dictionaries.append(entry)
100 def _merge_entries(self, one, two):
104 self._fatal("Expected key '%s' not found in entry: %s" % (key, two))
105 if one[key] and 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
115 val = [val_one, val_two]
118 merged[key] = one[key]
120 merged[key] = two[key]
124 def _parse_parameter(self, line):
126 name, value = line.split('=')
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
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
143 if '=' in arg_string:
144 arg_name, arg_value = arg_string.split('=')
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)
155 args[arg_name] = arg_value
158 def _fatal(self, message):
159 # FIXME: This should probably raise instead of exit(1)