2 # Copyright 2014 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.
10 IMPORT_TEMPLATE = '<import src="/%s.sky" as="%s" />'
11 PREAMBLE_TEMPLATE = '<script>'
12 POSTAMBLE_TEMPLATE = ' module.exports = exports;\n</script>'
15 def __init__(self, path, name):
25 def Serialize(module):
27 for i in module.imports:
28 lines.append(IMPORT_TEMPLATE % (i.path, i.name))
29 lines.append(PREAMBLE_TEMPLATE)
30 lines.append(module.body)
31 lines.append(POSTAMBLE_TEMPLATE)
32 return "\n".join(lines)
34 name_regex = re.compile(r'define\("([^"]+)"')
35 import_regex = re.compile(r' +"([^"]+)",')
36 begin_body_regexp = re.compile(r', function\(([^)]*)\)')
37 end_body_regexp = re.compile(r'return exports')
39 def AddImportNames(module, unparsed_names):
40 names = [n.strip() for n in unparsed_names.split(',')]
41 for i in range(len(module.imports)):
42 module.imports[i].name = names[i]
44 def RewritePathNames(path):
45 return path.replace("mojo/public/js", "mojo/public/sky")
47 def Parse(amd_module):
51 for line in amd_module.splitlines():
53 m = name_regex.search(line)
55 module.name = m.group(1)
56 m = begin_body_regexp.search(line)
58 AddImportNames(module, m.group(1))
63 if state == "imports":
64 m = import_regex.search(line)
66 module.imports.append(Import(RewritePathNames(m.group(1)), None))
68 m = begin_body_regexp.search(line)
70 AddImportNames(module, m.group(1))
73 raise Exception, "Unknown import declaration:" + line
75 if end_body_regexp.search(line):
76 module.body = "\n".join(body_lines)
78 body_lines.append(line)
80 raise Exception, "Unknown parser state"
81 raise Exception, "End of file reached with finding a module"
84 parser = argparse.ArgumentParser()
85 parser.add_argument("--input")
86 parser.add_argument("--output")
87 args = parser.parse_args()
90 with open(args.input, "r") as input_file:
91 module = Parse(input_file.read())
93 with open(args.output, "w+") as output_file:
94 output_file.write(Serialize(module))
98 if __name__ == "__main__":