Pepper: TempFile cleanup.
[chromium-blink-merge.git] / build / gypi_to_gn.py
blob3d5b89916dccf2df856891975487a7d26463e43a
1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Converts a given gypi file to a python scope and writes the result to stdout.
7 It is assumed that the file contains a toplevel dictionary, and this script
8 will return that dictionary as a GN "scope" (see example below). This script
9 does not know anything about GYP and it will not expand variables or execute
10 conditions.
12 It will strip conditions blocks.
14 A variables block at the top level will be flattened so that the variables
15 appear in the root dictionary. This way they can be returned to the GN code.
17 Say your_file.gypi looked like this:
19 'sources': [ 'a.cc', 'b.cc' ],
20 'defines': [ 'ENABLE_DOOM_MELON' ],
23 You would call it like this:
24 gypi_values = exec_script("//build/gypi_to_gn.py",
25 [ rebase_path("your_file.gypi") ],
26 "scope",
27 [ "your_file.gypi" ])
29 Notes:
30 - The rebase_path call converts the gypi file from being relative to the
31 current build file to being system absolute for calling the script, which
32 will have a different current directory than this file.
34 - The "scope" parameter tells GN to interpret the result as a series of GN
35 variable assignments.
37 - The last file argument to exec_script tells GN that the given file is a
38 dependency of the build so Ninja can automatically re-run GN if the file
39 changes.
41 Read the values into a target like this:
42 component("mycomponent") {
43 sources = gypi_values.sources
44 defines = gypi_values.defines
47 Sometimes your .gypi file will include paths relative to a different
48 directory than the current .gn file. In this case, you can rebase them to
49 be relative to the current directory.
50 sources = rebase_path(gypi_values.sources, ".",
51 "//path/gypi/input/values/are/relative/to")
53 This script will tolerate a 'variables' in the toplevel dictionary or not. If
54 the toplevel dictionary just contains one item called 'variables', it will be
55 collapsed away and the result will be the contents of that dictinoary. Some
56 .gypi files are written with or without this, depending on how they expect to
57 be embedded into a .gyp file.
59 This script also has the ability to replace certain substrings in the input.
60 Generally this is used to emulate GYP variable expansion. If you passed the
61 argument "--replace=<(foo)=bar" then all instances of "<(foo)" in strings in
62 the input will be replaced with "bar":
64 gypi_values = exec_script("//build/gypi_to_gn.py",
65 [ rebase_path("your_file.gypi"),
66 "--replace=<(foo)=bar"],
67 "scope",
68 [ "your_file.gypi" ])
70 """
72 import gn_helpers
73 from optparse import OptionParser
74 import sys
76 def LoadPythonDictionary(path):
77 file_string = open(path).read()
78 try:
79 file_data = eval(file_string, {'__builtins__': None}, None)
80 except SyntaxError, e:
81 e.filename = path
82 raise
83 except Exception, e:
84 raise Exception("Unexpected error while reading %s: %s" % (path, str(e)))
86 assert isinstance(file_data, dict), "%s does not eval to a dictionary" % path
88 # Strip any conditions.
89 if 'conditions' in file_data:
90 del file_data['conditions']
91 if 'target_conditions' in file_data:
92 del file_data['target_conditions']
94 # Flatten any varaiables to the top level.
95 if 'variables' in file_data:
96 file_data.update(file_data['variables'])
97 del file_data['variables']
99 # If the contents of the root is a dictionary with exactly one kee
100 # "variables", promote the contents of that to the top level. Some .gypi
101 # files contain this and some don't depending on how they expect to be
102 # embedded in a .gyp file. We don't actually care either way so collapse it
103 # away.
104 if len(file_data) == 1 and 'variables' in file_data:
105 return file_data['variables']
107 return file_data
110 def ReplaceSubstrings(values, search_for, replace_with):
111 """Recursively replaces substrings in a value.
113 Replaces all substrings of the "search_for" with "repace_with" for all
114 strings occurring in "values". This is done by recursively iterating into
115 lists as well as the keys and values of dictionaries."""
116 if isinstance(values, str):
117 return values.replace(search_for, replace_with)
119 if isinstance(values, list):
120 return [ReplaceSubstrings(v, search_for, replace_with) for v in values]
122 if isinstance(values, dict):
123 # For dictionaries, do the search for both the key and values.
124 result = {}
125 for key, value in values.items():
126 new_key = ReplaceSubstrings(key, search_for, replace_with)
127 new_value = ReplaceSubstrings(value, search_for, replace_with)
128 result[new_key] = new_value
129 return result
131 # Assume everything else is unchanged.
132 return values
134 def main():
135 parser = OptionParser()
136 parser.add_option("-r", "--replace", action="append",
137 help="Replaces substrings. If passed a=b, replaces all substrs a with b.")
138 (options, args) = parser.parse_args()
140 if len(args) != 1:
141 raise Exception("Need one argument which is the .gypi file to read.")
143 data = LoadPythonDictionary(args[0])
144 if options.replace:
145 # Do replacements for all specified patterns.
146 for replace in options.replace:
147 split = replace.split('=')
148 # Allow "foo=" to replace with nothing.
149 if len(split) == 1:
150 split.append('')
151 assert len(split) == 2, "Replacement must be of the form 'key=value'."
152 data = ReplaceSubstrings(data, split[0], split[1])
154 print gn_helpers.ToGNString(data)
156 if __name__ == '__main__':
157 try:
158 main()
159 except Exception, e:
160 print str(e)
161 sys.exit(1)