forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse_build_cache.py
executable file
·354 lines (298 loc) · 11.5 KB
/
use_build_cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
"""
This script should be run from the repo root dir, it rewrites setup.py
to use the build cache directory specified in the envar BUILD_CACHE_DIR
or in a file named .build_cache_dir in the repo root directory.
Artifacts included in the cache:
- gcc artifacts
- The .c files resulting from cythonizing pyx/d files
- 2to3 refactoring results (when run under python3)
Tested on releases back to 0.7.0.
"""
try:
import argparse
argparser = argparse.ArgumentParser(description="""
'Program description.
""".strip())
argparser.add_argument('-f', '--force-overwrite',
default=False,
help='Setting this will overwrite any existing cache results for the current commit',
action='store_true')
argparser.add_argument('-d', '--debug',
default=False,
help='Report cache hits/misses',
action='store_true')
args = argparser.parse_args()
except:
class Foo(object):
debug=False
force_overwrite=False
args = Foo() # for 2.6, no argparse
#print(args.accumulate(args.integers))
shim="""
import os
import sys
import shutil
import warnings
import re
"""
shim += ("BC_FORCE_OVERWRITE = %s\n" % args.force_overwrite)
shim += ("BC_DEBUG = %s\n" % args.debug)
shim += """
try:
if not ("develop" in sys.argv) and not ("install" in sys.argv):
1/0
basedir = os.path.dirname(__file__)
dotfile = os.path.join(basedir,".build_cache_dir")
BUILD_CACHE_DIR = ""
if os.path.exists(dotfile):
BUILD_CACHE_DIR = open(dotfile).readline().strip()
BUILD_CACHE_DIR = os.environ.get('BUILD_CACHE_DIR',BUILD_CACHE_DIR)
if os.path.isdir(BUILD_CACHE_DIR):
print("--------------------------------------------------------")
print("BUILD CACHE ACTIVATED (V2). be careful, this is experimental.")
print("BUILD_CACHE_DIR: " + BUILD_CACHE_DIR )
print("--------------------------------------------------------")
else:
BUILD_CACHE_DIR = None
# retrieve 2to3 artifacts
if sys.version_info[0] >= 3:
from lib2to3 import refactor
from hashlib import sha1
import shutil
import multiprocessing
pyver = "%d.%d" % (sys.version_info[:2])
fileq = ["pandas"]
to_process = dict()
# retrieve the hashes existing in the cache
orig_hashes=dict()
post_hashes=dict()
for path,dirs,files in os.walk(os.path.join(BUILD_CACHE_DIR,'pandas')):
for f in files:
s=f.split(".py-")[-1]
try:
prev_h,post_h,ver = s.split('-')
if ver == pyver:
orig_hashes[prev_h] = os.path.join(path,f)
post_hashes[post_h] = os.path.join(path,f)
except:
pass
while fileq:
f = fileq.pop()
if os.path.isdir(f):
fileq.extend([os.path.join(f,x) for x in os.listdir(f)])
else:
if not f.endswith(".py"):
continue
else:
try:
h = sha1(open(f,"rb").read()).hexdigest()
except IOError:
to_process[h] = f
else:
if h in orig_hashes and not BC_FORCE_OVERWRITE:
src = orig_hashes[h]
if BC_DEBUG:
print("2to3 cache hit %s,%s" % (f,h))
shutil.copyfile(src,f)
elif h not in post_hashes:
# we're not in a dev dir with already processed files
if BC_DEBUG:
print("2to3 cache miss (will process) %s,%s" % (f,h))
to_process[h] = f
avail_fixes = set(refactor.get_fixers_from_package("lib2to3.fixes"))
avail_fixes.discard('lib2to3.fixes.fix_next')
t=refactor.RefactoringTool(avail_fixes)
if to_process:
print("Starting 2to3 refactoring...")
for orig_h,f in to_process.items():
if BC_DEBUG:
print("2to3 on %s" % f)
try:
t.refactor([f],True)
post_h = sha1(open(f, "rb").read()).hexdigest()
cached_fname = f + '-' + orig_h + '-' + post_h + '-' + pyver
path = os.path.join(BUILD_CACHE_DIR, cached_fname)
pathdir =os.path.dirname(path)
if BC_DEBUG:
print("cache put %s in %s" % (f, path))
try:
os.makedirs(pathdir)
except OSError as exc:
import errno
if exc.errno == errno.EEXIST and os.path.isdir(pathdir):
pass
else:
raise
shutil.copyfile(f, path)
except Exception as e:
print("While processing %s 2to3 raised: %s" % (f,str(e)))
pass
print("2to3 done refactoring.")
except Exception as e:
if not isinstance(e,ZeroDivisionError):
print( "Exception: " + str(e))
BUILD_CACHE_DIR = None
class CompilationCacheMixin(object):
def __init__(self, *args, **kwds):
cache_dir = kwds.pop("cache_dir", BUILD_CACHE_DIR)
self.cache_dir = cache_dir
if not os.path.isdir(cache_dir):
raise Exception("Error: path to Cache directory (%s) is not a dir" % cache_dir)
def _copy_from_cache(self, hash, target):
src = os.path.join(self.cache_dir, hash)
if os.path.exists(src) and not BC_FORCE_OVERWRITE:
if BC_DEBUG:
print("Cache HIT: asked to copy file %s in %s" %
(src,os.path.abspath(target)))
s = "."
for d in target.split(os.path.sep)[:-1]:
s = os.path.join(s, d)
if not os.path.exists(s):
os.mkdir(s)
shutil.copyfile(src, target)
return True
return False
def _put_to_cache(self, hash, src):
target = os.path.join(self.cache_dir, hash)
if BC_DEBUG:
print( "Cache miss: asked to copy file from %s to %s" % (src,target))
s = "."
for d in target.split(os.path.sep)[:-1]:
s = os.path.join(s, d)
if not os.path.exists(s):
os.mkdir(s)
shutil.copyfile(src, target)
def _hash_obj(self, obj):
try:
return hash(obj)
except:
raise NotImplementedError("You must override this method")
class CompilationCacheExtMixin(CompilationCacheMixin):
def _hash_file(self, fname):
from hashlib import sha1
f= None
try:
hash = sha1()
hash.update(self.build_lib.encode('utf-8'))
try:
if sys.version_info[0] >= 3:
import io
f = io.open(fname, "rb")
else:
f = open(fname)
first_line = f.readline()
# ignore cython generation timestamp header
if "Generated by Cython" not in first_line.decode('utf-8'):
hash.update(first_line)
hash.update(f.read())
return hash.hexdigest()
except:
raise
return None
finally:
if f:
f.close()
except IOError:
return None
def _hash_obj(self, ext):
from hashlib import sha1
sources = ext.sources
if (sources is None or
(not hasattr(sources, '__iter__')) or
isinstance(sources, str) or
sys.version[0] == 2 and isinstance(sources, unicode)): # argh
return False
sources = list(sources) + ext.depends
hash = sha1()
try:
for fname in sources:
fhash = self._hash_file(fname)
if fhash:
hash.update(fhash.encode('utf-8'))
except:
return None
return hash.hexdigest()
class CachingBuildExt(build_ext, CompilationCacheExtMixin):
def __init__(self, *args, **kwds):
CompilationCacheExtMixin.__init__(self, *args, **kwds)
kwds.pop("cache_dir", None)
build_ext.__init__(self, *args, **kwds)
def build_extension(self, ext, *args, **kwds):
ext_path = self.get_ext_fullpath(ext.name)
build_path = os.path.join(self.build_lib, os.path.basename(ext_path))
hash = self._hash_obj(ext)
if hash and self._copy_from_cache(hash, ext_path):
return
build_ext.build_extension(self, ext, *args, **kwds)
hash = self._hash_obj(ext)
if os.path.exists(build_path):
self._put_to_cache(hash, build_path) # build_ext
if os.path.exists(ext_path):
self._put_to_cache(hash, ext_path) # develop
def cython_sources(self, sources, extension):
import re
cplus = self.cython_cplus or getattr(extension, 'cython_cplus', 0) or \
(extension.language and extension.language.lower() == 'c++')
target_ext = '.c'
if cplus:
target_ext = '.cpp'
for i, s in enumerate(sources):
if not re.search("\.(pyx|pxi|pxd)$", s):
continue
ext_dir = os.path.dirname(s)
ext_basename = re.sub("\.[^\.]+$", "", os.path.basename(s))
ext_basename += target_ext
target = os.path.join(ext_dir, ext_basename)
hash = self._hash_file(s)
sources[i] = target
if hash and self._copy_from_cache(hash, target):
continue
build_ext.cython_sources(self, [s], extension)
self._put_to_cache(hash, target)
sources = [x for x in sources if x.startswith("pandas") or "lib." in x]
return sources
if BUILD_CACHE_DIR: # use the cache
cmdclass['build_ext'] = CachingBuildExt
try:
# recent
setuptools_kwargs['use_2to3'] = True if BUILD_CACHE_DIR is None else False
except:
pass
try:
# pre eb2234231 , ~ 0.7.0,
setuptools_args['use_2to3'] = True if BUILD_CACHE_DIR is None else False
except:
pass
"""
def main():
opd = os.path.dirname
opj = os.path.join
s= None
with open(opj(opd(__file__),"..","setup.py")) as f:
s = f.read()
if s:
if "BUILD CACHE ACTIVATED (V2)" in s:
print( "setup.py already wired with V2 build_cache, skipping..")
else:
SEP="\nsetup("
before,after = s.split(SEP)
with open(opj(opd(__file__),"..","setup.py"),"wb") as f:
f.write((before + shim + SEP + after).encode('ascii'))
print("""
setup.py was rewritten to use a build cache.
Make sure you've put the following in your .bashrc:
export BUILD_CACHE_DIR=<an existing directory for saving cached files>
echo $BUILD_CACHE_DIR > pandas_repo_rootdir/.build_cache_dir
Once active, build results (compilation, cythonizations and 2to3 artifacts)
will be cached in "$BUILD_CACHE_DIR" and subsequent builds should be
sped up if no changes requiring recompilation were made.
Go ahead and run:
python setup.py clean
python setup.py develop
""")
if __name__ == '__main__':
import sys
sys.exit(main())