forked from root-project/cling
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpt.py
executable file
·2476 lines (2112 loc) · 94.3 KB
/
cpt.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# coding:utf-8
###############################################################################
#
# The Cling Interpreter
#
# Cling Packaging Tool (CPT)
#
# tools/packaging/cpt.py: Python script to launch Cling Packaging Tool (CPT)
#
# Documentation: tools/packaging/README.md
#
# Author: Anirudha Bose <[email protected]>
#
# This file is dual-licensed: you can choose to license it under the University
# of Illinois Open Source License or the GNU Lesser General Public License. See
# LICENSE.TXT for details.
#
###############################################################################
import sys
if sys.version_info < (3, 0):
raise Exception("cpt needs Python 3")
import argparse
import copy
import os
import platform
import subprocess
import shutil
import shlex
import glob
import re
import tarfile
import zipfile
from email.utils import formatdate
from datetime import tzinfo
import time
import multiprocessing
import stat
import json
from urllib.request import urlopen
###############################################################################
# Platform independent functions (formerly indep.py) #
###############################################################################
def _convert_subprocess_cmd(cmd):
if OS == 'Windows':
cmd = cmd.replace('\\','/')
return shlex.split(cmd, posix=True, comments=True)
def _perror(e):
print("subprocess.CalledProcessError: Command '%s' returned non-zero exit status %s" % (
' '.join(e.cmd), str(e.returncode)))
cleanup()
# Communicate return code to the calling program if any
sys.exit(e.returncode)
def exec_subprocess_call(cmd, cwd, showCMD=False):
if showCMD: print(cmd)
cmd = _convert_subprocess_cmd(cmd)
try:
subprocess.check_call(cmd, cwd=cwd, shell=False,
stdin=subprocess.PIPE, stdout=None, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
_perror(e)
def exec_subprocess_check_output(cmd, cwd):
cmd = _convert_subprocess_cmd(cmd)
out = ''
try:
out = subprocess.check_output(cmd, cwd=cwd, shell=False,
stdin=subprocess.PIPE, stderr=subprocess.STDOUT).decode('utf-8')
except subprocess.CalledProcessError as e:
_perror(e)
finally:
return out
def travis_fold_start(tag):
if os.environ.get('TRAVIS_BUILD_DIR', None):
print('travis_fold:start:cpt-%s:' % (tag))
def travis_fold_end(tag):
if os.environ.get('TRAVIS_BUILD_DIR', None):
print('travis_fold:end:cpt-%s:' % (tag))
def box_draw_header():
msg = 'cling (' + platform.machine() + ')' + formatdate(time.time(), tzinfo())
spaces_no = 80 - len(msg) - 4
spacer = ' ' * spaces_no
msg = 'cling (' + platform.machine() + ')' + spacer + formatdate(time.time(), tzinfo())
if OS != 'Windows':
print('''
╔══════════════════════════════════════════════════════════════════════════════╗
║ %s ║
╚══════════════════════════════════════════════════════════════════════════════╝''' % (msg))
else:
print('''
+=============================================================================+
| %s|
+=============================================================================+''' % (msg))
def box_draw(msg):
spaces_no = 80 - len(msg) - 4
spacer = ' ' * spaces_no
if OS == 'Linux':
print('''
┌──────────────────────────────────────────────────────────────────────────────┐
│ %s%s │
└──────────────────────────────────────────────────────────────────────────────┘''' % (msg, spacer))
else:
print('''
+-----------------------------------------------------------------------------+
| %s%s|
+-----------------------------------------------------------------------------+''' % (msg, spacer))
def pip_install(package):
# Needs brew install python. We should only install if we need the
# functionality
import pip
pip.main(['install', '--ignore-installed', '--prefix', os.path.join(workdir, 'pip'), '--upgrade', package])
def wget(url, out_dir, rename_file=None, retries=3):
file_name = url.split('/')[-1]
print(" HTTP request sent, awaiting response ... ")
u = urlopen(url)
if u.code != 200 or retries == 0:
exit()
else:
print(" Connected to %s [200 OK]" % (url))
try:
file_size = u.headers.get('Content-Length')
if file_size:
file_size = int(file_size)
else:
raise Exception
except Exception:
print(' Error due to broken pipe')
print(' Retrying ...')
wget(url, out_dir, retries-1)
else:
print(" Downloading: %s Bytes: %s" % (file_name, file_size))
file_size_dl = 0
block_sz = 8192
f = open(os.path.join(out_dir, file_name), 'wb')
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status += chr(8) * (len(status) + 1)
print(status, end=' ')
f.close()
if rename_file:
ffrom = os.path.join(out_dir, file_name)
fto = os.path.join(out_dir, rename_file)
print('Moving file: ' + ffrom + ' -> ' + fto)
os.rename(ffrom, fto)
print()
def fetch_llvm(llvm_revision):
box_draw("Fetch source files")
print('Last known good LLVM revision is: ' + llvm_revision)
print('Current working directory is: ' + workdir + '\n')
if "github.com" in LLVM_GIT_URL and args['create_dev_env'] is None and args['use_wget']:
_, _, _, user, repo = LLVM_GIT_URL.split('/')
print('Fetching LLVM ...')
wget(url='https://github.com/%s/%s' % (user, repo.replace('.git', '')) +
'/archive/cling-patches-r%s.tar.gz' % llvm_revision,
out_dir=workdir)
print('Extracting: ' + os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision))
tar = tarfile.open(os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision))
tar.extractall(path=workdir)
tar.close()
os.rename(os.path.join(workdir, 'llvm-cling-patches-r%s' % llvm_revision), srcdir)
if os.path.isfile(os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision)):
print("Remove file: " + os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision))
os.remove(os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision))
print()
return
def checkout():
exec_subprocess_call('git checkout cling-patches-r%s' % llvm_revision, srcdir)
def get_fresh_llvm():
exec_subprocess_call('git clone %s %s' % (LLVM_GIT_URL, srcdir), workdir)
checkout()
def update_old_llvm():
exec_subprocess_call('git stash', srcdir)
# exec_subprocess_call('git clean -f -x -d', srcdir)
checkout()
exec_subprocess_call('git fetch --tags', srcdir)
exec_subprocess_call('git pull origin refs/tags/cling-patches-r%s'
% llvm_revision, srcdir)
if os.path.isdir(srcdir):
update_old_llvm()
else:
get_fresh_llvm()
def download_llvm_binary():
global llvm_flags, tar_required
box_draw("Fetching LLVM binary")
print('Current working directory is: ' + workdir + '\n')
if DIST=="Ubuntu":
subprocess.call(
"sudo -H {0} -m pip install lit".format(sys.executable), shell=True
)
llvm_config_path = exec_subprocess_check_output("which llvm-config-{0}".format(llvm_vers), workdir)
if llvm_config_path != '' and tar_required is False:
llvm_dir = os.path.join("/usr", "lib", "llvm-"+llvm_vers)
if llvm_config_path[-1:] == "\n":
llvm_config_path = llvm_config_path[:-1]
llvm_flags = "-DLLVM_BINARY_DIR={0} -DLLVM_CONFIG={1} -DLLVM_LIBRARY_DIR={2} -DLLVM_MAIN_INCLUDE_DIR={3} -DLLVM_TABLEGEN_EXE={4} \
-DLLVM_TOOLS_BINARY_DIR={5} -DLLVM_TOOL_CLING_BUILD=ON".format(llvm_dir, llvm_config_path,
os.path.join(llvm_dir, 'lib'), os.path.join(llvm_dir, 'include'), os.path.join(llvm_dir, 'bin', 'llvm-tblgen'),
os.path.join(llvm_dir, 'bin'))
else:
tar_required = True
elif DIST == 'MacOSX':
subprocess.call(
"sudo -H {0} -m pip install lit".format(sys.executable), shell=True
)
if tar_required is False:
llvm_dir = os.path.join("/opt", "local", "libexec", "llvm-"+llvm_vers)
llvm_config_path = os.path.join(llvm_dir, "bin", "llvm-config")
if llvm_config_path[-1:] == "\n":
llvm_config_path = llvm_config_path[:-1]
llvm_flags = "-DLLVM_BINARY_DIR={0} -DLLVM_CONFIG={1} -DLLVM_LIBRARY_DIR={2} -DLLVM_MAIN_INCLUDE_DIR={3} -DLLVM_TABLEGEN_EXE={4} \
-DLLVM_TOOLS_BINARY_DIR={5} -DLLVM_TOOL_CLING_BUILD=ON".format(llvm_dir, llvm_config_path,
os.path.join(llvm_dir, 'lib'), os.path.join(llvm_dir, 'include'), os.path.join(llvm_dir, 'bin', 'llvm-tblgen'),
os.path.join(llvm_dir, 'bin'))
else:
raise Exception("Building clang using LLVM binary not possible. Please invoke cpt without --with-binary-llvm and --with-llvm-tar flags")
if tar_required:
llvm_flags = "-DLLVM_BINARY_DIR={0} -DLLVM_CONFIG={1} -DLLVM_LIBRARY_DIR={2} -DLLVM_MAIN_INCLUDE_DIR={3} -DLLVM_TABLEGEN_EXE={4} \
-DLLVM_TOOLS_BINARY_DIR={5} -DLLVM_TOOL_CLING_BUILD=ON".format(srcdir, os.path.join(srcdir, 'bin', 'llvm-config'),
os.path.join(srcdir, 'lib'), os.path.join(srcdir, 'include'), os.path.join(srcdir, 'bin', 'llvm-tblgen'),
os.path.join(srcdir, 'bin'))
if DIST=="Ubuntu" and REV=='16.04' and is_os_64bit():
download_link = 'http://releases.llvm.org/5.0.2/clang+llvm-5.0.2-x86_64-linux-gnu-ubuntu-16.04.tar.xz'
exec_subprocess_call('wget %s' % download_link, workdir)
exec_subprocess_call('tar xvf clang+llvm-5.0.2-x86_64-linux-gnu-ubuntu-16.04.tar.xz', workdir)
exec_subprocess_call('mv clang+llvm-5.0.2-x86_64-linux-gnu-ubuntu-16.04 %s' % srcdir, workdir)
elif DIST=="Ubuntu" and REV=='14.04' and is_os_64bit():
download_link = 'http://releases.llvm.org/5.0.2/clang+llvm-5.0.2-x86_64-linux-gnu-ubuntu-14.04.tar.xz'
exec_subprocess_call('wget %s' % download_link, workdir)
exec_subprocess_call('tar xvf clang+llvm-5.0.2-x86_64-linux-gnu-ubuntu-14.04.tar.xz', workdir)
exec_subprocess_call('mv clang+llvm-5.0.2-x86_64-linux-gnu-ubuntu-14.04 %s' % srcdir, workdir)
elif DIST=='MacOSX' and is_os_64bit():
download_link = 'http://releases.llvm.org/5.0.2/clang+llvm-5.0.2-x86_64-apple-darwin.tar.xz'
exec_subprocess_call('wget %s' % download_link, workdir)
exec_subprocess_call('tar xvf clang+llvm-5.0.2-x86_64-apple-darwin.tar.xz', workdir)
exec_subprocess_call('sudo mv clang+llvm-5.0.2-x86_64-apple-darwin %s' % srcdir, workdir)
else:
raise Exception("Building clang using LLVM binary not possible. Please invoke cpt without --with-binary-llvm and --with-llvm-tar flags")
# FIXME: Add Fedora and SUSE support
# TODO Refactor all fetch_ functions to use this class will remove a lot of dup
class RepoCache(object):
def __init__(self, url, rootDir, depth=10):
self.__url = url
self.__depth = depth
self.__projDir = rootDir
self.__workDir = os.path.join(rootDir, url.split('/')[-1])
def fetch(self, branch):
if os.path.isdir(self.__workDir):
exec_subprocess_call('git stash', self.__workDir)
exec_subprocess_call('git clean -f -x -d', self.__workDir)
exec_subprocess_call('git fetch --tags', self.__workDir)
else:
exec_subprocess_call('git clone %s' % self.__url, self.__projDir)
exec_subprocess_call('git checkout %s' % branch, self.__workDir)
def fetch_clang(llvm_revision):
if "github.com" in CLANG_GIT_URL and args['create_dev_env'] is None and args['use_wget']:
_, _, _, user, repo = CLANG_GIT_URL.split('/')
print('Fetching Clang ...')
wget(url='https://github.com/%s/%s' % (user, repo.replace('.git', '')) +
'/archive/cling-patches-r%s.tar.gz' % llvm_revision,
out_dir=workdir)
print('Extracting: ' + os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision))
tar = tarfile.open(os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision))
tar.extractall(path=os.path.join(srcdir, 'tools'))
tar.close()
os.rename(os.path.join(srcdir, 'tools', 'clang-cling-patches-r%s' % llvm_revision),
os.path.join(srcdir, 'tools', 'clang'))
if os.path.isfile(os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision)):
print("Remove file: " + os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision))
os.remove(os.path.join(workdir, 'cling-patches-r%s.tar.gz' % llvm_revision))
print()
return
if args["with_binary_llvm"]:
dir = workdir
else:
dir = os.path.join(srcdir, 'tools')
global clangdir
clangdir = os.path.join(dir, 'clang')
def checkout():
exec_subprocess_call('git checkout cling-patches-r%s' % llvm_revision, clangdir)
def get_fresh_clang():
exec_subprocess_call('git clone %s' % CLANG_GIT_URL, dir)
checkout()
def update_old_clang():
exec_subprocess_call('git stash', clangdir)
# exec_subprocess_call('git clean -f -x -d', clangdir)
exec_subprocess_call('git fetch --tags', clangdir)
checkout()
exec_subprocess_call('git fetch --tags', clangdir)
exec_subprocess_call('git pull origin refs/tags/cling-patches-r%s' % llvm_revision,
clangdir)
if os.path.isdir(clangdir):
update_old_clang()
else:
get_fresh_clang()
def fetch_cling(arg):
if args["with_binary_llvm"]:
global CLING_SRC_DIR
CLING_SRC_DIR = os.path.join(clangdir, 'tools', 'cling')
dir = clangdir
else:
dir = srcdir
def get_fresh_cling():
if CLING_BRANCH:
exec_subprocess_call('git clone --depth=10 --branch %s %s cling'
% (CLING_BRANCH, CLING_GIT_URL), os.path.join(dir, 'tools'))
else:
exec_subprocess_call('git clone %s cling' % CLING_GIT_URL, os.path.join(dir, 'tools'))
# if arg == 'last-stable':
# checkout_branch = exec_subprocess_check_output('git describe --match v* --abbrev=0 --tags | head -n 1',
# CLING_SRC_DIR)
if arg == 'master':
checkout_branch = 'master'
else:
checkout_branch = arg
exec_subprocess_call('git checkout %s' % checkout_branch, CLING_SRC_DIR)
def update_old_cling():
# exec_subprocess_call('git stash', CLING_SRC_DIR)
# exec_subprocess_call('git clean -f -x -d', CLING_SRC_DIR)
exec_subprocess_call('git fetch --tags', CLING_SRC_DIR)
# if arg == 'last-stable':
# checkout_branch = exec_subprocess_check_output('git describe --match v* --abbrev=0 --tags | head -n 1',
# CLING_SRC_DIR)
if arg == 'master':
checkout_branch = 'master'
else:
checkout_branch = arg
exec_subprocess_call('git checkout %s' % checkout_branch, CLING_SRC_DIR)
exec_subprocess_call('git pull origin %s' % checkout_branch, CLING_SRC_DIR)
if os.path.isdir(CLING_SRC_DIR):
update_old_cling()
else:
get_fresh_cling()
def set_version():
global VERSION
global REVISION
box_draw("Set Cling version")
VERSION = open(os.path.join(CLING_SRC_DIR, 'VERSION'), 'r').readline().strip()
# If development release, then add revision to the version
REVISION = exec_subprocess_check_output('git log -n 1 --pretty=format:%H', CLING_SRC_DIR).strip()
if '~dev' in VERSION:
VERSION = VERSION + '-' + REVISION[:7]
print('Version: ' + VERSION)
print('Revision: ' + REVISION)
def set_vars():
global EXEEXT
global SHLIBEXT
global CLANG_VERSION
box_draw("Set variables")
if not os.path.isfile(os.path.join(LLVM_OBJ_ROOT, 'test', 'lit.site.cfg')):
if not os.path.exists(os.path.join(LLVM_OBJ_ROOT, 'test')):
os.mkdir(os.path.join(LLVM_OBJ_ROOT, 'test'))
with open(os.path.join(LLVM_OBJ_ROOT, 'test', 'lit.site.cfg.py'), 'r') as lit_site_cfg:
for line in lit_site_cfg:
if re.match('^config.llvm_shlib_ext = ', line):
SHLIBEXT = re.sub('^config.llvm_shlib_ext = ', '', line).replace('"', '').strip()
elif re.match('^config.llvm_exe_ext = ', line):
EXEEXT = re.sub('^config.llvm_exe_ext = ', '', line).replace('"', '').strip()
if not os.path.isfile(os.path.join(LLVM_OBJ_ROOT, 'tools', 'clang', 'include', 'clang', 'Basic', 'Version.inc')):
exec_subprocess_call('make Version.inc',
os.path.join(LLVM_OBJ_ROOT, 'tools', 'clang', 'include', 'clang', 'Basic'))
with open(os.path.join(LLVM_OBJ_ROOT, 'tools', 'clang', 'include', 'clang', 'Basic', 'Version.inc'),
'r') as Version_inc:
for line in Version_inc:
if re.match('^#define CLANG_VERSION ', line):
CLANG_VERSION = re.sub('^#define CLANG_VERSION ', '', line).strip()
print('EXEEXT: ' + EXEEXT)
print('SHLIBEXT: ' + SHLIBEXT)
print('CLANG_VERSION: ' + CLANG_VERSION)
def set_vars_for_lit():
global tar_required, srcdir
with open(os.path.join(CLING_SRC_DIR, "test", "lit.site.cfg.in"), "r") as file:
lines = file.readlines()
for i in range(len(lines)):
if lines[i].startswith("config.llvm_tools_dir ="):
lines[i] = 'config.llvm_tools_dir = "{0}"\n'.format(os.path.join(LLVM_OBJ_ROOT, "bin"))
break
with open(os.path.join(CLING_SRC_DIR, "test", "lit.site.cfg.in"), "w") as file:
file.writelines(lines)
if tar_required:
with open(os.path.join(CLING_SRC_DIR, "test", "lit.site.cfg.in"), "r") as file:
lines = file.readlines()
for i in range(len(lines)):
if lines[i].startswith("config.llvm_src_root ="):
lines[i] = 'config.llvm_src_root = "{0}"\n'.format(srcdir)
break
with open(os.path.join(CLING_SRC_DIR, "test", "lit.site.cfg.in"), "w") as file:
file.writelines(lines)
elif DIST == 'MacOSX' and tar_required is False:
llvm_dir = os.path.join("/opt", "local", "libexec", "llvm-" + llvm_vers)
with open(os.path.join(CLING_SRC_DIR, "test", "lit.site.cfg.in"), "r") as file:
lines = file.readlines()
for i in range(len(lines)):
if lines[i].startswith("config.llvm_src_root ="):
lines[i] = 'config.llvm_src_root = "{0}"\n'.format(llvm_dir)
break
with open(os.path.join(CLING_SRC_DIR, "test", "lit.site.cfg.in"), "w") as file:
file.writelines(lines)
def allow_clang_tool():
with open(os.path.join(workdir, 'clang', 'tools', 'CMakeLists.txt'), 'a') as file:
file.writelines('add_llvm_external_project(cling)')
class Build(object):
def __init__(self, target=None):
if args.get('create_dev_env'):
if args.get('create_dev_env') is None:
self.buildType = 'Debug'
else:
self.buildType = args.get('create_dev_env')
else:
self.buildType = 'Release'
self.win32 = platform.system() == 'Windows'
self.cores = multiprocessing.cpu_count()
# Travis CI, GCC crashes if more than 4 cores used.
if os.environ.get('TRAVIS_OS_NAME', None):
self.cores = min(self.cores, 4)
if target:
self.make(target)
def config(self, configFlags=''):
box_draw('Configure Cling with CMake ' + configFlags)
exec_subprocess_call('%s %s' % (CMAKE, configFlags), LLVM_OBJ_ROOT, True)
def make(self, targets, flags=''):
box_draw('Building %s (using %d cores)' % (targets, self.cores))
if self.win32:
flags += ' --config %s' % self.buildType
for target in targets.split():
exec_subprocess_call('%s --build . --target %s %s'
% (CMAKE, target, flags), LLVM_OBJ_ROOT)
else:
if args['verbose']: flags += ' VERBOSE=1'
exec_subprocess_call('make -j%d %s %s' % (self.cores, targets, flags),
LLVM_OBJ_ROOT)
def compile(arg):
travis_fold_start("compile")
global prefix, EXTRA_CMAKE_FLAGS
prefix = arg
# Cleanup previous installation directory if any
if os.path.isdir(prefix):
print("Remove directory: " + prefix)
shutil.rmtree(prefix)
# Cleanup previous build directory if exists
if os.path.isdir(LLVM_OBJ_ROOT):
print("Using previous build directory: " + LLVM_OBJ_ROOT)
else:
print("Creating build directory: " + LLVM_OBJ_ROOT)
os.makedirs(LLVM_OBJ_ROOT)
### FIX: Target isn't being set properly on Travis OS X
### Either because ccache(when enabled) or maybe the virtualization environment
if TRAVIS_BUILD_DIR and OS == 'Darwin':
triple = exec_subprocess_check_output('sh %s/cmake/config.guess' % srcdir, srcdir)
if triple:
EXTRA_CMAKE_FLAGS = ' -DLLVM_HOST_TRIPLE="%s" ' % triple.rstrip() + EXTRA_CMAKE_FLAGS
build = Build()
cmake_config_flags = (srcdir + ' -DLLVM_BUILD_TOOLS=Off -DCMAKE_BUILD_TYPE={0} -DCMAKE_INSTALL_PREFIX={1} '
.format(build.buildType, TMP_PREFIX) + ' -DLLVM_TARGETS_TO_BUILD="host;NVPTX" ' +
EXTRA_CMAKE_FLAGS)
# configure cling
build.config(cmake_config_flags)
build.make('clang cling' if CLING_BRANCH else 'cling')
box_draw("Install compiled binaries to prefix (using %d cores)" % build.cores)
build.make('install')
if TRAVIS_BUILD_DIR:
### Run cling once, dumping the include paths, helps debug issues
try:
subprocess.check_call(os.path.join(workdir, 'builddir', 'bin', 'cling')
+ ' -v ".I"', shell=True)
except Exception as e:
print(e)
travis_fold_end("compile")
def compile_for_binary(arg):
travis_fold_start("compile")
global prefix, EXTRA_CMAKE_FLAGS
prefix = arg
# Cleanup previous installation directory if any
if os.path.isdir(prefix):
print("Remove directory: " + prefix)
shutil.rmtree(prefix)
# Cleanup previous build directory if exists
if os.path.isdir(LLVM_OBJ_ROOT):
print("Using previous build directory: " + LLVM_OBJ_ROOT)
else:
print("Creating build directory: " + LLVM_OBJ_ROOT)
os.makedirs(LLVM_OBJ_ROOT)
build = Build()
cmake_config_flags = (clangdir + ' -DCMAKE_BUILD_TYPE={0} -DCMAKE_INSTALL_PREFIX={1} '
.format(build.buildType, TMP_PREFIX) + llvm_flags +
' -DLLVM_TARGETS_TO_BUILD=host;NVPTX -DCLING_CXX_HEADERS=ON -DCLING_INCLUDE_TESTS=ON' +
EXTRA_CMAKE_FLAGS)
box_draw('Configure Cling with CMake ' + cmake_config_flags)
exec_subprocess_call('%s %s' % (CMAKE, cmake_config_flags), LLVM_OBJ_ROOT, True)
box_draw('Building %s (using %d cores)' % ("cling", multiprocessing.cpu_count()))
exec_subprocess_call('make -j%d %s' % (multiprocessing.cpu_count(), "cling"), LLVM_OBJ_ROOT)
box_draw("Install compiled binaries to prefix (using %d cores)" % build.cores)
build.make('install')
if TRAVIS_BUILD_DIR:
### Run cling once, dumping the include paths, helps debug issues
try:
subprocess.check_call(os.path.join(workdir, 'builddir', 'bin', 'cling')
+ ' -v ".I"', shell=True)
except Exception as e:
print(e)
travis_fold_end("compile")
def install_prefix():
travis_fold_start("install")
global prefix
set_vars()
box_draw("Filtering Cling's libraries and binaries")
regex_array = []
regex_filename = os.path.join(CPT_SRC_DIR, 'dist-files.txt')
for line in open(regex_filename).read().splitlines():
if line and not line.startswith('#'):
regex_array.append(line)
for root, dirs, files in os.walk(TMP_PREFIX):
for file in files:
f = os.path.join(root, file).replace(TMP_PREFIX, '')
if OS == 'Windows':
f = f.replace('\\', '/')
for regex in regex_array:
if args['verbose']: print ("Applying regex " + regex + " to file " + f)
if re.search(regex, f):
print ("Adding to final binary " + f)
if not os.path.isdir(os.path.join(prefix, os.path.dirname(f))):
os.makedirs(os.path.join(prefix, os.path.dirname(f)))
shutil.copy(os.path.join(TMP_PREFIX, f), os.path.join(prefix, f))
break
travis_fold_end("install")
def install_prefix_for_binary():
travis_fold_start("install")
global prefix
CPT_SRC_DIR = os.path.join(clangdir, 'tools', 'cling', 'tools', 'packaging')
set_vars_for_lit()
box_draw("Filtering Cling's libraries and binaries")
regex_array = []
regex_filename = os.path.join(CPT_SRC_DIR, 'dist-files.txt')
for line in open(regex_filename).read().splitlines():
if line and not line.startswith('#'):
regex_array.append(line)
for root, dirs, files in os.walk(TMP_PREFIX):
for file in files:
f = os.path.join(root, file).replace(TMP_PREFIX, '')
if OS == 'Windows':
f = f.replace('\\', '/')
for regex in regex_array:
if args['verbose']: print ("Applying regex " + regex + " to file " + f)
if re.search(regex, f):
print ("Adding to final binary " + f)
if not os.path.isdir(os.path.join(prefix, os.path.dirname(f))):
os.makedirs(os.path.join(prefix, os.path.dirname(f)))
shutil.copy(os.path.join(TMP_PREFIX, f), os.path.join(prefix, f))
break
travis_fold_end("install")
def runSingleTest(test, Idx = 2, Recurse = True):
try:
test = os.path.join(CLING_SRC_DIR, 'test', test)
if os.path.isdir(test):
if Recurse:
for t in os.listdir(test):
if t.endswith('.C'):
runSingleTest(os.path.join(test, t), Idx, False)
return
cling = os.path.join(LLVM_OBJ_ROOT, 'bin', 'cling')
flags = [[''], ['-Xclang -verify']]
flags.append([f[0] for f in flags])
for flag in flags[Idx]:
cmd = 'cat %s | %s --nologo 2>&1 %s' % (test, cling, flag)
print('** %s **' % cmd)
subprocess.check_call(cmd, cwd=os.path.dirname(test), shell=True)
except Exception as err:
print("Error running '%s': %s" % (test, err))
pass
def setup_tests():
global tar_required
llvm_revision = urlopen(
"https://raw.githubusercontent.com/root-project/cling/master/LastKnownGoodLLVMSVNRevision.txt").readline().strip().decode(
'utf-8')
assert llvm_revision[:-2] == "release_"
branch_vers = llvm_revision[-2]
branch_ref = subprocess.check_output(
[
"git",
"ls-remote",
"https://github.com/llvm/llvm-project.git",
"release/{0}.x".format(branch_vers),
],
stderr=subprocess.STDOUT,
).decode()
commit = branch_ref[: branch_ref.find("\trefs/heads")]
# We get zip instead of git clone to not download git history
subprocess.Popen(
[
'sudo wget https://github.com/llvm/llvm-project/archive/{0}.zip && sudo unzip {0}.zip "llvm-project-{0}/llvm/utils/*"'.format(
commit
)
],
cwd=os.path.join(CLING_SRC_DIR, "tools"),
shell=True,
stdin=subprocess.PIPE,
stdout=None,
stderr=subprocess.STDOUT,
).communicate("yes".encode("utf-8"))
subprocess.Popen(
["sudo cp -r llvm-project-{0}/llvm/utils/FileCheck FileCheck".format(commit)],
cwd=os.path.join(CLING_SRC_DIR, "tools"),
shell=True,
stdin=subprocess.PIPE,
stdout=None,
stderr=subprocess.STDOUT,
).communicate("yes".encode("utf-8"))
with open(os.path.join(CLING_SRC_DIR, 'tools', 'CMakeLists.txt'), 'a') as file:
file.writelines('add_subdirectory(\"FileCheck\")')
exec_subprocess_call("cmake {0}".format(LLVM_OBJ_ROOT), CLING_SRC_DIR)
exec_subprocess_call("cmake --build . --target FileCheck -- -j{0}".format(multiprocessing.cpu_count()), LLVM_OBJ_ROOT)
if not os.path.exists(os.path.join(CLING_SRC_DIR, "..", "clang", "test")):
llvm_dir = exec_subprocess_check_output("llvm-config --src-root", ".").strip()
if llvm_dir == "":
if tar_required:
llvm_dir = copy.copy(srcdir)
else:
llvm_dir = os.path.join("/usr", "lib", "llvm-" + llvm_vers, "build")
subprocess.Popen(
["sudo mkdir {1}/utils/".format(commit, llvm_dir)],
cwd=os.path.join(CLING_SRC_DIR, "tools"),
shell=True,
stdin=subprocess.PIPE,
stdout=None,
stderr=subprocess.STDOUT,
).communicate("yes".encode("utf-8"))
subprocess.Popen(
[
"sudo mv llvm-project-{0}/llvm/utils/lit/ {1}/utils/".format(
commit, llvm_dir
)
],
cwd=os.path.join(CLING_SRC_DIR, "tools"),
shell=True,
stdin=subprocess.PIPE,
stdout=None,
stderr=subprocess.STDOUT,
).communicate("yes".encode("utf-8"))
def test_cling():
box_draw("Run Cling test suite")
# Run single tests on CI with this
# runSingleTest('Prompt/ValuePrinter/Regression.C')
# runSingleTest('Prompt/ValuePrinter')
build = Build('check-cling')
def tarball():
box_draw("Compress binaries into a bzip2 tarball")
tar = tarfile.open(prefix + '.tar.bz2', 'w:bz2')
print('Creating archive: ' + os.path.basename(prefix) + '.tar.bz2')
tar.add(prefix, arcname=os.path.basename(prefix))
tar.close()
gInCleanup = False
def cleanup():
global gInCleanup
if gInCleanup:
print('Failure in cleanup lead to recursion\n')
return
gInCleanup = True
print('\n')
if args['skip_cleanup']:
box_draw("Skipping cleanup")
return
box_draw("Clean up")
if os.path.isdir(LLVM_OBJ_ROOT):
print("Skipping build directory: " + LLVM_OBJ_ROOT)
if os.path.isdir(prefix):
print("Remove directory: " + prefix)
shutil.rmtree(prefix)
if os.path.isdir(TMP_PREFIX):
print("Remove directory: " + TMP_PREFIX)
shutil.rmtree(TMP_PREFIX)
if os.path.isfile(os.path.join(workdir, 'cling.nsi')):
print("Remove file: " + os.path.join(workdir, 'cling.nsi'))
os.remove(os.path.join(workdir, 'cling.nsi'))
if args['current_dev'] == 'deb' or args['last_stable'] == 'deb' or args['deb_tag']:
print('Create output directory: ' + os.path.join(workdir, 'cling-%s-1' % (VERSION)))
os.makedirs(os.path.join(workdir, 'cling-%s-1' % (VERSION)))
for file in glob.glob(os.path.join(workdir, 'cling_%s*' % (VERSION))):
print(file + '->' + os.path.join(workdir, 'cling-%s-1' % (VERSION), os.path.basename(file)))
shutil.move(file, os.path.join(workdir, 'cling-%s-1' % (VERSION)))
if not os.listdir(os.path.join(workdir, 'cling-%s-1' % (VERSION))):
os.rmdir(os.path.join(workdir, 'cling-%s-1' % (VERSION)))
if args['current_dev'] == 'dmg' or args['last_stable'] == 'dmg' or args['dmg_tag']:
if os.path.isfile(os.path.join(workdir, 'cling-%s-temp.dmg' % (VERSION))):
print("Remove file: " + os.path.join(workdir, 'cling-%s-temp.dmg' % (VERSION)))
os.remove(os.path.join(workdir, 'cling-%s-temp.dmg' % (VERSION)))
if os.path.isdir(os.path.join(workdir, 'Cling.app')):
print('Remove directory: ' + 'Cling.app')
shutil.rmtree(os.path.join(workdir, 'Cling.app'))
if os.path.isdir(os.path.join(workdir, 'cling-%s-temp.dmg' % (VERSION))):
print('Remove directory: ' + os.path.join(workdir, 'cling-%s-temp.dmg' % (VERSION)))
shutil.rmtree(os.path.join(workdir, 'cling-%s-temp.dmg' % (VERSION)))
if os.path.isdir(os.path.join(workdir, 'Install')):
print('Remove directory: ' + os.path.join(workdir, 'Install'))
shutil.rmtree(os.path.join(workdir, 'Install'))
gInCleanup = False
def check_version_string_ge(vstring, min_vstring):
version_fields = [int(x) for x in vstring.split('.')]
min_versions = [int(x) for x in min_vstring.split('.')]
for i in range(0,len(min_versions)):
if version_fields[i] < min_versions[i]:
return False
elif version_fields[i] > min_versions[i]:
return True
return True
###############################################################################
# Debian specific functions (ported from debianize.sh) #
###############################################################################
def check_ubuntu(pkg):
if pkg == "gnupg":
SIGNING_USER = exec_subprocess_check_output('gpg --fingerprint | grep uid | sed s/"uid *"//g', '/').strip()
if SIGNING_USER == '':
print(pkg.ljust(20) + '[INSTALLED - NOT SETUP]'.ljust(30))
return True
else:
print(pkg.ljust(20) + '[OK]'.ljust(30))
return True
elif pkg == "cmake":
CMAKE = os.environ.get('CMAKE', 'cmake')
output = exec_subprocess_check_output('{cmake} --version'.format(cmake=CMAKE), '/').strip().split('\n')[0].split()
if (output == []) or (not check_version_string_ge(output[-1], '3.4.3')):
print(pkg.ljust(20) + '[OUTDATED VERSION (<3.4.3)]'.ljust(30))
return False
else:
print(pkg.ljust(20) + '[OK]'.ljust(30))
elif pkg == "gcc":
if float(exec_subprocess_check_output('gcc -dumpversion', '/')[:3].strip()) <= 4.7:
print(pkg.ljust(20) + '[UNSUPPORTED VERSION (<4.7)]'.ljust(30))
return False
else:
print(pkg.ljust(20) + '[OK]'.ljust(30))
return True
elif pkg == "g++":
if float(exec_subprocess_check_output('g++ -dumpversion', '/')[:3].strip()) <= 4.7:
print(pkg.ljust(20) + '[UNSUPPORTED VERSION (<4.7)]'.ljust(30))
return False
else:
print(pkg.ljust(20) + '[OK]'.ljust(30))
return True
elif pkg == "lit":
if exec_subprocess_check_output('which lit', workdir) != '':
print(pkg.ljust(20) + '[OK]'.ljust(30))
return True
else:
print(pkg.ljust(20) + '[NOT INSTALLED]'.ljust(30))
return False
elif pkg == 'llvm-'+llvm_vers+'-dev':
if exec_subprocess_check_output('which llvm-config-{0}'.format(llvm_vers), workdir) != '':
print(pkg.ljust(20) + '[OK]'.ljust(30))
return True
else:
print(pkg.ljust(20) + '[NOT INSTALLED]'.ljust(30))
return False
elif exec_subprocess_check_output("dpkg-query -W -f='${Status}' %s 2>/dev/null | grep -c 'ok installed'" % (pkg),
'/').strip() == '0':
print(pkg.ljust(20) + '[NOT INSTALLED]'.ljust(30))
return False
else:
print(pkg.ljust(20) + '[OK]'.ljust(30))
return True
def tarball_deb():
box_draw("Compress compiled binaries into a bzip2 tarball")
tar = tarfile.open(os.path.join(workdir, 'cling_' + VERSION + '.orig.tar.bz2'), 'w:bz2')
tar.add(prefix, arcname=os.path.basename(prefix))
tar.close()
def debianize():
SIGNING_USER = exec_subprocess_check_output('gpg --fingerprint | grep uid | sed s/"uid *"//g',
CLING_SRC_DIR).strip()
box_draw("Set up the debian directory")
print("Create directory: debian")
os.makedirs(os.path.join(prefix, 'debian'))
print("Create directory: " + os.path.join(prefix, 'debian', 'source'))
os.makedirs(os.path.join(prefix, 'debian', 'source'))
print("Create file: " + os.path.join(prefix, 'debian', 'source', 'format'))
f = open(os.path.join(prefix, 'debian', 'source', 'format'), 'w')
f.write('3.0 (quilt)')
f.close()
print("Create file: " + os.path.join(prefix, 'debian', 'source', 'lintian-overrides'))
f = open(os.path.join(prefix, 'debian', 'source', 'lintian-overrides'), 'w')
f.write('cling source: source-is-missing')
f.close()
# This section is no longer valid. I have kept it as a reference if we plan to
# distribute libcling.so or any other library with the package.
if False:
print('Create file: ' + os.path.join(prefix, 'debian', 'postinst'))
template = '''
#! /bin/sh -e
# postinst script for cling
#
# see: dh_installdeb(1)
set -e
# Call ldconfig on libclang.so
ldconfig -l /usr/lib/libclang.so
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0
'''
f = open(os.path.join(prefix, 'debian', 'postinst'), 'w')
f.write(template)
f.close()
print('Create file: ' + os.path.join(prefix, 'debian', 'cling.install'))
f = open(os.path.join(prefix, 'debian', 'cling.install'), 'w')
template = '''
bin/* /usr/bin
docs/* /usr/share/doc
include/* /usr/include
lib/* /usr/lib
share/* /usr/share
'''
f.write(template.strip())
f.close()
print('Create file: ' + os.path.join(prefix, 'debian', 'compact'))
# Optimize binary compression
f = open(os.path.join(prefix, 'debian', 'compact'), 'w')
f.write("7")
f.close()
print('Create file: ' + os.path.join(prefix, 'debian', 'compat'))
f = open(os.path.join(prefix, 'debian', 'compat'), 'w')
f.write("9")
f.close()
print('Create file: ' + os.path.join(prefix, 'debian', 'control'))
f = open(os.path.join(prefix, 'debian', 'control'), 'w')
template = '''
Source: cling
Section: devel
Priority: optional
Maintainer: Cling Developer Team <[email protected]>
Uploaders: %s
Build-Depends: debhelper (>= 9.0.0)
Standards-Version: 3.9.5
Homepage: http://cling.web.cern.ch/
Vcs-Git: http://root.cern.ch/git/cling.git
Vcs-Browser: http://root.cern.ch/gitweb?p=cling.git;a=summary
Package: cling
Priority: optional
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}
Description: interactive C++ interpreter
Cling is a new and interactive C++11 standard compliant interpreter built
on the top of Clang and LLVM compiler infrastructure. Its advantages over