2 # \brief SENFSCons package
4 ## \package senfscons.SENFSCons
5 # \brief Build helpers and utilities
7 # The SENFSCons package contains a number of build helpers and
8 # utilities which are used to simplify commmon tasks.
10 # The utitlities of this package are grouped into:
11 # <dl><dt>\ref use</dt><dd>help using complex environments and
12 # configure the construction environmen correspondingly</dd>
14 # <dt>\ref target</dt><dd>simplify building common targest and include
15 # enhanced functionality like unit-testing.</dd></dl>
17 # Additionally for external use are
18 # <dl><dt>MakeEnvironment()</dt><dd>Build construction
21 # <dt>GlobSources()</dt><dd>Utility to find source files</dd></dl>
23 # All other functions are for internal use only.
26 import SCons.Options, SCons.Environment, SCons.Script.SConscript, SCons.Node.FS, SCons.Defaults
28 ## \defgroup use Predefined Framework Configurators
30 # The following framework configurators are used in the top level \c
31 # SConstruct file to simplify more complex configurations.
33 # Each of the framework configurators introduces additional
34 # configuration parameters to \ref sconfig
36 ## \defgroup target Target Helpers
38 # To specify standard targets, the following helpers can be used. They
39 # automatically integrate several modules (like documentation,
42 ## \defgroup builder Builders
44 # The SENFSCons framework includes a series of builders. Each builder
45 # is defined in it's own package.
47 # Tools to load in MakeEnvironment
56 # This is the directory SENFSCons.py resides
57 basedir = os.path.abspath(os.path.split(__file__)[0])
59 ## \brief Initialize configuration options
63 if opts is not None: return
64 opts = SCons.Options.Options('SConfig')
65 opts.Add('CXX', 'C++ compiler to use', 'g++')
66 opts.Add('EXTRA_DEFINES', 'Additional preprocessor defines', '')
67 opts.Add('EXTRA_LIBS', 'Additional libraries to link against', '')
68 opts.Add(SCons.Options.BoolOption('final','Enable optimization',0))
70 # A finalizer is any callable object. All finalizers will be called
71 # in MakeEnvironment. We use them so every finalizer has knowledge of
72 # all frameworks in use (e.g.: the boost runtime depends on the use of
75 ## \brief Register finalizer
81 ## \brief Initialize the use of the <a href="http://www.boost.org/">Boost</a> library
83 # Configure the use of the <a href="http://www.boost.org">Boost</a>
84 # libraries. Most of these libraries are header-only, some however
85 # depend on a built library. The library selection is somewhat
86 # involved and depends on the threading model and the type of build
89 # \par Configuration Parameters:
90 # <table class="senf">
91 # <tr><td>\c BOOST_INCLUDES</td><td>Include directory.</td></tr>
92 # <tr><td>\c BOOST_LIBDIR</td><td>Library directory</td></tr>
93 # <tr><td>\c BOOST_VARIANT</td><td>Complete variant specification</td></tr>
94 # <tr><td>\c BOOST_TOOLSET</td><td>Toolset to use</td></tr>
95 # <tr><td>\c BOOST_RUNTIME</td><td>Runtime to use</td></tr>
96 # <tr><td>\c BOOST_DEBUG_RUNTIME</td><td>Explicit debug runtime</td></tr>
99 # You can either specify \c BOOST_VARIANT explicitly or specify \c
100 # BOOST_TOOLSET and \c BOOST_RUNTIME. If you give \c BOOST_TOOLSET, \c
101 # BOOST_RUNTIME defaults to empty and \c BOOST_DEBUG_RUNTIME defaults
102 # to \c gd, If \c BOOST_TOOLSET is specified and you have included
103 # STLPort support (UseSTLPort()), then \c p is appended to both
106 # The Boost configuration can get realtively complex. If the boost
107 # libraries are provided by the distribution, you probably don't need
108 # to specify any parameters. If your configuration is more complex,
110 # href="http://www.boost.org/tools/build/v1/build_system.htm">Boost.Build</a>
111 # documentation for a definition of the terms used above (toolset,
112 # variant, runtime ...).
118 opts.Add('BOOST_INCLUDES', 'Boost include directory', '')
119 opts.Add('BOOST_VARIANT', 'The boost variant to use', '')
120 opts.Add('BOOST_TOOLSET', 'The boost toolset to use', '')
121 opts.Add('BOOST_RUNTIME', 'The boost runtime to use', '')
122 opts.Add('BOOST_DEBUG_RUNTIME', 'The boost debug runtime to use', '')
123 opts.Add('BOOST_LIBDIR', 'The directory of the boost libraries', '')
124 Finalizer(FinalizeBoost)
126 ## \brief Finalize Boost environment
128 def FinalizeBoost(env):
129 env.Tool('BoostUnitTests', [basedir])
131 if env['BOOST_TOOLSET']:
133 if env['final'] : runtime += env.get('BOOST_RUNTIME','')
134 else : runtime += env.get('BOOST_DEBUG_RUNTIME','gd')
135 if env['STLPORT_LIB'] : runtime += "p"
136 if runtime: runtime = "-" + runtime
137 env['BOOST_VARIANT'] = "-" + env['BOOST_TOOLSET'] + runtime
139 env['BOOSTTESTLIB'] = 'libboost_unit_test_framework' + env['BOOST_VARIANT']
141 env.Append(LIBPATH = [ '$BOOST_LIBDIR' ],
142 CPPPATH = [ '$BOOST_INCLUDES' ])
144 ## \brief Use STLPort as STL replacement if available
146 # Use <a href="http://www.stlport.org">STLPort</a> as a replacement
147 # for the system STL. STLPort has the added feature of providing fully
148 # checked containers and iterators. This can greatly simplify
149 # debugging. However, STLPort and Boost interact in a non-trivial way
150 # so the configuration is relatively complex. This command does not
151 # enforce the use of STLPort, it is only used if available.
153 # \par Configuration Parameters:
154 # <table class="senf">
155 # <tr><td>\c STLPORT_INCLUDES</td><td>Include directory.</td></tr>
156 # <tr><td>\c STLPORT_LIBDIR</td><td>Library directory</td></tr>
157 # <tr><td>\c STLPORT_LIB</td><td>Name of STLPort library</td></tr>
158 # <tr><td>\c STLPORT_DEBUGLIB</td><td>Name of STLPort debug library</td></tr>
161 # If \c STLPORT_LIB is specified, \c STLPORT_DEBUGLIB defaults to \c
162 # STLPORT_LIB with \c _stldebug appended. The STLPort library will
163 # only be used, if \c STLPORT_LIB is set in \c SConfig.
169 opts.Add('STLPORT_INCLUDES', 'STLport include directory', '')
170 opts.Add('STLPORT_LIB', 'Name of the stlport library or empty to not use stlport', '')
171 opts.Add('STLPORT_DEBUGLIB', 'Name of the stlport debug library','')
172 opts.Add('STLPORT_LIBDIR', 'The directory of the stlport libraries','')
173 Finalizer(FinalizeSTLPort)
177 ## \brief Finalize STLPort environment
179 def FinalizeSTLPort(env):
180 if env['STLPORT_LIB']:
181 if not env['STLPORT_DEBUGLIB']:
182 env['STLPORT_DEBUGLIB'] = env['STLPORT_LIB'] + '_stldebug'
183 env.Append(LIBPATH = [ '$STLPORT_LIBDIR' ],
184 CPPPATH = [ '$STLPORT_INCLUDES' ])
186 env.Append(LIBS = [ '$STLPORT_LIB' ])
188 env.Append(LIBS = [ '$STLPORT_DEBUGLIB' ],
189 CPPDEFINES = [ '_STLP_DEBUG' ])
191 ## \brief Build a configured construction environment
193 # This function is called after all frameworks are specified to build
194 # a tailored construction environment. You can then use this
195 # construction environment just like an ordinary SCons construction
196 # environment (which it is ...)
198 # This call will set some default compilation parameters depending on
199 # the \c final command line option: specifying <tt>final=1</tt> will
200 # built a release version of the code.
201 def MakeEnvironment():
202 global opts, finalizers
204 env = SCons.Environment.Environment(options=opts)
205 if SCons.Script.SConscript.Arguments.get('final'):
207 env.Help(opts.GenerateHelpText(env))
209 # We want to pass the SSH_AUTH_SOCK system env-var so we can ssh
210 # into other hosts from within SCons rules. I have used rules like
211 # this e.g. to automatically install stuff on a remote system ...
212 if os.environ.has_key('SSH_AUTH_SOCK'):
213 env.Append( ENV = { 'SSH_AUTH_SOCK': os.environ['SSH_AUTH_SOCK'] } )
215 for finalizer in finalizers:
218 for tool in SCONS_TOOLS:
219 env.Tool(tool, [basedir])
221 # These are the default compilation parameters. We should probably
222 # make these configurable
223 env.Append(CXXFLAGS = [ '-Wall', '-Woverloaded-virtual', '-Wno-long-long' ],
224 LOCALLIBDIR = [ '#' ],
225 LIBPATH = [ '$LOCALLIBDIR' ])
228 env.Append(CXXFLAGS = [ '-O3' ],
229 CPPDEFINES = [ 'NDEBUG' ])
231 env.Append(CXXFLAGS = [ '-O0', '-g', '-fno-inline' ],
232 LINKFLAGS = [ '-g' ])
234 env.Append(CPPDEFINES = [ '$EXTRA_DEFINES' ],
235 LIBS = [ '$EXTRA_LIBS' ])
239 ## \brief Find normal and test C++ sources
241 # GlobSources() will return a list of all C++ source files (named
242 # "*.cc") as well as a list of all unit-test files (named "*.test.cc")
243 # in the current directory. The sources will be returned as a tuple of
244 # sources, test-sources. The target helpers all accept such a tuple as
245 # their source argument.
246 def GlobSources(exclude=[]):
247 testSources = glob.glob("*.test.cc")
248 sources = [ x for x in glob.glob("*.cc") if x not in testSources and x not in exclude ]
249 return (sources, testSources)
251 ## \brief Add generic standard targets for every module
253 # This target helper should be called in the top-level \c SConstruct file
254 # as well as in every module \c SConscipt file. It adds general
255 # targets. Right now, these are
256 # \li clean up \c .sconsign, \c .sconf_temp and \c config.log on
257 # <tt>scons -c all</tt>
260 def StandardTargets(env):
261 env.Clean(env.Alias('all'), [ '.sconsign', '.sconf_temp', 'config.log' ])
263 ## \brief Add generic global targets
265 # This target helper should be called in the top-level \c SConstruct
266 # file. It adds general global targets. Right now theese are
267 # \li Make <tt>scons all</tt> build all targets.
270 def GlobalTargets(env):
271 env.Depends(env.Alias('all'),'#')
273 ## \brief Return path of a built library within $LOCALLIBDIR
275 def LibPath(lib): return '$LOCALLIBDIR/lib%s.a' % lib
277 ## \brief Build object files
279 # This target helper will build object files from the given
282 # If \a testSources are given, a unit test will be built using the <a
283 # href="http://www.boost.org/libs/test/doc/index.html">Boost.Test</a>
284 # library. \a LIBS may specify any additional library modules <em>from
285 # the same project</em> on which the test depends. Those libraries
286 # will be linked into the final test executable. The test will
287 # automatically be run if the \c test or \c all_tests targets are
290 # If \a sources is a 2-tuple as returned by GlobSources(), it will
291 # provide both \a sources and \a testSources.
294 def Objects(env, sources, testSources = None, LIBS = []):
295 if type(sources) == type(()):
296 testSources = sources[1]
301 objects = env.Object(sources)
304 test = env.BoostUnitTests(
307 test_source = testSources,
309 DEPENDS = [ env.File(LibPath(x)) for x in LIBS ])
310 env.Alias('all_tests', test)
311 # Hmm ... here I'd like to use an Alias instead of a file
312 # however the alias does not seem to live in the subdirectory
313 # which breaks 'scons -u test'
314 env.Alias(env.File('test'), test)
318 ## \brief Build documentation with doxygen
320 # The doxygen target helper will build software documentation using
321 # the given \a doxyfile (which defaults to \c Doxyfile). The Doxygen
322 # builder used supports automatic dependency generation (dependencies
323 # are automatically generated from the parameters specified in the \a
324 # doxyfile), automatic target emitters (the exact targets created are
325 # found parsing the \a doxyfile) and lots of other features. See the
326 # Doxygen builder documentation
328 # If \a extra_sources are given, the generated documentation will
329 # depend on them. This can be used to build images or other
330 # supplementary files.
332 # The doxygen target helper extends the builder with additional
335 # \li Fix tagfiles by removing namespace entries. These entries only
336 # work for namespaces completely defined in a single module. As
337 # soon as another module (which references the tagfile) has it's
338 # own members in that namespace, the crosslinking will break.
339 # \li If \c DOXY_HTML_XSL is defined as a construction environment
340 # variable, preprocess all generated html files (if html files are
341 # generated) by the given XSLT stylesheet. Since the HTML
342 # generated by doxygen is broken, we first filter the code through
343 # HTML-\c tidy and filter out some error messages.
344 # \li If xml output is generatedwe create files \c bug.xmli and \c
345 # todo.xmli which contain all bugs and todo items specified in the
346 # sources. The format of these files is much more suited to
347 # postprocessing and is a more database like format as the doxygen
348 # generated files (which are more presentation oriented). if \c
349 # DOXY_XREF_TYPES is given, it will specify the cross reference
350 # types to support (defaults to \c bug and \c todo). See <a
351 # href="http://www.stack.nl/~dimitri/doxygen/commands.html#cmdxrefitem">\xrefitem</a>
352 # in the doxygen documentation.
355 def Doxygen(env, doxyfile = "Doxyfile", extra_sources = []):
356 # ARGHHH !!! without the [:] we are changing the target list
357 # ||| WITHIN THE DOXYGEN BUILDER
358 docs = env.Doxygen(doxyfile)[:]
363 if isinstance(doc,SCons.Node.FS.Dir): continue
364 if doc.name == 'xml.stamp' : xmlnode = doc
365 if doc.name == 'html.stamp' : htmlnode = doc
366 if os.path.splitext(doc.name)[1] == '.stamp' : continue # ignore other file stamps
367 # otherwise it must be the tag file
371 # Postprocess the tag file to remove the (broken) namespace
375 env.Action("xsltproc --nonet -o %(target)s.temp %(template)s %(target)s && mv %(target)s.temp %(target)s"
376 % { 'target': tagnode.abspath,
377 'template': os.path.join(basedir,"tagmunge.xsl") }))
379 if htmlnode and env.get('DOXY_HTML_XSL'):
380 xslfile = env.File(env['DOXY_HTML_XSL'])
383 env.Action(("for html in %s/*.html; do " +
385 " sed -e 's/id=\"current\"/class=\"current\"/' $${html}" +
386 " | tidy -ascii -q --show-warnings no --fix-uri no" +
387 " | xsltproc --nonet --html -o $${html}.new %s - 2>&1" +
389 " | grep -v 'ID .* already defined';" +
390 " mv $${html}.new $${html}; " +
392 % (htmlnode.dir.abspath, xslfile.abspath)))
394 env.Depends(doc,xslfile)
398 for type in env.get("DOXY_XREF_TYPES",[ "bug", "todo" ]):
399 xref = os.path.join(xmlnode.dir.abspath,type+".xml")
400 xref_pp = env.Command(xref+'i', [ xref, os.path.join(basedir,'xrefxtract.xslt'), xmlnode ],
401 [ "test -s $SOURCE && xsltproc -o $TARGET" +
402 " --stringparam module $MODULE" +
403 " --stringparam type $TYPE" +
404 " ${SOURCES[1]} $SOURCE || touch $TARGET" ],
405 MODULE = xmlnode.dir.dir.dir.name,
407 env.SideEffect(xref, xmlnode)
408 env.AddPreAction(docs, "rm -f %s" % (xref,))
409 env.AddPostAction(docs, "test -r %s || touch %s" % (xref,xref))
410 xrefs.extend(xref_pp)
413 env.Depends(docs,extra_sources)
415 env.Alias('all_docs', doc)
416 env.Clean('all_docs', doc)
417 env.Clean('all', doc)
421 ## \brief Build combined doxygen cross-reference
423 # This command will build a complete cross-reference of \c xrefitems
424 # accross all modules.
426 # Right now, this command is very project specific. It needs to be
430 def DoxyXRef(env, docs=None,
431 HTML_HEADER = None, HTML_FOOTER = None,
432 TITLE = "Cross-reference of action points"):
434 docs = env.Alias('all_docs')[0].sources
435 xrefs = [ doc for doc in docs if os.path.splitext(doc.name)[1] == ".xmli" ]
436 xref = env.Command("doc/html/xref.xml", xrefs,
437 [ "echo -e '<?xml version=\"1.0\"?>\\n<xref>' >$TARGET",
438 "cat $SOURCES >> $TARGET",
439 "echo '</xref>' >>$TARGET" ])
441 # Lastly we create the html file
442 sources = [ xref, "%s/xrefhtml.xslt" % basedir ]
443 if HTML_HEADER : sources.append(HTML_HEADER)
444 if HTML_FOOTER : sources.append(HTML_FOOTER)
449 "sed -e 's/\\$$title/$TITLE/g' -e 's/\\$$projectname/Overview/g' ${SOURCES[2]} > $TARGET")
450 commands.append("xsltproc --stringparam title '$TITLE' ${SOURCES[1]} $SOURCE >> $TARGET")
453 "sed -e 's/\\$$title/$TITLE/g' -e 's/\\$$projectname/Overview/g' ${SOURCES[%d]} >> $TARGET"
454 % (HTML_HEADER and 3 or 2))
456 xref = env.Command("doc/html/xref.html", sources, commands,
459 env.Alias('all_docs',xref)
462 ## \brief Build library
464 # This target helper will build the given library. The library will be
465 # called lib<i>library</i>.a as is customary on UNIX systems. \a
466 # sources, \a testSources and \a LIBS are directly forwarded to the
467 # Objects build helper.
469 # The library is added to the list of default targets.
472 def Lib(env, library, sources, testSources = None, LIBS = []):
473 objects = Objects(env,sources,testSources,LIBS=LIBS)
476 lib = env.Library(env.File(LibPath(library)),objects)
478 env.Append(ALLLIBS = library)
481 ## \brief Build executable
483 # This target helper will build the given binary. The \a sources, \a
484 # testSources and \a LIBS arguments are forwarded to the Objects
485 # builder. The final program will be linked against all the library
486 # modules specified in \a LIBS (those are libraries which are built as
487 # part of the same proejct). To specify non-module libraries, use the
488 # construction environment parameters or the framework helpers.
491 def Binary(env, binary, sources, testSources = None, LIBS = []):
492 objects = Objects(env,sources,testSources,LIBS=LIBS)
496 progEnv.Prepend(LIBS = LIBS)
497 program = progEnv.Program(target=binary,source=objects)
499 env.Depends(program, [ env.File(LibPath(x)) for x in LIBS ])