-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsoy2js.py
executable file
·63 lines (58 loc) · 2.25 KB
/
soy2js.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
import sys
import subprocess
import re
import os
def run(input_file, cp_dir):
intermediate_file = input_file + ".bare.js"
output_file = input_file + ".js"
d_ts_file = input_file + ".d.ts";
ret = subprocess.call(
["java", "-jar", "{0}/tools/SoyToJsSrcCompiler.jar".format(cp_dir), "--shouldProvideRequireSoyNamespaces",
"--shouldDeclareTopLevelNamespaces", "--shouldGenerateJsdoc", "--outputPathFormat",
intermediate_file, input_file])
inp = open(intermediate_file, 'r')
inp_lines = inp.readlines()
inp.close()
os.unlink(intermediate_file)
d_ts = []
out_lines = []
package = None
for line in inp_lines:
match = re.match(r'goog.provide\(\'([^\']*)\'\)', line)
if match:
package = match.group(1)
line = "define(['require','exports','lib/soyutils'],function(require,exports,soy){{\n var {0}= {0} ? {0} : {{}};".format(
package)
need_close = True
if re.match(r'goog.require', line):
line = ''
match_fn = re.match(r'^(.*)\.(.*)= function\(opt_data, opt_sb\)', line)
if match_fn:
package_name = match_fn.group(1).strip()
function_name = match_fn.group(2).strip()
d_ts.append(function_name)
out_lines.append(line)
if package is not None:
match = re.match(r'^([^\.]+)', package)
if match:
package = match.group(1)
out_lines.append('for(var i in {0}) {{ exports[i] = {0}[i] }};\n'.format(package))
out_lines.append("});\n")
out = open(output_file, 'w')
out.writelines(out_lines)
out.close()
d_ts_out = ['// Autogenerated from .soy file by soy2js\n']
match = re.match(r'.*src/(.*)$', input_file)
if match:
d_ts_out.append("declare module \"{0}\" {{\n".format(match.group(1)))
for d in d_ts:
d_ts_out.append("\tfunction {0}(state:any):any;\n".format(d))
d_ts_out.append("}\n")
for d in d_ts:
d_ts_out.append("declare function {0}(state:any):any;\n".format(d))
out_d_ts = open(d_ts_file, 'w')
out_d_ts.writelines(d_ts_out)
out_d_ts.close()
if __name__ == '__main__':
run(sys.argv[1], os.path.dirname(sys.argv[0]))