-
Notifications
You must be signed in to change notification settings - Fork 1
/
SConstruct
2166 lines (1647 loc) · 76.4 KB
/
SConstruct
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
# Emacs edit mode for this file is -*- python -*-
# Backward compatibility
if not 'Variables' in globals():
Variables = Options
BoolVariable = BoolOption
# Some hard-coded settings
pboriname = 'PolyBoRi'
try:
versionnumber = open('versionnumber', 'r').read().rstrip() + "-0"
(pboriversion, pborirevision) = versionnumber.split('-')[:2]
pborifullrevision = (pborirevision.split('.') + ['0', '0', '0'])[:3]
pborirelease = pborifullrevision[0]
except:
pboriversion = "0.0"
pborirevision = "0"
pborifullrevision = ['0', '0', '0']
pborirelease = "0"
debname = "polybori-" + pboriversion + '.' + pborirelease
import tarfile
import sys
from os import sep, path
from glob import glob
m4ri=Split("""grayflex.c permutation.c packedmatrix.c strassen.c
misc.c brilliantrussian.c trsm.c mmc.c echelonform.c pls.c pls_mmpf.c""")
m4ri=[path.join("M4RI/m4ri", m) for m in m4ri]
m4ri_inc = 'M4RI'
def ensure_dir(target, env):
target = env.subst(target)
if not path.exists(target):
try:
os.makedirs(target)
except:
# Maybe just a race condition occured, because two processes trixy
# to generate the directory at the same time. (This I could ignore.)
if not path.exists(target):
raise RuntimeError, "Could not mkdir " + target
def pathsplit(p, rest=[]):
(h,t) = os.path.split(p)
if len(h) < 1: return [t]+rest
if len(t) < 1: return [h]+rest
return pathsplit(h,[t]+rest)
def commonpath(l1, l2, common=[]):
if len(l1) < 1: return (common, l1, l2)
if len(l2) < 1: return (common, l1, l2)
if l1[0] != l2[0]: return (common, l1, l2)
return commonpath(l1[1:], l2[1:], common+[l1[0]])
def relpath(p1, p2):
(common,l1,l2) = commonpath(pathsplit(p1), pathsplit(p2))
p = []
if len(l1) > 0:
p = [ ('..' + sep) * len(l1) ]
p = p + l2
if len(p) == 0:
return ''
return os.path.join( *p )
def env_relpath(env, path, versus):
return relpath(env.subst(path), env.subst(versus))
Environment.relpath = env_relpath
def preprocessed_substitute(target, source, env):
def preprocess_at(page):
import re
p = re.compile('@([^@\n]*) @', re.VERBOSE)
return p.sub(r'$\1', page)
substitute_install(target, source, env, preprocess=preprocess_at)
# Fix some paths and names
class PathJoiner(object):
"""Generates a valid path from lists of strings, with custom prefix (set at
initialization). It also changes '/' to correct path separator."""
def __init__(self, *parent):
self.parent = path.join(*self.validpath(*parent))
def __call__(self, *args):
return path.join(self.parent, *self.validpath(*args))
def validpath(self, *args):
return [str(elt).replace('/', sep) for elt in args]
[TestsPath, PyPBPath, CuddPath, GBPath, PBPath, DocPath, BuildPath] = \
[ PathJoiner(fdir)
for fdir in Split("""testsuite PyPolyBoRi Cudd groebner libpolybori doc
build""") ]
M4RIPath = PathJoiner('M4RI')
M4RIInc = PathJoiner(M4RIPath('m4ri'))
DataPath = PathJoiner(TestsPath('py/data'))
DebPath = PathJoiner('pkgs/debian')
DebInstPath = PathJoiner('debian')
RPMPath = PathJoiner('pkgs/rpm')
SpecsPath = PathJoiner(RPMPath('SPECS'))
# Split lists separated by colons and whitespaces
def SplitColonSep(arg):
result = []
for element in Split(arg):
result += element.split(':')
return result
def shell_output(*args):
from subprocess import Popen, PIPE, STDOUT
process = Popen(args, stdin=None, stdout=PIPE, stderr=STDOUT, env=os.environ)
return process.communicate()[0].rstrip()
pyroot="pyroot/"
ipbroot = 'ipbori'
guiroot = 'gui'
cudd_name = 'pboriCudd'
[PyRootPath, IPBPath, GUIPath] = [PathJoiner(fdir) for fdir in [pyroot, ipbroot,
guiroot] ]
try:
import SCons.Tool.applelink as applelink
except:
pass
import os
def FinalizePermissions(targets, perm=None):
def isdll(path):
return 'dll' in os.path.basename(path).split(os.path.extsep)[1:]
for src in targets:
path = str(src)
if not os.path.islink(path):
if perm is None:
if os.path.isdir(path):
perm = 040755
else:
if os.access(path, os.X_OK) or isdll(path):
perm = 0755
else:
perm = 0644
env.AddPostAction(src, Chmod(path, perm))
return targets
def FinalizeExecs(targets):
return FinalizePermissions(targets, 0755)
def FinalizeNonExecs(targets):
return FinalizePermissions(targets, 0644)
distribute = 'distribute' in COMMAND_LINE_TARGETS
prepare_deb = 'prepare-debian' in COMMAND_LINE_TARGETS
generate_deb = 'deb' in COMMAND_LINE_TARGETS
deb_generation = prepare_deb or generate_deb
generate_rpm = 'rpm' in COMMAND_LINE_TARGETS
generate_srpm = 'srpm' in COMMAND_LINE_TARGETS
prepare_rpm = 'prepare-rpm' in COMMAND_LINE_TARGETS
rpm_generation = generate_rpm or generate_srpm or prepare_rpm
# Undocumented switches (for debugging foreign platforms)
defaultopts = Variables() # Works only from command line
defaultopts.Add('PLATFORM', "Manually set another platform (unusual)")
defaultopts.Add('TOOLS', "Manually set toolchain (unusual)", converter = Split)
defaultenv = Environment(ENV = os.environ, options=defaultopts)
# See also: http://trac.sagemath.org/sage_trac/ticket/9872 and #6437
def detect_linker(env):
import re
args = env.subst('$CC').split() + ['-Wl,-v']
if re.search("Binutils|GNU", shell_output(*args)):
return "gnu"
# Non-gnu linker or linux (could be Sun or Intel linker) will return 'posix'.
return env['PLATFORM']
def detect_compiler(env):
import re
args = env.subst('$CC').split() + ['-v']
if re.search("gcc version", shell_output(*args)):
return "gnu"
# Non-gnu linker or linux (could be Sun or Intel linker) will return 'posix'.
return env['PLATFORM']
# for gentoo-prefix on OS X
def _fix_dynlib_flags(env):
if env['PLATFORM']=="darwin":
return "-Wl,-flat_namespace"
return ''
def _sonameprefix(env):
linker = detect_linker(env)
#print linker, "linker detected!"
if env['PLATFORM']=="darwin":
return "-install_name @loader_path/"
elif (env['PLATFORM'] == "sunos") and (linker == 'sunos'):
return '-Wl,-h'
else:
return '-Wl,-soname,'
# dynamic module flags
def _dynmodule_flags(env):
"""Creates special flags for dynamic libraries, in particular on darwin."""
if env['PLATFORM'] == "darwin":
return "-Wl,-undefined -Wl,dynamic_lookup"
else:
return ""
def _moduleflags(env):
if env['PLATFORM']=="darwin":
python_absolute = shell_output("which", env.subst("$PYTHON"))
return ["-fvisibility=hidden", "-bundle_loader", python_absolute]
return []
def _relative_rpath(target, env):
if not target or env['PLATFORM'] in ["darwin", "cygwin"]:
return ''
targetdir = os.path.dirname(env.subst(str(target)))
libdir = BuildPath(env['DEVEL_LIB_PREFIX'].lstrip(sep))
relative_path = '\\$$ORIGIN/' + env.relpath(targetdir, libdir)
return [env['RPATHPREFIX'] + relative_path + env['RPATHSUFFIX'],
'-z', 'origin']
def scons_version():
import SCons
return SCons.__version__.split('.')
def oldstyle_flags():
return scons_version() < ['0','97','0']
class ExtendedVariables:
def __init__(self, vars, defaults):
from weakref import proxy
vars.AddWithDefaults = self
self.vars = proxy(vars)
self.defaults = defaults
def __call__(self, varname, *args, **kwds):
self.vars.Add(varname, *args, **kwds)
self.vars.Add('DEFAULT_' + varname,
"defaults appended to " + repr(varname),
self.defaults[varname])
pbori_cache_macros=["PBORI_UNIQUE_SLOTS","PBORI_CACHE_SLOTS","PBORI_MAX_MEMORY"]
def setup_env(defaultenv):
opts = Variables('custom.py')
ExtendedVariables(opts, defaultenv)
# Define option handle, may be changed from command line or custom.py
opts.Add('CXX', 'C++ Compiler (inherited from SCons)',
defaultenv['CXX'])
opts.Add('CC', 'C Compiler (inherited from SCons)',
defaultenv['CC'])
opts.Add('SHCXX',
'C++ Compiler (preparing shared libraries; inherited from SCons)',
defaultenv['SHCXX'])
opts.Add('SHCC',
'C Compiler (preparing shared libraries; inherited from SCons)',
defaultenv['SHCC'])
opts.Add('PYTHON', 'Python executable', "python$PROGSUFFIX")
opts.Add('LIBPATH', 'list of library paths (colon or whitespace separated)',
defaultenv.get('LIBPATH', []), converter = SplitColonSep)
opts.Add('CPPPATH', 'list of include paths (colon or whitespace separated)',
defaultenv.get('CPPPATH', []), converter = SplitColonSep)
opts.Add('TEST_CPPPATH', 'list of include paths for tests (colon or whitespace separated)',
'', converter = SplitColonSep)
opts.Add('CPPDEFINES', 'list of preprocessor defines (whitespace separated)',
defaultenv.get('CPPDEFINES',[]) + ['PBORI_NDEBUG'], converter = Split)
if oldstyle_flags() :
defaultenv.Append(CCFLAGS=["-std=c99", "$M4RI_CFLAGS"])
defaultenv.Append(CXXFLAGS=["-std=c++98", "$M4RI_CFLAGS",
"-ftemplate-depth-100"])
for (var, help, default) in [('CCFLAGS', "C compiler flags", ["-O3"]),
('CXXFLAGS', "C++ compiler flags", ["-O3"])]:
opts.AddWithDefaults(var, help, default, converter=Split)
else:
defaultenv.Append(CCFLAGS=["$M4RI_CFLAGS"])
defaultenv.Append(CFLAGS=["-std=c99"])
defaultenv.Append(CXXFLAGS=["-std=c++98", "-ftemplate-depth-100"])
for (var, help, default) in [('CCFLAGS', "C/C++ compiler flags", ["-O3"]),
('CFLAGS', "C compiler flags", []),
('CXXFLAGS', "C++ compiler flags", [])]:
opts.AddWithDefaults(var, help, default, converter=Split)
opts.Add('M4RI_CFLAGS', "C compiler flags for M4RI", converter = Split)
defaultenv.Append(LINKFLAGS=['${_fix_dynlib_flags(__env__)}',
'${_relative_rpath(TARGET, __env__)}'])
defaultenv.Append(SHLINKFLAGS=['$SONAMEFLAGS'])
defaultenv.Append(LDMODULEFLAGS=['${_moduleflags(__env__)}'])
defaultenv.Append(LIBS=[])
opts.AddWithDefaults('LINKFLAGS',
"Custom linker flags (e.g. '-s' for stripping)", [],
converter=Split)
opts.AddWithDefaults('SHLINKFLAGS', 'Shared libraries link flags.', [],
converter=Split)
opts.AddWithDefaults('LDMODULEFLAGS',
'Dynamic module compile flags', [], converter=Split)
for flag in Split("""SHCCFLAGS SHCFLAGS SHCXXFLAGS FRAMEWORKS"""):
if defaultenv.has_key(flag):
opts.AddWithDefaults(flag, "flags inherited from SCons",
[], converter=Split)
else:
print "Flags", flag, "not in default environment!"
opts.AddWithDefaults('LIBS', 'custom libraries needed for build', [],
converter = Split)
opts.Add('GD_LIBS', 'Library gb and its dependencies (if needed)',
["gd"], converter = Split)
opts.Add('PREFIX', 'installation prefix directory', '$DESTDIR/usr/local')
opts.Add('EPREFIX','executables installation prefix directory', '$PREFIX/bin')
opts.Add('INSTALLDIR', 'end user installation directory',
'$PREFIX/share/polybori')
opts.Add('DOCDIR', 'documentation installation directory',
'$INSTALLDIR/doc')
opts.Add('MANDIR', 'Man-pages installation directory',
'$PREFIX/man')
opts.Add('ICONDIR', 'Icon installation directory', '$PREFIX/share/pixmaps')
opts.Add('PYINSTALLPREFIX',
'python modules directory (default is built-in site)', '$DESTDIR$PYTHONSITE')
opts.Add('DEVEL_PREFIX',
'development version installation directory','$PREFIX' )
opts.Add('DEVEL_INCLUDE_PREFIX',
'development version header installation directory',
'$DEVEL_PREFIX/include' )
opts.Add('DEVEL_LIB_PREFIX',
'development version library installation directory',
'$DEVEL_PREFIX/lib' )
opts.Add(BoolVariable('M4RI_RPM',
'Assume rpm knows about M4RI', False))
opts.Add(BoolVariable('HAVE_DOXYGEN',
'Generate doxygen-based documentation, if available', '$DOCS'))
opts.Add(BoolVariable('HAVE_PYTHON_EXTENSION',
'Build python extension, if possible', True))
opts.Add('BOOST_PYTHON',
'Name of Boost-python library to link with', 'boost_python')
opts.Add('BOOST_TEST',
'Name of Boost unit test framework library to link with',
'boost_unit_test_framework')
opts.Add(BoolVariable('RELATIVE_SYMLINK',
'Use relative symbolic links on install', True))
opts.Add(BoolVariable('HAVE_L2H', 'Switch latex2html on/off (deprecated)',
False))
opts.Add(BoolVariable('HAVE_HEVEA', 'Switch hevea on/off (deprecated)', False))
opts.Add(BoolVariable('HAVE_TEX4HT', 'Switch tex4ht on/off', '$DOCS'))
opts.Add(BoolVariable('HAVE_PYDOC', 'Switch python doc generation on/off',
True))
opts.Add(BoolVariable('EXTERNAL_PYTHON_EXTENSION', 'External python interface',
False))
opts.Add(BoolVariable('USE_TIMESTAMP', 'Use timestamp on distribution', True))
opts.Add(BoolVariable('SHLIBVERSIONING',
'Use libtool-style versionated shared library', True))
opts.Add('SONAMEPREFIX', 'Prefix for compiler soname command.',
'${_sonameprefix(__env__)}')
opts.Add('SONAMESUFFIX','Suffix for compiler soname command.', '')
opts.Add('SONAMEFLAGS',
'Shared libraries link flags.',
['${_sonamecmd(SONAMEPREFIX, TARGET, SONAMESUFFIX, __env__)}'])
opts.Add('INSTALL_NAME_DIR',
'Path to be used for dylib install_name (darwin only)',
'@loader_path')
opts.Add('SHLIBVERSIONSUFFIX',
'Shared libraries suffix for library versioning.',
'-' + pboriversion +
defaultenv['SHLIBSUFFIX'] + '.$LIBRARY_VERSION')
opts.Add(BoolVariable('FORCE_HASH_MAP', "Force the use of gcc's deprecated " +
"hash_map extension, even if unordered_map is available (avoiding of buggy " +
"unordered_map)", False))
opts.Add('RPATH', "rpath setting", '', converter = SplitColonSep)
for m in pbori_cache_macros:
opts.Add(m, 'PolyBoRi Cache macro value: '+m, '')
for var in Split("""CCCOM CXXCOM SHCCCOM SHCXXCOM SHLINKCOM LINKCOM LINK SHLINK
SHLIBPREFIX LIBPREFIX SHLIBSUFFIX LIBSUFFIX"""):
if defaultenv.has_key(var):
opts.Add(var,
"inherited from SCons", defaultenv[var])
else:
if var != "LIBSUFFIX":
print "Variable", var, "not in default environment!"
opts.Add('LIBRARY_VERSION', "libtool-style library version",
'.'.join(pborifullrevision))
opts.Add('CONFFILE', "Dump settings to file, if given", '')
opts.Add('PKGCONFIGPATH',
"Write settings to pkg-config file in path, if given", '')
opts.Add('DESKTOPPATH',
"Generate .desktop file in given path, if given", '')
opts.Add('DESTDIR', "Temporary installation directory, if given", '')
opts.Add('M4RIURL',
"""Source destinations for missing m4ri download:
space-separated list of local files or pairs <URL>#<MD5>, '' skips""",
"""m4ri-20121224.tar.gz
http://m4ri.sagemath.org/downloads/m4ri-20121224.tar.gz#1a2a59b547fed9e825ff9135a21ba53b""",
converter=Split)
opts.Add(BoolVariable('DOCS',
"Build/install platform-independent documantation",
True))
opts.Add('PLATFORM', "Manually set another platform (unusual)",
defaultenv['PLATFORM'])
tools = defaultenv['TOOLS'] + ["disttar", "doxygen"]
# Get paths and related things from current environment os.environ
# note: We cannot avoid those due to non-standard system setups,
# also we do not know which variables are used in general
return (Environment(ENV = os.environ, options = opts, tools = tools,
toolpath = '.'), opts, tools)
(env, opts, tools) = setup_env(defaultenv)
if defaultenv['PLATFORM'] == "sunos": # forcing gcc, keeping linker
def is_gnu():
compilerenv = Environment(ENV = os.environ, options = opts)
return (detect_compiler(compilerenv) == 'gnu',
detect_linker(compilerenv) == 'gnu')
(is_gcc, is_gnulink) = is_gnu()
tools = [tool for tool in defaultenv['TOOLS']]
if is_gcc:
for arg in ['default', 'suncc', 'sunc++', 'sunar']:
if arg in tools:
tools.remove(arg)
tools += [ 'gcc', 'g++', 'ar']
if is_gnulink:
if 'sunlink' in tools:
tools.remove('sunlink')
tools += ['gnulink']
else:
if 'gnulink' in tools:
tools.remove('gnulink')
tools += ['sunlink']
if tools != defaultenv['TOOLS']:
platform_opts = Variables(args={'PLATFORM': defaultenv['PLATFORM']})
defaultenv = Environment(ENV=os.environ, tools=tools,
options=platform_opts)
(env, opts, tools) = setup_env(defaultenv)
# Monkey patching Install/InstallAs to fix permissions on install
_env_install = env.Install
_env_installas = env.InstallAs
def _env_install_final(env, *args):
return FinalizePermissions(_env_install(env, *args))
def _env_installas_final(env, *args):
return FinalizePermissions(_env_installas(env, *args))
_env_install_final.__doc__ = env.Install.__doc__
_env_installas_final.__doc__ = env.InstallAs.__doc__
env.Install = _env_install_final
env.InstallAs = _env_installas_final
# Another monkey patch: Ensure that necessary flags are appended
# (explicitely set DEFAULT_<flags>="" if defaults should be removed)
for key in env.Dictionary().keys():
if key.startswith('DEFAULT_'):
env.AppendUnique(**{key.replace('DEFAULT_',''): ['$' + key]})
# Extract some option values
HAVE_DOXYGEN = env['HAVE_DOXYGEN'] and ("doxygen" in tools)
HAVE_PYTHON_EXTENSION = env['HAVE_PYTHON_EXTENSION']
USERLIBS = list(env.get('LIBS', []))
# Skipping doxygen-based docu, if no doxygen is found.
if HAVE_DOXYGEN:
HAVE_DOXYGEN = env.Detect('doxygen')
if not HAVE_DOXYGEN:
print "Doxygen not found, skipping C++-documentation generation!"
# soname related stuff
def _sonamecmd(prefix, target, suffix, env = env):
"""Creates soname."""
target = str(env.subst(target))
import re
soPattern = re.compile('(.*)\.[0-9]*\.[^.]*$', re.I|re.S)
soname = soPattern.findall(path.basename(target))
if len(soname) > 0:
return prefix + soname[0] + suffix
else:
if env['PLATFORM']=="darwin":
return prefix + path.basename(target) + suffix
return ''
env['_sonameprefix'] = _sonameprefix
env['_sonamecmd'] = _sonamecmd
env['_fix_dynlib_flags'] = _fix_dynlib_flags
env['_moduleflags'] = _moduleflags
env['_relative_rpath'] = _relative_rpath
env['_dynmodule_flags'] = _dynmodule_flags
# config.h generator
def config_h_build(target, source, env):
""" config_h building..."""
def define_line(name, value):
return """#ifndef %(name)s
#define %(name)s %(value)s
#endif
""" % dict(name=name, value=value)
from string import join
macros = [elt.split('=') + [''] for elt in env['CPPDEFINES'] ]
for macro in pbori_cache_macros:
if env.get(macro, None): macros += [ (macro, env[macro]) ]
config_defs = join([define_line(elt[0], elt[1]) for elt in macros], '')
config_h_in = """/* File: %(target)s
* Automatically generated by PolyBoRi %(version)s */
#ifndef polybori_config_h_
#define polybori_config_h_
%(defs)s
#endif /* polybori_config_h_ */
"""
config_ver = pboriversion + '.' + pborirevision
for a_target, a_source in zip(target, source):
config_h = file(str(a_target), "w")
conf_repl = dict(target=a_target, version=config_ver, defs=config_defs)
config_h.write(config_h_in % conf_repl)
config_h.close()
def config_h_message(*args):
return "writing config.h..."
config_h = env.Command(PBPath('include/polybori/config.h'),
'SConstruct',
action = env.Action(config_h_build,
config_h_message))
env.AlwaysBuild(config_h)
class PythonConfig(object):
def __init__(self, python_executable):
def querycmd(arg):
from subprocess import Popen, PIPE, STDOUT
process = Popen([self.python], stdin=PIPE, stdout=PIPE, stderr=STDOUT,
env=os.environ)
return process.communicate("from distutils.sysconfig import *\n" +
"print " + arg + "\n")[0].strip()
self.python = python_executable
self.version = querycmd("get_python_version()")
self.major = self.version.split('.')[0]
self.sitedir = querycmd("get_python_lib()")
self.libdir = querycmd("get_config_vars()['LIBDIR']")
self.incdir = querycmd("get_python_inc()")
self.staticlibdir = querycmd("get_config_vars()['LIBPL']")
self.libs = querycmd("get_config_vars()['LIBS']")
self.module_suffix = querycmd("get_config_vars()['SO']")
self.libs = self.libs.split()
if env['PLATFORM']=="darwin":
#workaround for -framework, CoreFoundation entries...
self.libs=[l for l in self.libs if l.startswith('-l')]
self.libs=[l.replace('-l','') for l in self.libs]
self.libname = 'python' + str(self.version)
pyconf = PythonConfig(env.subst("$PYTHON"))
env.AppendUnique(PYTHONSITE = pyconf.sitedir)
have_l2h = have_t4h = False
external_m4ri = False
GD_LIBS = []
BOOST_TEST = env['BOOST_TEST']
dylibs = []
stlibs = []
def check_variants(conf, libname, header, generators, priority):
if not libname:
return None
if header:
def checklib(name):
return conf.CheckLibWithHeader(name, header, 'c++', autoadd=0)
else:
def checklib(name):
return conf.CheckLib(name, autoadd=0)
names=[[]]
for idx in priority:
gen = generators[idx]
names += [name + [(idx, elt)] for name in names for elt in gen]
for elt in names:
namelist = map(lambda x:x[1], sorted(elt, key=lambda x:x[0]))
name = '-'.join([libname] + namelist);
if checklib(name):
return name
return None
def check_boost_variants(conf, libname, header=None):
return check_variants(conf, libname, header,
[[pyconf.version], ['gcc'], ['mt', 'mt-p'],
['_'.join(map(str, env['BOOST_VERSION'][0:nlen]))
for nlen in [2,3] ] ], [3,0,2,1])
######################################################################
# Paths
######################################################################
InstPyPath = PathJoiner(env['PYINSTALLPREFIX'])
DevelInstPath = PathJoiner(env['DEVEL_PREFIX'])
PBInclPath = PathJoiner(PBPath('include/polybori'))
DevelInstInclPath = PathJoiner(env['DEVEL_INCLUDE_PREFIX'], 'polybori')
DevelInstLibPath = PathJoiner(env['DEVEL_LIB_PREFIX'])
BuildLibPath = PathJoiner(BuildPath(DevelInstLibPath().lstrip(sep)))
BuildInclPath = PathJoiner(BuildPath(DevelInstInclPath().lstrip(sep)))
BuildInclTopPath = PathJoiner(BuildPath(env.subst('$DEVEL_INCLUDE_PREFIX').lstrip(sep)))
BuildPyPBPath = PathJoiner(BuildPath(InstPyPath('polybori/dynamic').lstrip(sep)))
#######################################################################
m4ri_png = False
retrieve_m4ri = False
libm4ri = []
if not env.GetOption('clean'):
def BoostVersion(context):
# Boost versions are in format major.minor.subminor
context.Message('Detecting Boost version... ')
(result, values) = context.TryRun("""
#include <boost/version.hpp>
#include <iostream>
int main() {
std::cout << BOOST_VERSION;
return 0;
}
""", '.cpp')
result = (result == 1)
if result:
values = (int(values[0:-5]), int(values[-5:-2]), int(values[-2:-1]))
context.Display('.'.join(map(str, values)) + '... ')
else:
values = [0]*3
env.Append(BOOST_VERSION=values)
context.Result(result)
return result
def CheckSizeOfTypes(context):
context.Message('Detecting type sizes... ')
test_src_sizeof = """
#include <stdio.h>
int main(int argc, char **argv) {
printf("SIZEOF_VOID_P=%u SIZEOF_INT=%u SIZEOF_LONG=%u",
(unsigned)sizeof(void*), (unsigned)sizeof(int), (unsigned)sizeof(long));
return 0;
}
"""
(result, values) = context.TryRun(test_src_sizeof, '.c')
result = (result == 1)
if result:
context.Display('got ' + values + '...')
env.Append(CPPDEFINES=Split(values))
context.Result(result)
return result
def CheckLongLong(context):
context.Message('Checking whether C++ knows about long long... ')
test_src_longlong = """
int main(int argc, char **argv) {
long long val = 0LL;
return (int)val;
}
"""
(result, values) = context.TryRun(test_src_longlong, '.cc')
result = (result == 1)
context.Result(result)
return result
def M4RIConfig(context, url, hash, tmpdir):
def userAction(target,source,env):
import urllib
(tmpfile, headers) = urllib.urlretrieve(url, target[0].abspath)
if hash or not path.exists(env.File(url).abspath):
import hashlib
m = hashlib.md5()
for elt in open(tmpfile,"rb").readlines(): m.update(elt)
if m.hexdigest() != hash: return "hash mismatch"
import tarfile
tar = tarfile.open(tmpfile)
if not path.exists(tmpdir): ensure_dir(tmpdir, env)
tar.extractall(tmpdir)
tar.close()
env.Execute(Move(path.join(tmpdir, path.basename(url)), tmpfile))
return None
context.Message(" Downloading m4ri sources from " + repr(url) \
+ " to " + repr(tmpdir) + " ... ")
ret = context.TryAction(action=Action(userAction))[0]
context.Result(ret)
if ret == 1:
context.Message(" Configuring m4ri...")
ret = context.TryAction(" ".join(["cd",
path.join(tmpdir, path.basename(url).split('.')[0]),
"; ./configure",
"--prefix=" + env.Dir(BuildPath()).abspath,
"--libdir=" + env.Dir(BuildLibPath()).abspath,
"--includedir=" + \
env.Dir(BuildInclTopPath()).abspath]))[0]
context.Result( ret )
return ret
def GuessM4RIFlags(context, external):
context.Message('Guessing m4ri compile flags... ')
if not external:
if not os.path.exists(M4RIInc('config.h')):
context.Message("Abusing m4ri's configure to get headers... ")
Execute("cd M4RI; ./configure --prefix=$PREFIX; cd -")
test_src = """
#include <m4ri/%s>
#include <stdio.h>
int main(int argc, char **argv) {
#ifdef __M4RI_SIMD_CFLAGS
/* get relevant compile flags of M4RI */
printf(__M4RI_SIMD_CFLAGS);
printf(" ");
#elif defined(__M4RI_CFLAGS)
/* fall back: get compile flags of M4RI */
printf(__M4RI_CFLAGS);
printf(" ");
#else
/* fall back: test for possible current and future configurations */
%s
#endif
return 0;
}
""" % \
("%s", ''.join(["""
#if (defined(__M4RI_HAVE_%(macro)s) && (__M4RI_HAVE_%(macro)s)) || \
defined(HAVE_%(macro)s)
printf("-m%(option)s ");
#endif""" % \
dict(macro=opt.replace('.','_').upper(), option=opt) for opt in \
Split("sse sse2 sse3 sse4 sse4.1 sse4.2 sse4a ssse3 mmx 3dnow") ]) )
(result, values) = context.TryRun(test_src % "m4ri_config.h", '.c')
if result != 1:
(result, values) = context.TryRun(test_src % "config.h", '.c')
result = (result == 1)
if result:
context.Display(values)
env.Append(M4RI_CFLAGS=Split(values))
context.Result(result)
return result
conf = Configure(env,
custom_tests = {'CheckSizeOfTypes': CheckSizeOfTypes,
'CheckLongLong': CheckLongLong,
'GuessM4RIFlags': GuessM4RIFlags,
'BoostVersion': BoostVersion,
'M4RIConfig': M4RIConfig })
if not conf.CheckSizeOfTypes():
print "Could not detect type sizes (maybe compile/link flags " + \
"trouble)! Exiting."
Exit(1)
if conf.CheckLongLong():
env.Append(CPPDefines='PBORI_HAVE_LONG_LONG')
if env['FORCE_HASH_MAP']:
if conf.CheckCXXHeader('ext/hash_map'):
env.Append(CPPDEFINES=["PBORI_HAVE_HASH_MAP"])
else:
if conf.CheckCXXHeader('unordered_map'):
env.Append(CPPDEFINES=["PBORI_HAVE_UNORDERED_MAP"])
elif conf.CheckCXXHeader('tr1/unordered_map'):
env.Append(CPPDEFINES=["PBORI_HAVE_TR1_UNORDERED_MAP"])
elif conf.CheckCXXHeader('ext/hash_map'):
env.Append(CPPDEFINES=["PBORI_HAVE_HASH_MAP"])
extern_python_ext = env['EXTERNAL_PYTHON_EXTENSION']
if HAVE_PYTHON_EXTENSION or extern_python_ext:
env.Append(CPPPATH=[pyconf.incdir])
env.Append(LIBPATH=[pyconf.libdir, pyconf.staticlibdir])
env.Prepend(CPPPATH=[PBPath('include'), GBPath('include')])
env.Append(CPPDEFINES=["PBORI_HAVE_M4RI"])
if HAVE_PYTHON_EXTENSION:
if not (conf.CheckLib(pyconf.libname, autoadd=0)):
print "Python library not available (needed for python extension)!"
HAVE_PYTHON_EXTENSION = False
if HAVE_PYTHON_EXTENSION:
if not (conf.CheckCXXHeader(path.join('boost', 'python.hpp'))):
print "Developer's version of boost/python not available ",
print "(needed for python extension)!"
HAVE_PYTHON_EXTENSION = False
conf.BoostVersion()
if HAVE_PYTHON_EXTENSION:
store_libs =[elt for elt in env["LIBS"]]
env.Append(LIBS=pyconf.libname)
BOOST_PYTHON = check_boost_variants(conf, env['BOOST_PYTHON'],
path.join('boost', 'python.hpp'))
if BOOST_PYTHON is None:
print "Warning Boost/Python library BOOST_PYTHON =",
print repr(env['BOOST_PYTHON']), "(or variants) not available " +\
"(needed for python extension)!"
HAVE_PYTHON_EXTENSION = False
env['BOOST_PYTHON'] = BOOST_PYTHON
env["LIBS"] = store_libs
BOOST_TEST = check_boost_variants(conf, env['BOOST_TEST'])
if BOOST_TEST is None:
print "Warning Boost/unit test framework library BOOST_TEST =",
print repr(env['BOOST_TEST']), " not available. Skipping tests."
env['BOOST_TEST'] = BOOST_TEST
have_l2h = env['HAVE_L2H'] and env.Detect('latex2html')
tex_to_ht = 'hevea'
if not have_l2h:
have_t4h = env['HAVE_HEVEA'] and env.Detect('hevea')
t4h_opts = ''
if not have_t4h:
have_t4h = env['HAVE_TEX4HT'] and env.Detect('htlatex')
tex_to_ht = 'htlatex'
if not have_t4h:
print "Warning: No LaTeX to html converter found,",
print "Tutorial will not be installed"
external_m4ri = conf.CheckLib('m4ri', autoadd=0)
if external_m4ri:
libm4ri = ['m4ri']
if conf.CheckFunc('testing_m4ri_PNGs', """
#include <m4ri/io.h>
#if defined(__M4RI_HAVE_LIBPNG) && __M4RI_HAVE_LIBPNG
#define testing_m4ri_PNGs()
#else
#define testing_m4ri_PNGs() fail fail fail
#endif """):
m4ri_png = True
else:
tmpdir = BuildPath('tmp')
urls = [(elt + '#').split('#')[:2] for elt in Split(env.subst('$M4RIURL'))]
for (url, hash) in urls:
m4ri_name = path.basename(url).split('.')[0]
m4ri_dir = path.join(tmpdir, m4ri_name)
if conf.M4RIConfig(url, hash, tmpdir):
env.Prepend(CPPPATH=m4ri_dir)
libm4ri = ['m4ri']
external_m4ri = retrieve_m4ri = m4ri_png = True
env['PB_M4RI_SRC'] = m4ri_name + '.tar.gz'
env['M4RIVERSION'] = m4ri_name[-8:]
break
if not external_m4ri:
print " Cannot build without m4ri!"
Exit(1)
if m4ri_png:
env.Append(CPPDEFINES=["PBORI_HAVE_M4RI_PNG"])
for suffix in ['', '12', '13', '10', '11']:
if conf.CheckLib('png' + suffix, autoadd=0):
GD_LIBS = ['png' + suffix]
break
conf.GuessM4RIFlags(external_m4ri)
if not m4ri_png:
gdlibs = env["GD_LIBS"]
if gdlibs and conf.CheckCHeader("gd.h"):
store_libs = [elt for elt in env["LIBS"]]
env.Append(LIBS=gdlibs[1:])
if conf.CheckLib(gdlibs[0], autoadd=0):
env["LIBS"] = store_libs
env.Append(LIBS=gdlibs)
if conf.CheckFunc("testing_PNGs",
"#include<gd.h>\n#define testing_PNGs() gdImagePng(NULL,NULL) "):
env.Append(CPPDEFINES=["PBORI_HAVE_GD"])
GD_LIBS = gdlibs
else:
print "libgd is available, but could not generate png file -",\
"dependencies in GD_LIBS missing? -", \
"Skipping gd-based optional features."
env["LIBS"] = store_libs
env = conf.Finish()
else: # when cleaning