c2819199483c9e91a9835cdd014be81c047bbe15
[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
27 import SCons.Defaults, SCons.Action
28
29 ## \defgroup use Predefined Framework Configurators
30 #
31 # The following framework configurators are used in the top level \c
32 # SConstruct file to simplify more complex configurations.
33 #
34 # Each of the framework configurators introduces additional
35 # configuration parameters to \ref sconfig
36
37 ## \defgroup target Target Helpers
38 #
39 # To specify standard targets, the following helpers can be used. They
40 # automatically integrate several modules (like documentation,
41 # unit-testing etc).
42
43 ## \defgroup builder Builders
44 #
45 # The SENFSCons framework includes a series of builders. Each builder
46 # is defined in it's own package.
47
48 # Tools to load in MakeEnvironment
49 SCONS_TOOLS = [
50     "Doxygen",
51     "Dia2Png",
52     "CopyToDir",
53 ]
54
55 opts = None
56 finalizers = []
57
58 # This is the directory SENFSCons.py resides
59 basedir = os.path.abspath(os.path.split(__file__)[0])
60
61 ## \brief Initialize configuration options
62 # \internal
63 def InitOpts():
64     global opts
65     if opts is not None: return
66     opts = SCons.Options.Options('SConfig')
67     opts.Add('CXX', 'C++ compiler to use', 'g++')
68     opts.Add('EXTRA_DEFINES', 'Additional preprocessor defines', '')
69     opts.Add('EXTRA_LIBS', 'Additional libraries to link against', '')
70     opts.Add(SCons.Options.BoolOption('final','Enable optimization',0))
71
72 # A finalizer is any callable object. All finalizers will be called
73 # in MakeEnvironment. We use them so every finalizer has knowledge of
74 # all frameworks in use (e.g.: the boost runtime depends on the use of
75 # stlport).
76
77 ## \brief Register finalizer
78 # \internal
79 def Finalizer(f):
80     global finalizers
81     finalizers.append(f)
82
83 ## \brief Initialize the use of the <a href="http://www.boost.org/">Boost</a> library
84 #
85 # Configure the use of the <a href="http://www.boost.org">Boost</a>
86 # libraries. Most of these libraries are header-only, some however
87 # depend on a built library. The library selection is somewhat
88 # involved and depends on the threading model and the type of build
89 # (debug or final).
90 #
91 # \par Configuration Parameters:
92 #     <table class="senf">
93 #     <tr><td>\c BOOST_INCLUDES</td><td>Include directory.</td></tr>
94 #     <tr><td>\c BOOST_LIBDIR</td><td>Library directory</td></tr>
95 #     <tr><td>\c BOOST_VARIANT</td><td>Complete variant specification</td></tr>
96 #     <tr><td>\c BOOST_TOOLSET</td><td>Toolset to use</td></tr>
97 #     <tr><td>\c BOOST_RUNTIME</td><td>Runtime to use</td></tr>
98 #     <tr><td>\c BOOST_DEBUG_RUNTIME</td><td>Explicit debug runtime</td></tr>
99 #     </table>
100 #
101 # You can either specify \c BOOST_VARIANT explicitly or specify \c
102 # BOOST_TOOLSET and \c BOOST_RUNTIME. If you give \c BOOST_TOOLSET, \c
103 # BOOST_RUNTIME defaults to empty and \c BOOST_DEBUG_RUNTIME defaults
104 # to \c gd, If \c BOOST_TOOLSET is specified and you have included
105 # STLPort support (UseSTLPort()), then \c p is appended to both
106 # runtimes.
107 #
108 # The Boost configuration can get realtively complex. If the boost
109 # libraries are provided by the distribution, you probably don't need
110 # to specify any parameters. If your configuration is more complex,
111 # refer to the <a
112 # href="http://www.boost.org/tools/build/v1/build_system.htm">Boost.Build</a>
113 # documentation for a definition of the terms used above (toolset,
114 # variant, runtime ...).
115 #
116 # \ingroup use
117 def UseBoost():
118     global opts
119     InitOpts()
120     opts.Add('BOOST_INCLUDES', 'Boost include directory', '')
121     opts.Add('BOOST_VARIANT', 'The boost variant to use', '')
122     opts.Add('BOOST_TOOLSET', 'The boost toolset to use', '')
123     opts.Add('BOOST_RUNTIME', 'The boost runtime to use', '')
124     opts.Add('BOOST_DEBUG_RUNTIME', 'The boost debug runtime to use', '')
125     opts.Add('BOOST_LIBDIR', 'The directory of the boost libraries', '')
126     Finalizer(FinalizeBoost)
127
128 ## \brief Finalize Boost environment
129 # \internal
130 def FinalizeBoost(env):
131     env.Tool('BoostUnitTests', [basedir])
132
133     if env['BOOST_TOOLSET']:
134         runtime = ""
135         if env['final'] : runtime += env.get('BOOST_RUNTIME','')
136         else            : runtime += env.get('BOOST_DEBUG_RUNTIME','gd')
137         if env['STLPORT_LIB'] : runtime += "p"
138         if runtime: runtime = "-" + runtime
139         env['BOOST_VARIANT'] = "-" + env['BOOST_TOOLSET'] + runtime
140
141     env['BOOSTTESTLIB'] = 'libboost_unit_test_framework' + env['BOOST_VARIANT']
142     env['BOOSTREGEXLIB'] = 'libboost_regex' + env['BOOST_VARIANT']
143
144     env.Append(LIBPATH = [ '$BOOST_LIBDIR' ],
145                CPPPATH = [ '$BOOST_INCLUDES' ])
146
147 ## \brief Use STLPort as STL replacement if available
148 #
149 # Use <a href="http://www.stlport.org">STLPort</a> as a replacement
150 # for the system STL. STLPort has the added feature of providing fully
151 # checked containers and iterators. This can greatly simplify
152 # debugging. However, STLPort and Boost interact in a non-trivial way
153 # so the configuration is relatively complex. This command does not
154 # enforce the use of STLPort, it is only used if available.
155 #
156 # \par Configuration Parameters:
157 #     <table class="senf">
158 #     <tr><td>\c STLPORT_INCLUDES</td><td>Include directory.</td></tr>
159 #     <tr><td>\c STLPORT_LIBDIR</td><td>Library directory</td></tr>
160 #     <tr><td>\c STLPORT_LIB</td><td>Name of STLPort library</td></tr>
161 #     <tr><td>\c STLPORT_DEBUGLIB</td><td>Name of STLPort debug library</td></tr>
162 #     </table>
163 #
164 # If \c STLPORT_LIB is specified, \c STLPORT_DEBUGLIB defaults to \c
165 # STLPORT_LIB with \c _stldebug appended. The STLPort library will
166 # only be used, if \c STLPORT_LIB is set in \c SConfig.
167 #
168 # \ingroup use
169 def UseSTLPort():
170     global opts
171     InitOpts()
172     opts.Add('STLPORT_INCLUDES', 'STLport include directory', '')
173     opts.Add('STLPORT_LIB', 'Name of the stlport library or empty to not use stlport', '')
174     opts.Add('STLPORT_DEBUGLIB', 'Name of the stlport debug library','')
175     opts.Add('STLPORT_LIBDIR', 'The directory of the stlport libraries','')
176     Finalizer(FinalizeSTLPort)
177
178 # \}
179
180 ## \brief Finalize STLPort environment
181 # \internal
182 def FinalizeSTLPort(env):
183     if env['STLPORT_LIB']:
184         if not env['STLPORT_DEBUGLIB']:
185             env['STLPORT_DEBUGLIB'] = env['STLPORT_LIB'] + '_stldebug'
186         env.Append(LIBPATH = [ '$STLPORT_LIBDIR' ],
187                    CPPPATH = [ '$STLPORT_INCLUDES' ])
188         if env['final']:
189             env.Append(LIBS = [ '$STLPORT_LIB' ])
190         else:
191             env.Append(LIBS = [ '$STLPORT_DEBUGLIB' ],
192                        CPPDEFINES = [ '_STLP_DEBUG' ])
193
194 ## \brief Build a configured construction environment
195 #
196 # This function is called after all frameworks are specified to build
197 # a tailored construction environment. You can then use this
198 # construction environment just like an ordinary SCons construction
199 # environment (which it is ...)
200 #
201 # This call will set some default compilation parameters depending on
202 # the \c final command line option: specifying <tt>final=1</tt> will
203 # built a release version of the code.
204 def MakeEnvironment():
205     global opts, finalizers
206     InitOpts()
207     env = SCons.Environment.Environment(options=opts)
208     if SCons.Script.SConscript.Arguments.get('final'):
209         env['final'] = 1
210     env.Help(opts.GenerateHelpText(env))
211
212     # We want to pass the SSH_AUTH_SOCK system env-var so we can ssh
213     # into other hosts from within SCons rules. I have used rules like
214     # this e.g. to automatically install stuff on a remote system ...
215     if os.environ.has_key('SSH_AUTH_SOCK'):
216         env.Append( ENV = { 'SSH_AUTH_SOCK': os.environ['SSH_AUTH_SOCK'] } )
217
218     for finalizer in finalizers:
219         finalizer(env)
220
221     for tool in SCONS_TOOLS:
222         env.Tool(tool, [basedir])
223
224     # These are the default compilation parameters. We should probably
225     # make these configurable
226     env.Append(CXXFLAGS = [ '-Wall', '-Woverloaded-virtual', '-Wno-long-long' ],
227                LOCALLIBDIR = [ '#' ],
228                LIBPATH = [ '$LOCALLIBDIR' ])
229
230     if env['final']:
231         env.Append(CXXFLAGS = [ '-O3' ],
232                    CPPDEFINES = [ 'NDEBUG' ])
233     else:
234         env.Append(CXXFLAGS = [ '-O0', '-g', '-fno-inline' ],
235                    LINKFLAGS = [ '-g' ])
236
237     env.Append(CPPDEFINES = [ '$EXTRA_DEFINES' ],
238                LIBS = [ '$EXTRA_LIBS' ])
239
240     return env
241
242 ## \brief Find normal and test C++ sources
243 #
244 # GlobSources() will return a list of all C++ source files (named
245 # "*.cc") as well as a list of all unit-test files (named "*.test.cc")
246 # in the current directory. The sources will be returned as a tuple of
247 # sources, test-sources. The target helpers all accept such a tuple as
248 # their source argument.
249 def GlobSources(exclude=[], subdirs=[]):
250     testSources = glob.glob("*.test.cc")
251     sources = [ x for x in glob.glob("*.cc") if x not in testSources and x not in exclude ]
252     for subdir in subdirs:
253         testSources += glob.glob(os.path.join(subdir,"*.test.cc"))
254         sources += [ x for x in glob.glob(os.path.join(subdir,"*.cc"))
255                      if x not in testSources and x not in exclude ]
256     return (sources, testSources)
257
258 ## \brief Add generic standard targets for every module
259 #
260 # This target helper should be called in the top-level \c SConstruct file
261 # as well as in every module \c SConscipt file. It adds general
262 # targets. Right now, these are
263 # \li clean up \c .sconsign, \c .sconf_temp and \c config.log on
264 #   <tt>scons -c all</tt>
265 #
266 # \ingroup target
267 def StandardTargets(env):
268     env.Clean(env.Alias('all'), [ '.sconsign', '.sconf_temp', 'config.log' ])
269
270 ## \brief Add generic global targets
271 #
272 # This target helper should be called in the top-level \c SConstruct
273 # file. It adds general global targets. Right now theese are
274 # \li Make <tt>scons all</tt> build all targets.
275 #
276 # \ingroup target
277 def GlobalTargets(env):
278     env.Depends(env.Alias('all'),'#')
279
280 ## \brief Return path of a built library within $LOCALLIBDIR
281 # \internal
282 def LibPath(lib): return '$LOCALLIBDIR/lib%s.a' % lib
283
284 ## \brief Build object files
285 #
286 # This target helper will build object files from the given
287 # sources.
288 #
289 # If \a testSources are given, a unit test will be built using the <a
290 # href="http://www.boost.org/libs/test/doc/index.html">Boost.Test</a>
291 # library. \a LIBS may specify any additional library modules <em>from
292 # the same project</em> on which the test depends. Those libraries
293 # will be linked into the final test executable. The test will
294 # automatically be run if the \c test or \c all_tests targets are
295 # given.
296 #
297 # If \a sources is a 2-tuple as returned by GlobSources(), it will
298 # provide both \a sources and \a testSources.
299 #
300 # \ingroup target
301 def Objects(env, sources, testSources = None, LIBS = [], OBJECTS = []):
302     if type(sources) == type(()):
303         testSources = sources[1]
304         sources = sources[0]
305     if type(sources) is not type([]):
306         sources = [ sources ]
307
308     objects = None
309     if sources:
310         objects = env.Object([
311             source
312             for source in sources
313             if not str(source).endswith('.o') ]) + [
314             source
315             for source in sources
316             if str(source).endswith('.o') ]
317         
318
319     if testSources:
320         test = env.BoostUnitTests(
321             target = 'test',
322             objects = objects,
323             test_sources = testSources,
324             LIBS = LIBS,
325             OBJECTS = OBJECTS,
326             DEPENDS = [ env.File(LibPath(x)) for x in LIBS ])
327         env.Alias('all_tests', test)
328         # Hmm ... here I'd like to use an Alias instead of a file
329         # however the alias does not seem to live in the subdirectory
330         # which breaks 'scons -u test'
331         env.Alias(env.File('test'), test)
332
333     return objects
334
335 ## \brief Build documentation with doxygen
336 #
337 # The doxygen target helper will build software documentation using
338 # the given \a doxyfile (which defaults to \c Doxyfile). The Doxygen
339 # builder used supports automatic dependency generation (dependencies
340 # are automatically generated from the parameters specified in the \a
341 # doxyfile), automatic target emitters (the exact targets created are
342 # found parsing the \a doxyfile) and lots of other features. See the
343 # Doxygen builder documentation
344 #
345 # If \a extra_sources are given, the generated documentation will
346 # depend on them. This can be used to build images or other
347 # supplementary files.
348 #
349 # The doxygen target helper extends the builder with additional
350 # functionality:
351 #
352 # \li Fix tagfiles by removing namespace entries. These entries only
353 #     work for namespaces completely defined in a single module. As
354 #     soon as another module (which references the tagfile) has it's
355 #     own members in that namespace, the crosslinking will break.
356 # \li If \c DOXY_HTML_XSL is defined as a construction environment
357 #     variable, preprocess all generated html files (if html files are
358 #     generated) by the given XSLT stylesheet. Since the HTML
359 #     generated by doxygen is broken, we first filter the code through
360 #     HTML-\c tidy and filter out some error messages.
361 # \li If xml output is generated we create files \c bug.xmli and \c
362 #     todo.xmli which contain all bugs and todo items specified in the
363 #     sources. The format of these files is much more suited to
364 #     postprocessing and is a more database like format as the doxygen
365 #     generated files (which are more presentation oriented). if \c
366 #     DOXY_XREF_TYPES is given, it will specify the cross reference
367 #     types to support (defaults to \c bug and \c todo). See <a
368 #     href="http://www.stack.nl/~dimitri/doxygen/commands.html#cmdxrefitem">\xrefitem</a>
369 #     in the doxygen documentation.
370 #
371 # \ingroup target
372 def Doxygen(env, doxyfile = "Doxyfile", extra_sources = []):
373     # ARGHHH !!! without the [:] we are changing the target list
374     #        ||| WITHIN THE DOXYGEN BUILDER
375     docs = env.Doxygen(doxyfile)[:]
376     xmlnode = None
377     htmlnode = None
378     tagnode = None
379     for doc in docs:
380         if isinstance(doc,SCons.Node.FS.Dir): continue
381         if doc.name == 'xml.stamp' : xmlnode = doc
382         if doc.name == 'html.stamp' : htmlnode = doc
383         if doc.name == 'search.idx' : continue
384         if os.path.splitext(doc.name)[1] == '.stamp' : continue # ignore other file stamps
385         # otherwise it must be the tag file
386         tagnode = doc
387
388     if tagnode:
389         # Postprocess the tag file to remove the (broken) namespace
390         # references
391         env.AddPostAction(
392             docs,
393             SCons.Action.Action("xsltproc --nonet -o %(target)s.temp %(template)s %(target)s && mv %(target)s.temp %(target)s"
394                        % { 'target': tagnode.abspath,
395                            'template': os.path.join(basedir,"tagmunge.xsl") }))
396
397     if htmlnode and env.get('DOXY_HTML_XSL'):
398         xslfile = env.File(env['DOXY_HTML_XSL'])
399         reltopdir = '../' * len(htmlnode.dir.abspath[len(env.Dir('#').abspath)+1:].split('/'))
400         if reltopdir : reltopdir = reltopdir[:-1]
401         else         : reltopdir = '.'
402         env.AddPostAction(
403             docs,
404             SCons.Action.Action(("for html in %s/*.html; do " +
405                         "    echo $$html;" +
406                         "    sed -e 's/id=\"current\"/class=\"current\"/' $${html}" +
407                         "        | tidy -ascii -q --show-warnings no --fix-uri no " +
408                         "        | xsltproc --nonet --html --stringparam topdir %s -o $${html}.new %s - 2>&1" +
409                         "        | grep '^-'" +
410                         "        | grep -v 'ID .* already defined';" +
411                         "    mv $${html}.new $${html}; " +
412                         "done")
413                        % (htmlnode.dir.abspath, reltopdir, xslfile.abspath)))
414         for doc in docs:
415             env.Depends(doc, xslfile)
416
417     if xmlnode:
418         xrefs = []
419         for type in env.get("DOXY_XREF_TYPES",[ "bug", "todo" ]):
420             xref = os.path.join(xmlnode.dir.abspath,type+".xml")
421             xref_pp = env.Command(xref+'i', [ xref, os.path.join(basedir,'xrefxtract.xslt'), xmlnode ],
422                                   [ "test -s $SOURCE && xsltproc -o $TARGET" +
423                                     " --stringparam module $MODULE" +
424                                     " --stringparam type $TYPE" +
425                                     " ${SOURCES[1]} $SOURCE || touch $TARGET" ],
426                                   MODULE = xmlnode.dir.dir.dir.abspath[
427                                                len(env.Dir('#').abspath)+1:],
428                                   TYPE = type)
429             env.SideEffect(xref, xmlnode)
430             env.AddPreAction(docs, "rm -f %s" % (xref,))
431             env.AddPostAction(docs, "test -r %s || touch %s" % (xref,xref))
432             xrefs.extend(xref_pp)
433         docs.extend(xrefs)
434
435     if extra_sources and htmlnode:
436         env.Depends(docs,
437                     [ env.CopyToDir( source=source, target=htmlnode.dir )
438                       for source in extra_sources ])
439
440     if extra_sources and xmlnode:
441         env.Depends(docs,
442                     [ env.CopyToDir( source=source, target=xmlnode.dir )
443                       for source in extra_sources ])
444
445     if not htmlnode and not xmlnode:
446         env.Depends(docs, extra_sources)
447         
448     for doc in docs :
449         env.Alias('all_docs', doc)
450         env.Clean('all_docs', doc)
451         env.Clean('all', doc)
452
453     return docs
454
455 ## \brief Build combined doxygen cross-reference
456 #
457 # This command will build a complete cross-reference of \c xrefitems
458 # accross all modules.
459 #
460 # Right now, this command is very project specific. It needs to be
461 # generalized.
462 #
463 # \ingroup target
464 def DoxyXRef(env, docs=None,
465              HTML_HEADER = None, HTML_FOOTER = None,
466              TITLE = "Cross-reference of action points"):
467     if docs is None:
468         docs = env.Alias('all_docs')[0].sources
469     xrefs = [ doc for doc in docs if os.path.splitext(doc.name)[1] == ".xmli" ]
470     xref = env.Command("doc/html/xref.xml", xrefs,
471                        [ "echo '<?xml version=\"1.0\"?>' > $TARGET",
472                          "echo '<xref>' >> $TARGET",
473                          "cat $SOURCES >> $TARGET",
474                          "echo '</xref>' >>$TARGET" ])
475
476     # Lastly we create the html file
477     sources = [ xref, "%s/xrefhtml.xslt" % basedir ]
478     if HTML_HEADER : sources.append(HTML_HEADER)
479     if HTML_FOOTER : sources.append(HTML_FOOTER)
480
481     commands = []
482     if HTML_HEADER:
483         commands.append("sed" +
484                         " -e 's/\\$$title/$TITLE/g'" +
485                         " -e 's/\\$$projectname/Overview/g'" +
486                         " ${SOURCES[2]} > $TARGET")
487     commands.append("xsltproc" +
488                     " --stringparam title '$TITLE'" +
489                     " --stringparam types '$DOXY_XREF_TYPES'" +
490                     " ${SOURCES[1]} $SOURCE >> $TARGET")
491     if HTML_FOOTER:
492         commands.append(
493             "sed -e 's/\\$$title/$TITLE/g' -e 's/\\$$projectname/Overview/g' ${SOURCES[%d]} >> $TARGET"
494             % (HTML_HEADER and 3 or 2))
495
496     if env.get('DOXY_HTML_XSL'):
497         xslfile = env.File(env['DOXY_HTML_XSL'])
498         reltopdir = '../' * len(xref[0].dir.abspath[len(env.Dir('#').abspath)+1:].split('/'))
499         if reltopdir : reltopdir = reltopdir[:-1]
500         else         : reltopdir = '.'
501         commands.append(("xsltproc -o ${TARGET}.tmp" +
502                          " --nonet --html" +
503                          " --stringparam topdir %s" +
504                          " ${SOURCES[-1]} $TARGET 2>/dev/null")
505                         % reltopdir)
506         commands.append("mv ${TARGET}.tmp ${TARGET}")
507         sources.append(xslfile)
508         
509     xref = env.Command("doc/html/xref.html", sources, commands,
510                        TITLE = TITLE)
511
512     env.Alias('all_docs',xref)
513     return xref
514
515
516 ## \brief Build library
517 #
518 # This target helper will build the given library. The library will be
519 # called lib<i>library</i>.a as is customary on UNIX systems. \a
520 # sources, \a testSources and \a LIBS are directly forwarded to the
521 # Objects build helper.
522 #
523 # The library is added to the list of default targets.
524 #
525 #\ingroup target
526 def Lib(env, library, sources, testSources = None, LIBS = [], OBJECTS = []):
527     objects = Objects(env,sources,testSources,LIBS=LIBS,OBJECTS=OBJECTS)
528     lib = None
529     if objects:
530         lib = env.Library(env.File(LibPath(library)),objects)
531         env.Default(lib)
532         env.Append(ALLLIBS = library)
533     return lib
534
535 ## \brief Build Object from multiple sources
536 def Object(env, target, sources, testSources = None, LIBS = [], OBJECTS = []):
537     objects = Objects(env,sources,testSources,LIBS=LIBS,OBJECTS=OBJECTS)
538     ob = None
539     if objects:
540         ob = env.Command(target+".o", objects, "ld -r -o $TARGET $SOURCES")
541         env.Default(ob)
542     return ob
543
544 ## \brief Build executable
545 #
546 # This target helper will build the given binary.  The \a sources, \a
547 # testSources and \a LIBS arguments are forwarded to the Objects
548 # builder. The final program will be linked against all the library
549 # modules specified in \a LIBS (those are libraries which are built as
550 # part of the same proejct). To specify non-module libraries, use the
551 # construction environment parameters or the framework helpers.
552 #
553 # \ingroup target
554 def Binary(env, binary, sources, testSources = None, LIBS = [], OBJECTS = []):
555     objects = Objects(env,sources,testSources,LIBS=LIBS,OBJECTS=OBJECTS)
556     program = None
557     if objects:
558         progEnv = env.Copy()
559         progEnv.Prepend(LIBS = LIBS)
560         program = progEnv.Program(target=binary,source=objects+OBJECTS)
561         env.Default(program)
562         env.Depends(program, [ env.File(LibPath(x)) for x in LIBS ])
563     return program