Coverage for /pythoncovmergedfiles/medio/medio/src/underscore/underscore/__init__.py: 72%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright (c) 2013 Huan Do, http://huan.do
3import ast
4import glob
5import os
7import codegen
8import environment
9import constant_visitor
10import future_visitor
11import variable_visitor
13def _(src, dest=None, original=False, verbose=False):
14 return __(src, dest, original, verbose).compile()
16class __(object):
18 def __init__(self, src, dest=None, original=False, verbose=True):
19 self.src = src
20 self.dest = dest
21 __.original = original
22 __.verbose = verbose
24 def compile(self):
25 self._generic_compile(self.src, self.dest)
27 @staticmethod
28 def _generic_compile(src, dest):
29 if src == dest:
30 raise ValueError('_: {src} and {dest} are the same location'.
31 format(src=src, dest=dest))
32 while src.endswith('/'):
33 src = src[:-1]
34 head, tail = os.path.split(src)
35 if dest is None:
36 dest = os.path.join(head, '_' + tail)
38 if os.path.isdir(src):
39 return __._compile_dir(src, dest)
40 elif os.path.isfile(src):
41 return __._compile_file(src, dest)
42 else:
43 raise ValueError('_: {src}: No such file or directory'.
44 format(src=src))
46 @staticmethod
47 def _compile_file(filename, dest):
48 if os.path.isdir(dest):
49 dest = os.path.join(dest, os.path.basename(filename))
52 if __.verbose:
53 print('compiling {src} -> {dest}'.format(
54 src=filename, dest=dest))
56 original_code = open(filename).read()
57 output = __._compile_code(original_code)
58 __._writeout(output, dest, original_code)
60 @staticmethod
61 def _compile_dir(dirname, destdir):
62 if os.path.isfile(destdir):
63 raise ValueError('_: {desination} is a file, expected directory'.
64 format(desination=destdir))
66 if not os.path.isdir(destdir):
67 os.mkdir(destdir)
69 for item in os.listdir(dirname):
70 src = os.path.join(dirname, item)
71 if os.path.isdir(src) or src.endswith('.py'):
72 dest = os.path.join(destdir, item)
73 __._generic_compile(src, dest)
75 @staticmethod
76 def _compile_code(code):
77 tree = ast.parse(code)
78 __._underscore_tree(tree)
79 return codegen.to_source(tree)
81 @staticmethod
82 def _underscore_tree(tree):
83 env = environment.Environment(tree)
84 variable_visitor.VariableVisitor(env).traverse()
85 constant_visitor.ConstantVisitor(env).traverse()
86 future_visitor.FutureVisitor(env).traverse()
87 return tree
89 @staticmethod
90 def _writeout(output, dest, original_code):
91 with open(dest, 'w') as out:
92 if __.original:
93 __._writeout_original(out, original_code)
94 out.write(output)
96 @staticmethod
97 def _writeout_original(out, original_code):
98 for line in original_code.splitlines():
99 out.write(('# ' + line).rstrip() + '\n')
100 out.write('\n')