384349c84e4ac32615f0430f931b441fda47ee6f
[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     env.Default(env.CreateFile(target, 
103                                env.Value("".join([ '#include <%s>\n' % f.srcnode().get_path(env.Dir('#'))
104                                                    for f in headers ]))))
105
106 INDEXPAGE="""
107 /** \mainpage ${TITLE}
108
109     ${TEXT}
110
111     \htmlonly
112     <dl>
113
114 {{  for name, title in SUBPAGES:
115       <dt><a href="../../${name}/doc/html/index.html">${name}</a></dt><dd>${title}</a></dd>
116 }}
117
118     </dl>
119     \endhtmlonly
120  */
121 """
122
123 def IndexPage(env, name, title, text=""):
124     SUBPAGES = []
125     for dox in sorted(env.Glob("*/Mainpage.dox",strings=True)):
126         subtitle = ([None] + [ line.split('\\mainpage',1)[-1].strip() for line in file(dox)
127                                if '\\mainpage' in line ])[-1]
128         if subtitle:
129             SUBPAGES.append( (dox.split('/',1)[0], subtitle) )
130     file(name,"w").write(yaptu.process(
131             INDEXPAGE, globals(), { 'TITLE': title, 'TEXT': text, 'SUBPAGES': SUBPAGES }))
132     env.Clean('all',name)
133     env.Clean('all_docs',name)
134
135
136 ###########################################################################
137 # The following functions serve as simple macros for most SConscript files
138 #
139 # If you need to customize these rules, copy-and-paste the code into the
140 # SConscript file and adjust at will (don't forget to replace the
141 # parameters with their actual value. Parameters are marked with ((name)) )
142
143 def AutoRules(env, exclude=[], subdirs=[], doc_extra_sources = []):
144     import SENFSCons
145
146     sources, tests, includes = SENFSCons.Glob(env, exclude=((exclude)), subdirs=((subdirs)) )
147     subscripts               = sorted(env.Glob("*/SConscript", strings=True))
148     doxyfile                 = env.Glob("Doxyfile")
149     objects                  = []
150
151     if sources               : env.Append(ALLOBJECTS = env.Object(sources))
152     if tests                 : env.BoostUnitTest('test', tests)
153     if includes              : env.InstallSubdir('$INCLUDEINSTALLDIR', includes)
154     if doxyfile              : SENFSCons.Doxygen(env, extra_sources=((doc_extra_sources)) )
155     if subscripts            : SConscript(subscripts)
156
157
158 def AutoPacketBundle(env, name, exclude=[], subdirs=[], doc_extra_sources=[]):
159     import SENFSCons
160
161     sources, tests, includes = SENFSCons.Glob(env, exclude=((exclude)), subdirs=((subdirs)) )
162     subscripts               = sorted(env.Glob("*/SConscript", strings=True))
163     doxyfile                 = env.Glob("Doxyfile")
164
165     objects = env.Object(sources)
166     cobject = env.CombinedObject('${LOCALLIBDIR}/${NAME}${OBJADDSUFFIX}', objects, NAME=((name)))
167
168     env.Default(cobject)
169     env.Append(ALLOBJECTS = objects, PACKET_BUNDLES = cobject)
170     env.Install('$OBJINSTALLDIR', cobject)
171
172     if tests                 : env.BoostUnitTest('test', tests + cobject)
173     if includes              : env.InstallSubdir('$INCLUDEINSTALLDIR', includes)
174     if doxyfile              : SENFSCons.Doxygen(env, extra_sources=((doc_extra_sources)) )
175     if subscripts            : SConscript(subscripts)