Better doxygen env-var handling (e.g. REVISION)
[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_path = []):
65     global senfutildir
66     senf_path.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     env.SetDefault( 
99         CXXFLAGS_final    = [],
100         CXXFLAGS_normal   = [],
101         CXXFLAGS_debug    = [],
102
103         CPPDEFINES_final  = [],
104         CPPDEFINES_normal = [],
105         CPPDEFINES_debug  = [],
106
107         LINKFLAGS_final   = [],
108         LINKFLAGS_normal  = [],
109         LINKFLAGS_debug   = [],
110
111         LOGLEVELS_final   = [],
112         LOGLEVELS_normal  = [],
113         LOGLEVELS_debug   = [],
114
115         PROJECTNAME       = "Unnamed project",
116         DOCLINKS          = [],
117         PROJECTEMAIL      = "nobody@nowhere.org",
118         COPYRIGHT         = "nobody",
119         REVISION          = "unknown",
120         )
121
122     # Interpret command line options
123     parseArguments(
124         env, 
125         BoolVariable('final', 'Build final (optimized) build', False),
126         BoolVariable('debug', 'Link in debug symbols', False),
127     )
128
129     # If we have a symbolic link (or directory) 'senf', we use it as our
130     # senf repository
131     for path in senf_path:
132         if not path.startswith('/') : sconspath = '#/%s' % path
133         else                        : sconspath = path
134         if os.path.exists(os.path.join(path,"senf/config.hh")):
135             print "\nUsing SENF in '%s'\n" \
136                 % ('/..' in sconspath and os.path.abspath(path) or sconspath)
137             env.Append( LIBPATH = [ sconspath ],
138                         CPPPATH = [ sconspath ],
139                         BUNDLEDIR = sconspath )
140             try:
141                 env.MergeFlags(file(os.path.join(path,"senf.conf")).read())
142             except IOError:
143                 print "(SENF configuration file 'senf.conf' not found, assuming non-final SENF)"
144                 env.Append(CPPDEFINES = [ 'SENF_DEBUG' ])
145             break
146         elif os.path.exists(os.path.join(path,"include/senf/config.hh")):
147             print "\nUsing system SENF in '%s/'\n" % sconspath
148             env.Append(BUNDLEDIR = os.path.join(sconspath,"lib/senf"))
149             break
150     else:
151         print "\nSENF library not found .. trying build anyway !!\n"
152
153     env.Alias('all', '#')
154
155
156 def DefaultOptions(env):
157     env.Append(
158         CXXFLAGS         = [ '-Wall', '-Woverloaded-virtual' ],
159         CXXFLAGS_final   = [ '-O2' ],
160         CXXFLAGS_normal  = [ '-O0', '-g' ],
161         CXXFLAGS_debug   = [ '$CXXFLAGS_normal' ],
162
163         LINKFLAGS_normal = [ '-Wl,-S' ],
164         LINKFLAGS_debug  = [ '-g' ],
165     )
166
167 def Glob(env, exclude=[], subdirs=[]):
168     testSources = glob.glob("*.test.cc")
169     sources = [ x for x in glob.glob("*.cc") if x not in testSources and x not in exclude ]
170     for subdir in subdirs:
171         testSources += glob.glob(os.path.join(subdir,"*.test.cc"))
172         sources += [ x for x in glob.glob(os.path.join(subdir,"*.cc"))
173                      if x not in testSources and x not in exclude ]
174     return (sources, testSources)
175
176 tagfiles = None
177
178 def Doxygen(env, doxyheader=None, doxyfooter=None, doxycss=None, mydoxyfile=False, senfdoc_path=[],
179             **kw):
180     # Additional interesting keyword arguments or environment variables:
181     #    PROJECTNAME, DOCLINKS, PROJECTEMAIL, COPYRIGHT, REVISION
182
183     global senfutildir
184     global tagfiles
185     libdir=os.path.join(senfutildir, 'lib')
186     
187     if tagfiles is None:
188         senfdocdir = None
189         senfdoc_path.extend(('senfdoc', 'senf/manual', 'senf', '../senf/manual', '../senf', 
190                              os.path.join(os.path.dirname(senfutildir), 'manual'),
191                              os.path.dirname(senfutildir), 
192                              '/usr/share/doc/senf', '/usr/local/share/doc/senf',
193                              '/usr/share/doc/libsenf-doc/html'))
194         for path in senfdoc_path:
195             if os.path.exists(os.path.join(path, "doc/Main.tag")):
196                 senfdocdir = path
197                 break
198         tagfiles = []
199         if senfdocdir is None:
200             print "(SENF documentation not found)"
201         else:
202             for dir, dirs, files in os.walk(senfdocdir):
203                 tagfiles.extend([ os.path.join(dir,f) for f in files if f.endswith('.tag') ])
204                 if dir.endswith('/doc') : dirs.remove('html')
205                 for d in dirs: 
206                     if d.startswith('.') : dirs.remove(d)
207     
208     if env.GetOption('clean'):
209         env.Clean('doc', env.Dir('doc'))
210         if not mydoxyfile:
211             env.Clean('doc', "Doxyfile")
212
213     if not mydoxyfile:
214         # Create Doxyfile NOW
215         site_tools.Yaptu.yaptuAction("Doxyfile", 
216                                      os.path.join(libdir, "Doxyfile.yap"),
217                                      env)
218
219     envvalues = [ env.Value('$PROJECTNAME'),
220                   env.Value('$DOCLINKS'),
221                   env.Value('$PROJECTEMAIL'),
222                   env.Value('$COPYRIGHT'),
223                   env.Value('$REVISION') ]
224
225     # The other files are created using dependencies
226     if doxyheader: 
227         doxyheader = env.CopyToDir(env.Dir("doc"), doxyheader)
228     else:
229         doxyheader = env.Yaptu("doc/doxyheader.html", os.path.join(libdir, "doxyheader.yap"), **kw)
230         env.Depends(doxyheader, envvalues)
231     if doxyfooter:
232         doxyfooter = env.CopyToDir(env.Dir("doc"), doxyfooter)
233     else:
234         doxyfooter = env.Yaptu("doc/doxyfooter.html", os.path.join(libdir, "doxyfooter.yap"), **kw)
235         env.Depends(doxyfooter, envvalues)
236     if doxycss:
237         doxycss = env.CopyToDir(env.Dir("doc"), doxycss)
238     else:
239         doxycss    = env.CopyToDir(env.Dir("doc"), os.path.join(libdir, "doxy.css"))
240
241     doc = env.Doxygen("Doxyfile",
242                       DOXYOPTS   = [ '--html', '--tagfiles', '"$TAGFILES"' ],
243                       DOXYENV    = { 'TOPDIR'     : env.Dir('#').abspath,
244                                      'LIBDIR'     : libdir,
245                                      'REVISION'   : '$REVISION',
246                                      'tagfiles'   : '$TAGFILES',
247                                      'output_dir' : 'doc',
248                                      'html_dir'   : 'html',
249                                      'html'       : 'YES' },
250                       TAGFILES   = tagfiles, 
251                       DOCLIBDIR  = libdir,
252                       DOXYGENCOM = "$DOCLIBDIR/doxygen.sh $DOXYOPTS $SOURCE")
253
254     env.Depends(doc, [ doxyheader, doxyfooter, doxycss ])
255
256     return doc