13f515ea0972d3bbf5029b4444259549699c4c99
[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         denv.update(kw)
51         return { 'DOXYENV'         : denv,
52                  'MODULE'          : module,
53                  'OUTPUT_DIRECTORY': output_directory,
54                  'DOXYGENCOM'      : "site_scons/lib/doxygen.sh $DOXYOPTS $SOURCE",
55                  };
56     opts = [ '--tagfile-name', '"${MODULE}.tag"',
57              '--output-dir', '$OUTPUT_DIRECTORY' ]
58
59     # Rule to generate tagfile
60     # (need to exclude the 'clean' case, otherwise we'll have duplicate nodes)
61     if not env.GetOption('clean'):
62         tagfile = env.Doxygen(doxyfile, DOXYOPTS = opts + [ '--tagfile' ],
63                               **vars(generate_tagfile='${OUTPUT_DIRECTORY}/${MODULE}.tag'))
64         env.Append(ALL_TAGFILES = [ tagfile[0].abspath ])
65         env.Depends(tagfile, [ env.File('#/site_scons/lib/doxygen.sh'), 
66                                env.File('#/site_scons/lib/tag-munge.xsl') ])
67
68         env.Install(env.Dir('$DOCINSTALLDIR').Dir(tagfile[0].dir.get_path(env.Dir('#'))),
69                     tagfile[0])
70
71     # Rule to generate HTML documentation
72     doc = env.Doxygen(doxyfile, DOXYOPTS = opts + [ '--tagfiles', '"$ALL_TAGFILES"', '--html' ],
73                       **vars(html='YES', tagfiles='$ALL_TAGFILES'))
74     env.Depends(doc, [ env.File('#/site_scons/lib/doxygen.sh'),
75                        env.File('#/site_scons/lib/html-munge.xsl') ])
76
77     # Copy the extra_sources (the images) into the documentation directory
78     # (need to exclude the 'clean' case otherwise there are multiple ways to clean the copies)
79     if extra_sources:
80         if env.GetOption('clean'):
81             env.Depends(doc, extra_sources)
82         else:
83             env.Depends(tagfile, env.CopyToDir(doc[0].dir, extra_sources))
84
85     # Install documentation into DOCINSTALLDIR
86     env.InstallDir(env.Dir('$DOCINSTALLDIR').Dir(doc[0].dir.dir.get_path(env.Dir('#'))), doc[0].dir,
87                    FILTER_SUFFIXES=['.html','.css','.png','.php','.idx'])
88
89     # Useful aliases
90     env.Alias('all_docs', doc)
91     env.Clean(env.Alias('all_docs'), doc)
92     env.Clean(env.Alias('all'), doc)
93
94     return doc
95
96 def AllIncludesHH(env, exclude=[]):
97     exclude = exclude + ['all_includes.hh']
98     headers = [ f for f in env.Glob("*.hh", source=True)
99                 if f.name not in exclude and not f.name.endswith('.test.hh') ]
100     headers.sort(key=lambda x:x.name)
101     target = env.File("all_includes.hh")
102     allinch = env.CreateFile(target, 
103                              env.Value("".join([ '#include <%s>\n' % f.srcnode().get_path(env.Dir('#'))
104                                                  for f in headers ])))
105     env.Default(allinch)
106     env.Depends(allinch, headers)
107
108 INDEXPAGE="""
109 /** \mainpage ${TITLE}
110
111     ${TEXT}
112
113     \htmlonly
114     <dl>
115
116 {{  for name, title in SUBPAGES:
117       <dt><a href="../../${name}/doc/html/index.html">${name}</a></dt><dd>${title}</a></dd>
118 }}
119
120     </dl>
121     \endhtmlonly
122  */
123 """
124
125 def IndexPage(env, name, title, text=""):
126     SUBPAGES = []
127     for dox in sorted(env.Glob("*/Mainpage.dox",strings=True)):
128         subtitle = ([None] + [ line.split('\\mainpage',1)[-1].strip() for line in file(dox)
129                                if '\\mainpage' in line ])[-1]
130         if subtitle:
131             SUBPAGES.append( (dox.split('/',1)[0], subtitle) )
132     file(name,"w").write(yaptu.process(
133             INDEXPAGE, globals(), { 'TITLE': title, 'TEXT': text, 'SUBPAGES': SUBPAGES }))
134     env.Clean('all',name)
135     env.Clean('all_docs',name)
136
137 ###########################################################################
138 # The following functions serve as simple macros for most SConscript files
139 #
140 # If you need to customize these rules, copy-and-paste the code into the
141 # SConscript file and adjust at will (don't forget to replace the
142 # parameters with their actual value. Parameters are marked with ((name)) )
143
144 def AutoRules(env, exclude=[], subdirs=[], doc_extra_sources = []):
145     import SENFSCons
146
147     sources, tests, includes = SENFSCons.Glob(env, exclude=((exclude)), subdirs=((subdirs)) )
148     subscripts               = sorted(env.Glob("*/SConscript", strings=True))
149     doxyfile                 = env.Glob("Doxyfile")
150     objects                  = []
151
152     if sources               : env.Append(ALLOBJECTS = env.Object(sources))
153     if tests                 : env.BoostUnitTest('test', tests)
154     if includes              : env.InstallSubdir('$INCLUDEINSTALLDIR', includes)
155     if doxyfile              : SENFSCons.Doxygen(env, extra_sources=((doc_extra_sources)) )
156     if subscripts            : SConscript(subscripts)
157
158
159 def AutoPacketBundle(env, name, exclude=[], subdirs=[], doc_extra_sources=[]):
160     import SENFSCons
161
162     sources, tests, includes = SENFSCons.Glob(env, exclude=((exclude)), subdirs=((subdirs)) )
163     subscripts               = sorted(env.Glob("*/SConscript", strings=True))
164     doxyfile                 = env.Glob("Doxyfile")
165
166     objects = env.Object(sources)
167     cobject = env.CombinedObject('${LOCALLIBDIR}/${NAME}${OBJADDSUFFIX}', objects, NAME=((name)))
168     sobundle = env.SharedLibrary('${LOCALLIBDIR}/${NAME}${OBJADDSUFFIX}', sources, NAME=((name)),
169                                  LIBS=[], SHLIBPREFIX='')
170
171     env.Default(cobject)
172     env.Default(sobundle)
173     env.Append(ALLOBJECTS = objects, PACKET_BUNDLES = cobject)
174     env.Install('$OBJINSTALLDIR', cobject)
175     env.Install('$OBJINSTALLDIR', sobundle)
176
177     if tests                 : env.BoostUnitTest('test', tests + cobject)
178     if includes              : env.InstallSubdir('$INCLUDEINSTALLDIR', includes)
179     if doxyfile              : SENFSCons.Doxygen(env, extra_sources=((doc_extra_sources)) )
180     if subscripts            : SConscript(subscripts)