Skip to content

Instantly share code, notes, and snippets.

@bingwen
Created November 26, 2015 08:59
Show Gist options
  • Save bingwen/8ad102766532a8511064 to your computer and use it in GitHub Desktop.
Save bingwen/8ad102766532a8511064 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import os, sys, re
def usage():
print "usage: toCommonJS file1 file2 ..."
def readfile(filename):
''' read file as a string '''
fd = None
try:
fd = open(filename, 'r')
s = fd.read()
except:
print "file not exist: %s" % filename
s = ''
finally:
if not fd is None:
fd.close()
return s
def process(filename, content):
''' replace AMD as CommonJS require '''
regexp = r"define\(\[[^'\]]*(('[^'\]]+',*[^'\]]*)+)\],[ ]*function\((([^,\)]+,*)+)*\)[ ]*\{(.*)return[\s]*([^;]*);.*$"
matchObj = re.match(regexp, content, re.S)
if not matchObj or not matchObj.group(1):
print "regular expression not match: [%s]" % filename
return content
requires = matchObj.group(1)
defines = matchObj.group(3)
middle = matchObj.group(5)
variable = matchObj.group(6)
part_requires = process_requires(requires, defines)
part_middle = process_middle(middle)
part_variable = process_variable(variable)
return "\n\n".join([part_requires, part_middle, part_variable])
def process_requires(requires, defines):
''' make requires and defines as CommonJS style '''
require_list = requires.strip().strip(',').split(',')
define_list = defines.strip().strip(',').split(',')
part = ['// require modules']
pathlen = len(require_list)
varlen = len(define_list)
cnt = 0
while cnt < pathlen:
path = require_list[cnt].strip()
if cnt >= varlen:
break
var = define_list[cnt].strip()
part.append('var %s = require(%s);' % (var, path))
cnt = cnt + 1
return "\n".join(part)
def process_middle(middle):
''' shift the function part left with tabstop '''
middle_list = middle.strip().split('\n')
part = ['// module definition']
for line in middle_list:
part.append(re.sub(r' ', '', line, 1))
return "\n".join(part)
def process_variable(variable):
''' export the variable '''
return 'module.exports = %s;' % variable
def output(filename, process_content):
''' output the new content and replace the file '''
fd = None
try:
fd = open(filename, 'w')
fd.write(process_content)
except Exception, e:
print "write file [%s] error: [%s]" % (filename, e)
finally:
if not fd is None:
fd.close()
def transform(filename):
''' transform a file written with AMD style to CommonJS style '''
content = readfile(filename)
process_content = process(filename, content)
output(filename, process_content)
if __name__ == "__main__":
if len(sys.argv) < 2:
usage()
exit(1)
files = sys.argv[1:]
for f in files:
try:
transform(f)
except Exception, e:
print "transform [%s] error: [%s]" % (f, e)
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment