55665dc83d185878ea6ab557500b074137de4636
[senf.git] / site_scons / senfutil.py
1 import os.path, glob, site_tools.Yaptu
2 from SCons.Script import *
3
4 senfutildir = os.path.dirname(__file__)
5
6 # Fix for SCons 0.97 compatibility
7 try:
8     Variables
9 except NameError: 
10     Variables = Options
11     BoolVariable = BoolOption
12
13 def parseLogOption(value):
14     stream, area, level = ( x.strip() for x in value.strip().split('|') )
15     stream = ''.join('(%s)' % x for x in stream.split('::') )
16     if area : area = ''.join( '(%s)' % x for x in area.split('::') )
17     else    : area = '(_)'
18     return '((%s,%s,%s))' % (stream,area,level)
19
20 def expandLogOption(target, source, env, for_signature):
21     if env.get('LOGLEVELS'):
22         return [ 'SENF_LOG_CONF="' + ''.join( parseLogOption(x) for x in env.subst('$LOGLEVELS').split() )+'"']
23     else:
24         return []
25
26 class BuildTypeOptions:
27     def __init__(self, var):
28         self._var = var
29
30     def __call__(self, target, source, env, for_signature):
31         type = env['final'] and "final" or env['debug'] and "debug" or "normal"
32         return env[self._var + "_" + type]
33
34 def parseArguments(env, *defs):
35     vars = Variables(args=ARGUMENTS)
36     for d in defs : vars.Add(d)
37     vars.Update(env)
38     env.Help("""
39 Any construction environment variable may be set from the scons
40 command line (see SConstruct file and SCons documentation for a list
41 of variables) using
42
43    VARNAME=value    Assign new value  
44    VARNAME+=value   Append value at end
45
46 Special command line parameters:
47 """)
48     env.Help(vars.GenerateHelpText(env))
49     try                  : unknv = vars.UnknownVariables()
50     except AttributeError: unknv = vars.UnknownOptions()
51     for k,v in unknv.iteritems():
52         if k.endswith('+'):
53             env.Append(**{k[:-1]: v})
54         else:
55             env.Replace(**{k: v})
56
57
58 ###########################################################################
59 # This looks much more complicated than it is: We do three things here:
60 # a) switch between final or debug options
61 # b) parse the LOGLEVELS parameter into the correct SENF_LOG_CONF syntax
62 # c) check for a local SENF, set options accordingly and update that SENF if needed
63
64 def SetupForSENF(env, senf_paths = []):
65     global senfutildir
66     senf_paths.extend(('senf', '../senf', os.path.dirname(senfutildir), '/usr/local', '/usr'))
67     tooldir = os.path.join(senfutildir, 'site_tools')
68
69     env.Tool('Boost',       [ tooldir ])
70     env.Tool('PhonyTarget', [ tooldir ])
71     env.Tool('Yaptu',       [ tooldir ])
72     env.Tool('CopyToDir',   [ tooldir ])
73     env.Tool('Doxygen',     [ tooldir ])
74
75     env.Append(
76         LIBS              = [ 'senf', 'rt', '$BOOSTREGEXLIB',
77                               '$BOOSTIOSTREAMSLIB', '$BOOSTSIGNALSLIB',
78                               '$BOOSTFSLIB' ],
79         BOOSTREGEXLIB     = 'boost_regex',
80         BOOSTIOSTREAMSLIB = 'boost_iostreams',
81         BOOSTSIGNALSLIB   = 'boost_signals',
82         BOOSTFSLIB        = 'boost_filesystem',
83         
84         CXXFLAGS          = [ '-Wno-long-long', '$CXXFLAGS_' ],
85         CXXFLAGS_         = BuildTypeOptions('CXXFLAGS'),
86         
87         CPPDEFINES        = [ '$expandLogOption', '$CPPDEFINES_' ],
88         expandLogOption   = expandLogOption,
89         CPPDEFINES_       = BuildTypeOptions('CPPDEFINES'),
90         
91         LINKFLAGS         = [ '-rdynamic', '$LINKFLAGS_' ],
92         LINKFLAGS_        = BuildTypeOptions('LINKFLAGS'),
93
94         LOGLEVELS         = [ '$LOGLEVELS_' ],
95         LOGLEVELS_        = BuildTypeOptions('LOGLEVELS'),
96         )
97
98     rev = 'unknown'
99     if os.path.isdir('.svn'):
100         rev = 'r'+os.popen('svnversion').read().strip().lower()
101     elif os.path.isdir('.git'):
102         rev = 'r'+os.popen('gitsvnversion').read().strip().lower()
103     env.SetDefault( 
104         CXXFLAGS_final    = [],
105         CXXFLAGS_normal   = [],
106         CXXFLAGS_debug    = [],
107
108         CPPDEFINES_final  = [],
109         CPPDEFINES_normal = [],
110         CPPDEFINES_debug  = [],
111
112         LINKFLAGS_final   = [],
113         LINKFLAGS_normal  = [],
114         LINKFLAGS_debug   = [],
115
116         LOGLEVELS_final   = [],
117         LOGLEVELS_normal  = [],
118         LOGLEVELS_debug   = [],
119
120         PROJECTNAME       = "Unnamed project",
121         DOCLINKS          = [],
122         PROJECTEMAIL      = "nobody@nowhere.org",
123         COPYRIGHT         = "nobody",
124         REVISION          = rev,
125         )
126
127     # Interpret command line options
128     parseArguments(
129         env, 
130         BoolVariable('final', 'Build final (optimized) build', False),
131         BoolVariable('debug', 'Link in debug symbols', False),
132     )
133
134     # If we have a symbolic link (or directory) 'senf', we use it as our
135     # senf repository
136     for path in senf_paths:
137         if not path.startswith('/') : sconspath = '#/%s' % path
138         else                        : sconspath = path
139         if os.path.exists(os.path.join(path,"senf/config.hh")):
140             print "\nUsing SENF in '%s'\n" \
141                 % ('/..' in sconspath and os.path.abspath(path) or sconspath)
142             env.Append( LIBPATH = [ sconspath ],
143                         CPPPATH = [ sconspath ],
144                         BUNDLEDIR = sconspath )
145             try:
146                 env.MergeFlags(file(os.path.join(path,"senf.conf")).read())
147             except IOError:
148                 print "(SENF configuration file 'senf.conf' not found, assuming non-final SENF)"
149                 env.Append(CPPDEFINES = [ 'SENF_DEBUG' ])
150             break
151         elif os.path.exists(os.path.join(path,"include/senf/config.hh")):
152             print "\nUsing system SENF in '%s/'\n" % sconspath
153             env.Append(BUNDLEDIR = os.path.join(sconspath,"lib/senf"))
154             break
155     else:
156         print "\nSENF library not found .. trying build anyway !!\n"
157
158
159 def DefaultOptions(env):
160     env.Append(
161         CXXFLAGS         = [ '-Wall', '-Woverloaded-virtual' ],
162         CXXFLAGS_final   = [ '-O2' ],
163         CXXFLAGS_normal  = [ '-O0', '-g' ],
164         CXXFLAGS_debug   = [ '$CXXFLAGS_normal' ],
165
166         LINKFLAGS_normal = [ '-Wl,-S' ],
167         LINKFLAGS_debug  = [ '-g' ],
168     )
169
170 def Glob(env, exclude=[], subdirs=[]):
171     testSources = glob.glob("*.test.cc")
172     sources = [ x for x in glob.glob("*.cc") if x not in testSources and x not in exclude ]
173     for subdir in subdirs:
174         testSources += glob.glob(os.path.join(subdir,"*.test.cc"))
175         sources += [ x for x in glob.glob(os.path.join(subdir,"*.cc"))
176                      if x not in testSources and x not in exclude ]
177     return (sources, testSources)
178
179 def Doxygen(env, doxyheader=None, doxyfooter=None, doxycss=None, mydoxyfile=False, **kw):
180     # Additional interesting keyword arguments or environment variables:
181     #    PROJECTNAME, DOCLINKS, PROJECTEMAIL, COPYRIGHT
182
183     libdir=os.path.join(senfutildir, 'lib')
184     
185     if env.GetOption('clean'):
186         env.Clean('doc', env.Dir('doc'))
187         if not mydoxyfile:
188             env.Clean('doc', "Doxyfile")
189
190     if not mydoxyfile:
191         # Create Doxyfile NOW
192         site_tools.Yaptu.yaptuAction("Doxyfile", 
193                                      os.path.join(libdir, "Doxyfile.yap"),
194                                      env)
195
196     # The other files are created using dependencies
197     if doxyheader: 
198         doxyheader = env.CopyToDir(env.Dir("doc"), doxyheader)
199     else:
200         doxyheader = env.Yaptu("doc/doxyheader.html", os.path.join(libdir, "doxyheader.yap"), **kw)
201     if doxyfooter:
202         doxyfooter = env.CopyToDir(env.Dir("doc"), doxyfooter)
203     else:
204         doxyfooter = env.Yaptu("doc/doxyfooter.html", os.path.join(libdir, "doxyfooter.yap"), **kw)
205     if doxycss:
206         doxycss = env.CopyToDir(env.Dir("doc"), doxycss)
207     else:
208         doxycss    = env.CopyToDir(env.Dir("doc"), os.path.join(libdir, "doxy.css"))
209
210     doc = env.Doxygen("Doxyfile",
211                       DOXYOPTS   = [ '--html' ],
212                       DOXYENV    = { 'TOPDIR'     : env.Dir('#').abspath,
213                                      'LIBDIR'     : libdir,
214                                      'output_dir' : 'doc',
215                                      'html_dir'   : 'html',
216                                      'html'       : 'YES' },
217                       DOCLIBDIR  = libdir,
218                       DOXYGENCOM = "$DOCLIBDIR/doxygen.sh $DOXYOPTS $SOURCE")
219
220     env.Depends(doc, [ doxyheader, doxyfooter, doxycss ])
221
222     return doc