PageRenderTime 33ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/sites/all/libraries/blockly/build.py

https://gitlab.com/Drulenium-test/pantheon-travis
Python | 468 lines | 406 code | 9 blank | 53 comment | 1 complexity | 7d91be4f9c3ca1c7e47e73d97b039bc2 MD5 | raw file
  1. #!/usr/bin/python2.7
  2. # Compresses the core Blockly files into a single JavaScript file.
  3. #
  4. # Copyright 2012 Google Inc.
  5. # https://developers.google.com/blockly/
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. # This script generates two versions of Blockly's core files:
  19. # blockly_compressed.js
  20. # blockly_uncompressed.js
  21. # The compressed file is a concatenation of all of Blockly's core files which
  22. # have been run through Google's Closure Compiler. This is done using the
  23. # online API (which takes a few seconds and requires an Internet connection).
  24. # The uncompressed file is a script that loads in each of Blockly's core files
  25. # one by one. This takes much longer for a browser to load, but is useful
  26. # when debugging code since line numbers are meaningful and variables haven't
  27. # been renamed. The uncompressed file also allows for a faster developement
  28. # cycle since there is no need to rebuild or recompile, just reload.
  29. #
  30. # This script also generates:
  31. # blocks_compressed.js: The compressed Blockly language blocks.
  32. # javascript_compressed.js: The compressed Javascript generator.
  33. # python_compressed.js: The compressed Python generator.
  34. # dart_compressed.js: The compressed Dart generator.
  35. # lua_compressed.js: The compressed Lua generator.
  36. # msg/js/<LANG>.js for every language <LANG> defined in msg/js/<LANG>.json.
  37. import sys
  38. if sys.version_info[0] != 2:
  39. raise Exception("Blockly build only compatible with Python 2.x.\n"
  40. "You are using: " + sys.version)
  41. import errno, glob, httplib, json, os, re, subprocess, threading, urllib
  42. def import_path(fullpath):
  43. """Import a file with full path specification.
  44. Allows one to import from any directory, something __import__ does not do.
  45. Args:
  46. fullpath: Path and filename of import.
  47. Returns:
  48. An imported module.
  49. """
  50. path, filename = os.path.split(fullpath)
  51. filename, ext = os.path.splitext(filename)
  52. sys.path.append(path)
  53. module = __import__(filename)
  54. reload(module) # Might be out of date.
  55. del sys.path[-1]
  56. return module
  57. HEADER = ("// Do not edit this file; automatically generated by build.py.\n"
  58. "'use strict';\n")
  59. class Gen_uncompressed(threading.Thread):
  60. """Generate a JavaScript file that loads Blockly's raw files.
  61. Runs in a separate thread.
  62. """
  63. def __init__(self, search_paths):
  64. threading.Thread.__init__(self)
  65. self.search_paths = search_paths
  66. def run(self):
  67. target_filename = 'blockly_uncompressed.js'
  68. f = open(target_filename, 'w')
  69. f.write(HEADER)
  70. f.write("""
  71. var isNodeJS = !!(typeof module !== 'undefined' && module.exports &&
  72. typeof window === 'undefined');
  73. if (isNodeJS) {
  74. var window = {};
  75. require('../closure-library/closure/goog/bootstrap/nodejs');
  76. }
  77. window.BLOCKLY_DIR = (function() {
  78. if (!isNodeJS) {
  79. // Find name of current directory.
  80. var scripts = document.getElementsByTagName('script');
  81. var re = new RegExp('(.+)[\/]blockly_uncompressed\.js$');
  82. for (var i = 0, script; script = scripts[i]; i++) {
  83. var match = re.exec(script.src);
  84. if (match) {
  85. return match[1];
  86. }
  87. }
  88. alert('Could not detect Blockly\\'s directory name.');
  89. }
  90. return '';
  91. })();
  92. window.BLOCKLY_BOOT = function() {
  93. var dir = '';
  94. if (isNodeJS) {
  95. require('../closure-library/closure/goog/bootstrap/nodejs');
  96. dir = 'blockly';
  97. } else {
  98. // Execute after Closure has loaded.
  99. if (!window.goog) {
  100. alert('Error: Closure not found. Read this:\\n' +
  101. 'developers.google.com/blockly/hacking/closure');
  102. }
  103. dir = window.BLOCKLY_DIR.match(/[^\\/]+$/)[0];
  104. }
  105. """)
  106. add_dependency = []
  107. base_path = calcdeps.FindClosureBasePath(self.search_paths)
  108. for dep in calcdeps.BuildDependenciesFromFiles(self.search_paths):
  109. add_dependency.append(calcdeps.GetDepsLine(dep, base_path))
  110. add_dependency = '\n'.join(add_dependency)
  111. # Find the Blockly directory name and replace it with a JS variable.
  112. # This allows blockly_uncompressed.js to be compiled on one computer and be
  113. # used on another, even if the directory name differs.
  114. m = re.search('[\\/]([^\\/]+)[\\/]core[\\/]blockly.js', add_dependency)
  115. add_dependency = re.sub('([\\/])' + re.escape(m.group(1)) +
  116. '([\\/]core[\\/])', '\\1" + dir + "\\2', add_dependency)
  117. f.write(add_dependency + '\n')
  118. provides = []
  119. for dep in calcdeps.BuildDependenciesFromFiles(self.search_paths):
  120. if not dep.filename.startswith(os.pardir + os.sep): # '../'
  121. provides.extend(dep.provides)
  122. provides.sort()
  123. f.write('\n')
  124. f.write('// Load Blockly.\n')
  125. for provide in provides:
  126. f.write("goog.require('%s');\n" % provide)
  127. f.write("""
  128. delete this.BLOCKLY_DIR;
  129. delete this.BLOCKLY_BOOT;
  130. };
  131. if (isNodeJS) {
  132. window.BLOCKLY_BOOT()
  133. module.exports = Blockly;
  134. } else {
  135. // Delete any existing Closure (e.g. Soy's nogoog_shim).
  136. document.write('<script>var goog = undefined;</script>');
  137. // Load fresh Closure Library.
  138. document.write('<script src="' + window.BLOCKLY_DIR +
  139. '/../closure-library/closure/goog/base.js"></script>');
  140. document.write('<script>window.BLOCKLY_BOOT();</script>');
  141. }
  142. """)
  143. f.close()
  144. print("SUCCESS: " + target_filename)
  145. class Gen_compressed(threading.Thread):
  146. """Generate a JavaScript file that contains all of Blockly's core and all
  147. required parts of Closure, compiled together.
  148. Uses the Closure Compiler's online API.
  149. Runs in a separate thread.
  150. """
  151. def __init__(self, search_paths):
  152. threading.Thread.__init__(self)
  153. self.search_paths = search_paths
  154. def run(self):
  155. self.gen_core()
  156. self.gen_blocks()
  157. self.gen_generator("javascript")
  158. self.gen_generator("python")
  159. self.gen_generator("php")
  160. self.gen_generator("dart")
  161. self.gen_generator("lua")
  162. def gen_core(self):
  163. target_filename = "blockly_compressed.js"
  164. # Define the parameters for the POST request.
  165. params = [
  166. ("compilation_level", "SIMPLE_OPTIMIZATIONS"),
  167. ("use_closure_library", "true"),
  168. ("output_format", "json"),
  169. ("output_info", "compiled_code"),
  170. ("output_info", "warnings"),
  171. ("output_info", "errors"),
  172. ("output_info", "statistics"),
  173. ]
  174. # Read in all the source files.
  175. filenames = calcdeps.CalculateDependencies(self.search_paths,
  176. [os.path.join("core", "blockly.js")])
  177. for filename in filenames:
  178. # Filter out the Closure files (the compiler will add them).
  179. if filename.startswith(os.pardir + os.sep): # '../'
  180. continue
  181. f = open(filename)
  182. params.append(("js_code", "".join(f.readlines())))
  183. f.close()
  184. self.do_compile(params, target_filename, filenames, "")
  185. def gen_blocks(self):
  186. target_filename = "blocks_compressed.js"
  187. # Define the parameters for the POST request.
  188. params = [
  189. ("compilation_level", "SIMPLE_OPTIMIZATIONS"),
  190. ("output_format", "json"),
  191. ("output_info", "compiled_code"),
  192. ("output_info", "warnings"),
  193. ("output_info", "errors"),
  194. ("output_info", "statistics"),
  195. ]
  196. # Read in all the source files.
  197. # Add Blockly.Blocks to be compatible with the compiler.
  198. params.append(("js_code", "goog.provide('Blockly.Blocks');"))
  199. filenames = glob.glob(os.path.join("blocks", "*.js"))
  200. for filename in filenames:
  201. f = open(filename)
  202. params.append(("js_code", "".join(f.readlines())))
  203. f.close()
  204. # Remove Blockly.Blocks to be compatible with Blockly.
  205. remove = "var Blockly={Blocks:{}};"
  206. self.do_compile(params, target_filename, filenames, remove)
  207. def gen_generator(self, language):
  208. target_filename = language + "_compressed.js"
  209. # Define the parameters for the POST request.
  210. params = [
  211. ("compilation_level", "SIMPLE_OPTIMIZATIONS"),
  212. ("output_format", "json"),
  213. ("output_info", "compiled_code"),
  214. ("output_info", "warnings"),
  215. ("output_info", "errors"),
  216. ("output_info", "statistics"),
  217. ]
  218. # Read in all the source files.
  219. # Add Blockly.Generator to be compatible with the compiler.
  220. params.append(("js_code", "goog.provide('Blockly.Generator');"))
  221. filenames = glob.glob(
  222. os.path.join("generators", language, "*.js"))
  223. filenames.insert(0, os.path.join("generators", language + ".js"))
  224. for filename in filenames:
  225. f = open(filename)
  226. params.append(("js_code", "".join(f.readlines())))
  227. f.close()
  228. filenames.insert(0, "[goog.provide]")
  229. # Remove Blockly.Generator to be compatible with Blockly.
  230. remove = "var Blockly={Generator:{}};"
  231. self.do_compile(params, target_filename, filenames, remove)
  232. def do_compile(self, params, target_filename, filenames, remove):
  233. # Send the request to Google.
  234. headers = {"Content-type": "application/x-www-form-urlencoded"}
  235. conn = httplib.HTTPConnection("closure-compiler.appspot.com")
  236. conn.request("POST", "/compile", urllib.urlencode(params), headers)
  237. response = conn.getresponse()
  238. json_str = response.read()
  239. conn.close()
  240. # Parse the JSON response.
  241. json_data = json.loads(json_str)
  242. def file_lookup(name):
  243. if not name.startswith("Input_"):
  244. return "???"
  245. n = int(name[6:]) - 1
  246. return filenames[n]
  247. if json_data.has_key("serverErrors"):
  248. errors = json_data["serverErrors"]
  249. for error in errors:
  250. print("SERVER ERROR: %s" % target_filename)
  251. print(error["error"])
  252. elif json_data.has_key("errors"):
  253. errors = json_data["errors"]
  254. for error in errors:
  255. print("FATAL ERROR")
  256. print(error["error"])
  257. if error["file"]:
  258. print("%s at line %d:" % (
  259. file_lookup(error["file"]), error["lineno"]))
  260. print(error["line"])
  261. print((" " * error["charno"]) + "^")
  262. sys.exit(1)
  263. else:
  264. if json_data.has_key("warnings"):
  265. warnings = json_data["warnings"]
  266. for warning in warnings:
  267. print("WARNING")
  268. print(warning["warning"])
  269. if warning["file"]:
  270. print("%s at line %d:" % (
  271. file_lookup(warning["file"]), warning["lineno"]))
  272. print(warning["line"])
  273. print((" " * warning["charno"]) + "^")
  274. print()
  275. if not json_data.has_key("compiledCode"):
  276. print("FATAL ERROR: Compiler did not return compiledCode.")
  277. sys.exit(1)
  278. code = HEADER + "\n" + json_data["compiledCode"]
  279. code = code.replace(remove, "")
  280. # Trim down Google's Apache licences.
  281. # The Closure Compiler used to preserve these until August 2015.
  282. # Delete this in a few months if the licences don't return.
  283. LICENSE = re.compile("""/\\*
  284. [\w ]+
  285. (Copyright \\d+ Google Inc.)
  286. https://developers.google.com/blockly/
  287. Licensed under the Apache License, Version 2.0 \(the "License"\);
  288. you may not use this file except in compliance with the License.
  289. You may obtain a copy of the License at
  290. http://www.apache.org/licenses/LICENSE-2.0
  291. Unless required by applicable law or agreed to in writing, software
  292. distributed under the License is distributed on an "AS IS" BASIS,
  293. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  294. See the License for the specific language governing permissions and
  295. limitations under the License.
  296. \\*/""")
  297. code = re.sub(LICENSE, r"\n// \1 Apache License 2.0", code)
  298. stats = json_data["statistics"]
  299. original_b = stats["originalSize"]
  300. compressed_b = stats["compressedSize"]
  301. if original_b > 0 and compressed_b > 0:
  302. f = open(target_filename, "w")
  303. f.write(code)
  304. f.close()
  305. original_kb = int(original_b / 1024 + 0.5)
  306. compressed_kb = int(compressed_b / 1024 + 0.5)
  307. ratio = int(float(compressed_b) / float(original_b) * 100 + 0.5)
  308. print("SUCCESS: " + target_filename)
  309. print("Size changed from %d KB to %d KB (%d%%)." % (
  310. original_kb, compressed_kb, ratio))
  311. else:
  312. print("UNKNOWN ERROR")
  313. class Gen_langfiles(threading.Thread):
  314. """Generate JavaScript file for each natural language supported.
  315. Runs in a separate thread.
  316. """
  317. def __init__(self):
  318. threading.Thread.__init__(self)
  319. def _rebuild(self, srcs, dests):
  320. # Determine whether any of the files in srcs is newer than any in dests.
  321. try:
  322. return (max(os.path.getmtime(src) for src in srcs) >
  323. min(os.path.getmtime(dest) for dest in dests))
  324. except OSError as e:
  325. # Was a file not found?
  326. if e.errno == errno.ENOENT:
  327. # If it was a source file, we can't proceed.
  328. if e.filename in srcs:
  329. print("Source file missing: " + e.filename)
  330. sys.exit(1)
  331. else:
  332. # If a destination file was missing, rebuild.
  333. return True
  334. else:
  335. print("Error checking file creation times: " + e)
  336. def run(self):
  337. # The files msg/json/{en,qqq,synonyms}.json depend on msg/messages.js.
  338. if self._rebuild([os.path.join("msg", "messages.js")],
  339. [os.path.join("msg", "json", f) for f in
  340. ["en.json", "qqq.json", "synonyms.json"]]):
  341. try:
  342. subprocess.check_call([
  343. "python",
  344. os.path.join("i18n", "js_to_json.py"),
  345. "--input_file", "msg/messages.js",
  346. "--output_dir", "msg/json/",
  347. "--quiet"])
  348. except (subprocess.CalledProcessError, OSError) as e:
  349. # Documentation for subprocess.check_call says that CalledProcessError
  350. # will be raised on failure, but I found that OSError is also possible.
  351. print("Error running i18n/js_to_json.py: ", e)
  352. sys.exit(1)
  353. # Checking whether it is necessary to rebuild the js files would be a lot of
  354. # work since we would have to compare each <lang>.json file with each
  355. # <lang>.js file. Rebuilding is easy and cheap, so just go ahead and do it.
  356. try:
  357. # Use create_messages.py to create .js files from .json files.
  358. cmd = [
  359. "python",
  360. os.path.join("i18n", "create_messages.py"),
  361. "--source_lang_file", os.path.join("msg", "json", "en.json"),
  362. "--source_synonym_file", os.path.join("msg", "json", "synonyms.json"),
  363. "--key_file", os.path.join("msg", "json", "keys.json"),
  364. "--output_dir", os.path.join("msg", "js"),
  365. "--quiet"]
  366. json_files = glob.glob(os.path.join("msg", "json", "*.json"))
  367. json_files = [file for file in json_files if not
  368. (file.endswith(("keys.json", "synonyms.json", "qqq.json")))]
  369. cmd.extend(json_files)
  370. subprocess.check_call(cmd)
  371. except (subprocess.CalledProcessError, OSError) as e:
  372. print("Error running i18n/create_messages.py: ", e)
  373. sys.exit(1)
  374. # Output list of .js files created.
  375. for f in json_files:
  376. # This assumes the path to the current directory does not contain "json".
  377. f = f.replace("json", "js")
  378. if os.path.isfile(f):
  379. print("SUCCESS: " + f)
  380. else:
  381. print("FAILED to create " + f)
  382. if __name__ == "__main__":
  383. try:
  384. calcdeps = import_path(os.path.join(
  385. os.path.pardir, "closure-library", "closure", "bin", "calcdeps.py"))
  386. except ImportError:
  387. if os.path.isdir(os.path.join(os.path.pardir, "closure-library-read-only")):
  388. # Dir got renamed when Closure moved from Google Code to GitHub in 2014.
  389. print("Error: Closure directory needs to be renamed from"
  390. "'closure-library-read-only' to 'closure-library'.\n"
  391. "Please rename this directory.")
  392. elif os.path.isdir(os.path.join(os.path.pardir, "google-closure-library")):
  393. # When Closure is installed by npm, it is named "google-closure-library".
  394. #calcdeps = import_path(os.path.join(
  395. # os.path.pardir, "google-closure-library", "closure", "bin", "calcdeps.py"))
  396. print("Error: Closure directory needs to be renamed from"
  397. "'google-closure-library' to 'closure-library'.\n"
  398. "Please rename this directory.")
  399. else:
  400. print("""Error: Closure not found. Read this:
  401. https://developers.google.com/blockly/hacking/closure""")
  402. sys.exit(1)
  403. search_paths = calcdeps.ExpandDirectories(
  404. ["core", os.path.join(os.path.pardir, "closure-library")])
  405. # Run both tasks in parallel threads.
  406. # Uncompressed is limited by processor speed.
  407. # Compressed is limited by network and server speed.
  408. Gen_uncompressed(search_paths).start()
  409. Gen_compressed(search_paths).start()
  410. # This is run locally in a separate thread.
  411. Gen_langfiles().start()