linkjs.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/python
  2. import os
  3. import re
  4. import sys
  5. def extract_require(s):
  6. m = re.search('(//)?(.*)require\\("(.*)"\\)', s)
  7. if not m or m.group(1):
  8. return None
  9. prefix = m.group(2)
  10. if prefix and len(prefix):
  11. prefix = prefix[-1]
  12. if prefix.isalpha() or prefix.isdigit() or prefix == '_':
  13. return None
  14. return m.group(3)
  15. def resolve_require(req, out, resolved, resolving):
  16. if not os.path.exists(req):
  17. raise Exception('cannot resolve "%s"' % req)
  18. process(req, out, resolved, resolving)
  19. def process(path, out, resolved, resolving):
  20. module_name = os.path.splitext(os.path.basename(path))[0]
  21. if module_name in resolving:
  22. raise Exception('cyclic import detected: "%s"' % module_name)
  23. result = 'imports["%s"] = {};\n' % path
  24. result += '(function %s(exports){\n' % module_name
  25. with open(path) as f:
  26. for l in f:
  27. req = extract_require(l)
  28. if req and not req in resolved:
  29. try:
  30. resolve_require(req, out, resolved, resolving + [module_name])
  31. except Exception, e:
  32. print 'while resolving "%s"...' % module_name
  33. raise e
  34. result += l
  35. result += '\n})(imports["%s"]);\n' % path
  36. out.write(result)
  37. resolved += [path]
  38. if __name__ == '__main__':
  39. if len(sys.argv) != 3:
  40. raise Exception("Usage: linkjs.py <input js> <output js>")
  41. input_path = sys.argv[1]
  42. output_path = sys.argv[2]
  43. with open(output_path, "w") as out:
  44. prolog = "var imports = {};\n"
  45. prolog += 'function require(module){return imports[module];}\n'
  46. out.write(prolog)
  47. process(input_path, out, [], [])