8beeabfa53fcaab0579e1e8c71d205c856a9d99b
[senf.git] / site_scons / SENFSCons.py
1 import os.path, glob, yaptu
2 import SCons.Options, SCons.Environment, SCons.Script.SConscript, SCons.Node.FS
3 import SCons.Defaults, SCons.Action
4 from SCons.Script import *
5
6 def Glob(env, exclude=[], subdirs=[]):
7     testSources = env.Glob("*.test.cc",strings=True)
8     sources = [ x 
9                 for x in env.Glob("*.cc",strings=True) 
10                 if x not in testSources and x not in exclude ]
11     for subdir in subdirs:
12         testSources += env.Glob(os.path.join(subdir,"*.test.cc"),strings=True)
13         sources += [ x 
14                      for x in env.Glob(os.path.join(subdir,"*.cc"),strings=True)
15                      if x not in testSources and x not in exclude ]
16     includes = []
17     for d in [ '' ] + [ x+'/' for x in subdirs ]:
18         for p in env.Glob("%s*" % d, strings=True) + env.Glob("%s*" % d, strings=True, ondisk=False):
19             ext = '.' + p.split('.',1)[-1]
20             if ext in env['CPP_INCLUDE_EXTENSIONS'] \
21                and ext not in env['CPP_EXCLUDE_EXTENSIONS'] \
22                and p not in exclude:
23                 includes.append(p)
24     includes = list(set(includes))
25     sources.sort()
26     testSources.sort()
27     includes.sort()
28     return ( sources, testSources, includes )
29
30 def Doxygen(env, doxyfile = "Doxyfile", extra_sources = [], output_directory = "doc"):
31     # There is one small problem we need to solve with this builder: The Doxygen builder reads
32     # the Doxyfile and thus depends on the environment variables set by site_scons/lib/doxygen.sh.
33     # We thus have to provide all necessary definitions here manually via DOXYENV !
34
35     if type(doxyfile) is type(""):
36         doxyfile = env.File(doxyfile)
37
38     # Module name is derived from the doxyfile path
39     # Utils/Console/Doxyfile -> Utils_Console
40     module = doxyfile.dir.get_path(env.Dir('#')).replace('/','_')
41     if module == '.' : module = "Main"
42
43     # Standard doc build vars and opts
44     def vars(env=env, **kw):
45         denv = { 'TOPDIR'          : env.Dir('#').abspath,
46                  'LIBDIR'          : env.Dir('#/site_scons/lib').abspath,
47                  'output_dir'      : '$OUTPUT_DIRECTORY',
48                  'html_dir'        : 'html',
49                  'html'            : 'NO',
50                  'DOXYGEN'         : '$DOXYGEN' }
51         denv.update(kw)
52         return { 'DOXYENV'         : denv,
53                  'MODULE'          : module,
54                  'OUTPUT_DIRECTORY': output_directory,
55                  'DOXYGENCOM'      : "site_scons/lib/doxygen.sh $DOXYOPTS $SOURCE",
56                  };
57     opts = [ '--tagfile-name', '"${MODULE}.tag"',
58              '--output-dir', '$OUTPUT_DIRECTORY' ]
59
60     # Rule to generate tagfile
61     # (need to exclude the 'clean' case, otherwise we'll have duplicate nodes)
62     if not env.GetOption('clean'):
63         tagfile = env.Doxygen(doxyfile, DOXYOPTS = opts + [ '--tagfile' ],
64                               **vars(generate_tagfile='${OUTPUT_DIRECTORY}/${MODULE}.tag'))
65         env.Append(ALL_TAGFILES = [ tagfile[0].abspath ])
66         env.Depends(tagfile, [ env.File('#/site_scons/lib/doxygen.sh'), 
67                                env.File('#/site_scons/lib/tag-munge.xsl') ])
68
69         env.Install(env.Dir('$DOCINSTALLDIR').Dir(tagfile[0].dir.get_path(env.Dir('#'))),
70                     tagfile[0])
71
72     # Rule to generate HTML documentation
73     doc = env.Doxygen(doxyfile, DOXYOPTS = opts + [ '--tagfiles', '"$ALL_TAGFILES"', '--html' ],
74                       **vars(html='YES', tagfiles='$ALL_TAGFILES'))
75     env.Depends(doc, [ env.File('#/site_scons/lib/doxygen.sh'),
76                        env.File('#/site_scons/lib/html-munge.xsl') ])
77
78     # Copy the extra_sources (the images) into the documentation directory
79     # (need to exclude the 'clean' case otherwise there are multiple ways to clean the copies)
80     if extra_sources:
81         if env.GetOption('clean'):
82             env.Depends(doc, extra_sources)
83         else:
84             env.Depends(tagfile, env.CopyToDir(doc[0].dir, extra_sources))
85
86     # Install documentation into DOCINSTALLDIR
87     env.InstallDir(env.Dir('$DOCINSTALLDIR').Dir(doc[0].dir.dir.get_path(env.Dir('#'))), doc[0].dir,
88                    FILTER_SUFFIXES=['.html','.css','.png','.php','.idx'])
89
90     # Useful aliases
91     env.Alias('all_docs', doc)
92     env.Clean(env.Alias('all_docs'), doc)
93     env.Clean(env.Alias('all'), doc)
94
95     return doc
96
97 def AllIncludesHH(env, exclude=[]):
98     exclude = exclude + ['all_includes.hh']
99     headers = [ f for f in env.Glob("*.hh", source=True)
100                 if f.name not in exclude and not f.name.endswith('.test.hh') ]
101     headers.sort(key=lambda x:x.name)
102     target = env.File("all_includes.hh")
103     allinch = env.CreateFile(target, 
104                              env.Value("".join([ '#include <%s>\n' % f.srcnode().get_path(env.Dir('#'))
105                                                  for f in headers ])))
106     env.Default(allinch)
107     env.Depends(allinch, headers)
108
109 INDEXPAGE="""
110 /** \mainpage ${TITLE}
111
112     ${TEXT}
113
114     \htmlonly
115     <dl>
116
117 {{  for name, title in SUBPAGES:
118       <dt><a href="../../${name}/doc/html/index.html">${name}</a></dt><dd>${title}</a></dd>
119 }}
120
121     </dl>
122     \endhtmlonly
123  */
124 """
125
126 def IndexPage(env, name, title, text=""):
127     SUBPAGES = []
128     for dox in sorted(env.Glob("*/Mainpage.dox",strings=True)):
129         subtitle = ([None] + [ line.split('\\mainpage',1)[-1].strip() for line in file(dox)
130                                if '\\mainpage' in line ])[-1]
131         if subtitle:
132             SUBPAGES.append( (dox.split('/',1)[0], subtitle) )
133     file(name,"w").write(yaptu.process(
134             INDEXPAGE, globals(), { 'TITLE': title, 'TEXT': text, 'SUBPAGES': SUBPAGES }))
135     env.Clean('all',name)
136     env.Clean('all_docs',name)
137
138 ###########################################################################
139 # The following functions serve as simple macros for most SConscript files
140 #
141 # If you need to customize these rules, copy-and-paste the code into the
142 # SConscript file and adjust at will (don't forget to replace the
143 # parameters with their actual value. Parameters are marked with ((name)) )
144
145 def AutoRules(env, exclude=[], subdirs=[], doc_extra_sources = []):
146     import SENFSCons
147
148     sources, tests, includes = SENFSCons.Glob(env, exclude=((exclude)), subdirs=((subdirs)) )
149     subscripts               = sorted(env.Glob("*/SConscript", strings=True))
150     doxyfile                 = env.Glob("Doxyfile")
151     objects                  = []
152
153     if sources               : env.Append(ALLOBJECTS = env.Object(sources))
154     if tests                 : env.BoostUnitTest('test', tests)
155     if includes              : env.InstallSubdir('$INCLUDEINSTALLDIR', includes)
156     if doxyfile              : SENFSCons.Doxygen(env, extra_sources=((doc_extra_sources)) )
157     if subscripts            : SConscript(subscripts)
158
159
160 def AutoPacketBundle(env, name, exclude=[], subdirs=[], doc_extra_sources=[]):
161     import SENFSCons
162
163     sources, tests, includes = SENFSCons.Glob(env, exclude=((exclude)), subdirs=((subdirs)) )
164     subscripts               = sorted(env.Glob("*/SConscript", strings=True))
165     doxyfile                 = env.Glob("Doxyfile")
166
167     objects = env.Object(sources)
168     cobject = env.CombinedObject('${LOCALLIBDIR}/${NAME}${OBJADDSUFFIX}', objects, NAME=((name)))
169     sobundle = env.SharedLibrary('${LOCALLIBDIR}/${NAME}${OBJADDSUFFIX}', sources, NAME=((name)),
170                                  LIBS=[], SHLIBPREFIX='')
171
172     env.Default(cobject)
173     env.Default(sobundle)
174     env.Append(ALLOBJECTS = objects, PACKET_BUNDLES = cobject)
175     env.Install('$OBJINSTALLDIR', cobject)
176     env.Install('$OBJINSTALLDIR', sobundle)
177
178     if tests                 : env.BoostUnitTest('test', tests + cobject)
179     if includes              : env.InstallSubdir('$INCLUDEINSTALLDIR', includes)
180     if doxyfile              : SENFSCons.Doxygen(env, extra_sources=((doc_extra_sources)) )
181     if subscripts            : SConscript(subscripts)