Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Unified Diff: script_compiler.py

Issue 4995669794226176: Issue 2539 - Move VCS abstraction part of ensure_dependencies into a separate module (Closed)
Patch Set: Created May 18, 2015, 3:23 p.m.
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: script_compiler.py
===================================================================
new file mode 100644
--- /dev/null
+++ b/script_compiler.py
@@ -0,0 +1,40 @@
+# coding: utf-8
+
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import importlib
+import inspect
+
+def multiline_repr(str):
Sebastian Noack 2015/05/19 11:52:41 Nit: Please avoid variable names conflicting with
+ return "'''%s'''" % str.replace('\\', '\\\\').replace("'", "\\'")
Sebastian Noack 2015/05/19 11:52:41 Note that you only need to escape quotes if follow
+
+def compile_script(main, modules=[]):
+ '''
+ Combines the source code of a main module and a number of additional modules
+ in a single Python script.
+ '''
+
+ yield '#!/usr/bin/env python\n'
Sebastian Noack 2015/05/19 11:52:41 I'd rather pass in the file object and use the pri
+ yield 'modules = []\n'
+ for module in modules + [main]:
+ path = inspect.getsourcefile(reload(importlib.import_module(module)))
+ with open(path, 'rb') as file:
+ data = file.read()
+ yield 'modules.append((%s, %s))\n' % (repr(module), multiline_repr(data))
+
+ yield '''
+import imp
+import importlib
Sebastian Noack 2015/05/19 11:52:41 importlib isn't used in the generated file.
+import sys
+
+if __name__ == '__main__':
+ for module, source in modules:
Sebastian Noack 2015/05/19 11:52:41 IMO, both, the generated and the generating code w
+ m = imp.new_module(module)
+ if (module, source) == modules[-1]:
+ m.__name__ = __name__
+ m.__file__ = __file__
+ exec source in m.__dict__
+ sys.modules[module] = m
+'''

Powered by Google App Engine
This is Rietveld