9d243ce7803bc3e22cd3b08f8494fd4744b2c302
[senf.git] / senfscons / SENFSCons.py
1 ## \file
2 # \brief SENFSCons package
3
4 ## \package senfscons.SENFSCons
5 # \brief Build helpers and utilities
6 #
7 # The SENFSCons package contains a number of build helpers and
8 # utilities which are used to simplify commmon tasks. 
9 #
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>
13 #
14 # <dt>\ref target</dt><dd>simplify building common targest and include
15 # enhanced functionality like unit-testing.</dd></dl>
16 #
17 # Additionally for external use are
18 # <dl><dt>MakeEnvironment()</dt><dd>Build construction
19 # environment</dd>
20 #
21 # <dt>GlobSources()</dt><dd>Utility to find source files</dd></dl>
22 #
23 # All other functions are for internal use only.
24
25 import os.path, glob
26 import  SCons.Options, SCons.Environment, SCons.Script.SConscript, SCons.Node.FS, SCons.Defaults
27
28 ## \defgroup use Predefined Framework Configurators
29 #
30 # The following framework configurators are used in the top level \c
31 # SConstruct file to simplify more complex configurations. 
32 #
33 # Each of the framework configurators introduces additional
34 # configuration parameters to \ref sconfig
35
36 ## \defgroup target Target Helpers
37 #
38 # To specify standard targets, the following helpers can be used. They
39 # automatically integrate several modules (like documentation,
40 # unit-testing etc).
41
42 ## \defgroup builder Builders
43 #
44 # The SENFSCons framework includes a series of builders. Each builder
45 # is defined in it's own package.
46
47 # Tools to load in MakeEnvironment
48 SCONS_TOOLS = [
49     "Doxygen",
50     "Dia2Png",
51 ]
52
53 opts = None
54 finalizers = []
55
56 # This is the directory SENFSCons.py resides
57 basedir = os.path.abspath(os.path.split(__file__)[0])
58
59 ## \brief Initialize configuration options
60 # \internal
61 def InitOpts():
62     global opts
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))
69
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
73 # stlport).
74
75 ## \brief Register finalizer
76 # \internal
77 def Finalizer(f):
78     global finalizers
79     finalizers.append(f)
80
81 ## \brief Initialize the use of the <a href="http://www.boost.org/">Boost</a> library
82 #
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
87 # (debug or final).
88 #
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>
97 #     </table>
98 #
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
104 # runtimes.
105 #
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,
109 # refer to the <a
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 ...).
113 #
114 # \ingroup use
115 def UseBoost():
116     global opts
117     InitOpts()
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)
125
126 ## \brief Finalize Boost environment
127 # \internal
128 def FinalizeBoost(env):
129     env.Tool('BoostUnitTests', [basedir])
130
131     if env['BOOST_TOOLSET']:
132         runtime = ""
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
138
139     env['BOOSTTESTLIB'] = 'libboost_unit_test_framework' + env['BOOST_VARIANT']
140
141     env.Append(LIBPATH = [ '$BOOST_LIBDIR' ],
142                CPPPATH = [ '$BOOST_INCLUDES' ])
143
144 ## \brief Use STLPort as STL replacement if available
145 #
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.
152 #
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>
159 #     </table>
160 #
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.
164 #
165 # \ingroup use
166 def UseSTLPort():
167     global opts
168     InitOpts()
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)
174
175 # \}
176
177 ## \brief Finalize STLPort environment
178 # \internal
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' ])
185         if env['final']:
186             env.Append(LIBS = [ '$STLPORT_LIB' ])
187         else:
188             env.Append(LIBS = [ '$STLPORT_DEBUGLIB' ],
189                        CPPDEFINES = [ '_STLP_DEBUG' ])
190
191 ## \brief Build a configured construction environment
192 #
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 ...)
197 #
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
203     InitOpts()
204     env = SCons.Environment.Environment(options=opts)
205     if SCons.Script.SConscript.Arguments.get('final'):
206         env['final'] = 1
207     env.Help(opts.GenerateHelpText(env))
208
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'] } )
214
215     for finalizer in finalizers:
216         finalizer(env)
217
218     for tool in SCONS_TOOLS:
219         env.Tool(tool, [basedir])
220
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' ])
226
227     if env['final']:
228         env.Append(CXXFLAGS = [ '-O3' ],
229                    CPPDEFINES = [ 'NDEBUG' ])
230     else:
231         env.Append(CXXFLAGS = [ '-O0', '-g', '-fno-inline' ],
232                    LINKFLAGS = [ '-g' ])
233
234     env.Append(CPPDEFINES = [ '$EXTRA_DEFINES' ],
235                LIBS = [ '$EXTRA_LIBS' ])
236
237     return env
238
239 ## \brief Find normal and test C++ sources
240 #
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)
250     
251 ## \brief Add generic standard targets for every module
252 #
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>
258
259 # \ingroup target
260 def StandardTargets(env):
261     env.Clean(env.Alias('all'), [ '.sconsign', '.sconf_temp', 'config.log' ])
262
263 ## \brief Add generic global targets
264 #
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.
268 #
269 # \ingroup target
270 def GlobalTargets(env):
271     env.Depends(env.Alias('all'),'#')
272
273 ## \brief Return path of a built library within $LOCALLIBDIR
274 # \internal
275 def LibPath(lib): return '$LOCALLIBDIR/lib%s.a' % lib
276
277 ## \brief Build object files
278 #
279 # This target helper will build object files from the given
280 # sources.
281 #
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
288 # given.
289 #
290 # If \a sources is a 2-tuple as returned by GlobSources(), it will
291 # provide both \a sources and \a testSources.
292 #
293 # \ingroup target
294 def Objects(env, sources, testSources = None, LIBS = []):
295     if type(sources) == type(()):
296         testSources = sources[1]
297         sources = sources[0]
298
299     objects = None
300     if sources:
301         objects = env.Object(sources)
302
303     if testSources:
304         test = env.BoostUnitTests(
305             target = 'test',
306             source = sources,
307             test_source = testSources,
308             LIBS = LIBS,
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)
315
316     return objects
317
318 ## \brief Build documentation with doxygen
319 #
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
327 #
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.
331 #
332 # The doxygen target helper extends the builder with additional
333 # functionality:
334 #
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.
353 #
354 # \ingroup target
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)[:]
359     xmlnode = None
360     htmlnode = None
361     tagnode = None
362     for doc in docs:
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
368         tagnode = doc
369
370     if tagnode:
371         # Postprocess the tag file to remove the (broken) namespace
372         # references
373         env.AddPostAction(
374             docs,
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") }))
378
379     if htmlnode and env.get('DOXY_HTML_XSL'):
380         xslfile = env.File(env['DOXY_HTML_XSL'])
381         env.AddPostAction(
382             docs,
383             env.Action(("for html in %s/*.html; do " +
384                         "    echo $$html;" +
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" +
388                         "        | grep '^-'" +
389                         "        | grep -v 'ID .* already defined';" +
390                         "    mv $${html}.new $${html}; " +
391                         "done")
392                        % (htmlnode.dir.abspath, xslfile.abspath)))
393         for doc in docs:
394             env.Depends(doc,xslfile)
395
396     if xmlnode:
397         xrefs = []
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,
406                                   TYPE = type)
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)
411         docs.extend(xrefs)
412
413     env.Depends(docs,extra_sources)
414     for doc in docs :
415         env.Alias('all_docs', doc)
416         env.Clean('all_docs', doc)
417         env.Clean('all', doc)
418
419     return docs
420
421 ## \brief Build combined doxygen cross-reference
422 #
423 # This command will build a complete cross-reference of \c xrefitems
424 # accross all modules.
425 #
426 # Right now, this command is very project specific. It needs to be
427 # generalized.
428 #
429 # \ingroup target
430 def DoxyXRef(env, docs=None,
431              HTML_HEADER = None, HTML_FOOTER = None,
432              TITLE = "Cross-reference of action points"):
433     if docs is None:
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" ])
440
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)
445
446     commands = []
447     if HTML_HEADER:
448         commands.append(
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")
451     if HTML_FOOTER:
452         commands.append(
453             "sed -e 's/\\$$title/$TITLE/g' -e 's/\\$$projectname/Overview/g' ${SOURCES[%d]} >> $TARGET"
454             % (HTML_HEADER and 3 or 2))
455     
456     xref = env.Command("doc/html/xref.html", sources, commands,
457                        TITLE = TITLE)
458
459     env.Alias('all_docs',xref)
460     return xref
461
462 ## \brief Build library
463 #
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.
468 #
469 # The library is added to the list of default targets.
470 #
471 #\ingroup target
472 def Lib(env, library, sources, testSources = None, LIBS = []):
473     objects = Objects(env,sources,testSources,LIBS=LIBS)
474     lib = None
475     if objects:
476         lib = env.Library(env.File(LibPath(library)),objects)
477         env.Default(lib)
478         env.Append(ALLLIBS = library)
479     return lib
480
481 ## \brief Build executable
482 #
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.
489 #
490 # \ingroup target
491 def Binary(env, binary, sources, testSources = None, LIBS = []):
492     objects = Objects(env,sources,testSources,LIBS=LIBS)
493     program = None
494     if objects:
495         progEnv = env.Copy()
496         progEnv.Prepend(LIBS = LIBS)
497         program = progEnv.Program(target=binary,source=objects)
498         env.Default(program)
499         env.Depends(program, [ env.File(LibPath(x)) for x in LIBS ])
500     return program