1 # vi:filetype=python:expandtab:tabstop=2:shiftwidth=2
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
9 # Full author contact details are available in file CREDITS.
11 # This file defines all the utility functions for the
12 # scons-based build system of lyx
15 import os, sys, re, shutil, glob
16 from SCons.Util import WhereIs
18 config_h = os.path.join('src', 'config.h')
21 def writeToFile(filename, lines, append = False):
22 " utility function: write or append lines to filename "
24 file = open(filename, 'a')
26 file = open(filename, 'w')
31 def printEnvironment(env, keys=[]):
32 ''' used to check profile settings '''
33 dict = env.Dictionary()
39 # try to expand, but this is not always possible
40 print key, '=', env.subst('$'+key)
42 print '<<UNEXPANDED>>:', key, '=', dict[key]
45 def env_subst(target, source, env):
46 ''' subst variables in source by those in env, and output to target
47 source and target are scons File() objects
49 %key% (not key itself) is an indication of substitution
51 assert len(target) == 1
52 assert len(source) == 1
53 target_file = file(str(target[0]), "w")
54 source_file = file(str(source[0]), "r")
56 contents = source_file.read()
57 for k, v in env.items():
59 val = env.subst('$'+k)
60 # temporary fix for the \Resource backslash problem
61 val = val.replace('\\', '/')
62 # multi-line replacement
63 val = val.replace('\n',r'\\n\\\n')
64 contents = re.sub('@'+k+'@', val, contents)
65 contents = re.sub('%'+k+'%', val, contents)
68 target_file.write(contents + "\n")
70 #st = os.stat(str(source[0]))
71 #os.chmod(str(target[0]), stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
76 def globSource(dir, pattern, build_dir=None, exclude=[], include=[]):
77 ''' glob files, in dir and use build_dir as returned path name '''
78 files = filter(lambda x: x not in exclude, glob.glob1(dir, pattern)) + include
82 return ['%s/%s' % (build_dir, x) for x in files]
88 def checkPkgConfig(conf, version):
89 ''' Return false if pkg_config does not exist, or is too old '''
90 conf.Message('Checking for pkg-config...')
91 ret = conf.TryAction('pkg-config --atleast-pkgconfig-version=%s' % version)[0]
96 def checkPackage(conf, pkg):
97 ''' check if pkg is under the control of conf '''
98 conf.Message('Checking for package %s...' % pkg)
99 ret = conf.TryAction("pkg-config --print-errors --exists %s" % pkg)[0]
105 ''' Write the first part of config.h '''
106 global config_content
107 config_content = '''/* src/config.h. Generated by scon. */
112 * This file is part of LyX, the document processor.
113 * Licence details can be found in the file COPYING.
115 * This is the compilation configuration file for LyX.
116 * It was generated by scon.
117 * You might want to change some of the defaults if something goes wrong
118 * during the compilation.
126 def addToConfig(lines, newline=2):
127 ''' utility function: shortcut for appending lines to outfile
128 add newline at the end of lines.
130 global config_content
131 if lines.strip() != '':
132 config_content += lines + '\n'*newline
135 def endConfigH(top_src_dir):
136 ''' Write the last part of config.h '''
137 global config_content
138 writeToFile(os.path.join(top_src_dir, config_h), config_content +
139 '''/************************************************************
140 ** You should not need to change anything beyond this point */
142 #ifndef HAVE_STRERROR
143 #if defined(__cplusplus)
146 char * strerror(int n);
150 #ifndef HAVE_DECL_MKSTEMP
151 #if defined(__cplusplus)
158 #if defined(HAVE_OSTREAM) && defined(HAVE_LOCALE) && defined(HAVE_SSTREAM)
159 # define USE_BOOST_FORMAT 1
161 # define USE_BOOST_FORMAT 0
164 #define BOOST_USER_CONFIG <config.h>
166 #if !defined(ENABLE_ASSERTIONS)
167 # define BOOST_DISABLE_ASSERTS 1
169 #define BOOST_ENABLE_ASSERT_HANDLER 1
171 #define BOOST_DISABLE_THREADS 1
172 #define BOOST_NO_WREGEX 1
173 #define BOOST_NO_WSTRING 1
176 # define BOOST_POSIX 1
179 #if defined(HAVE_NEWAPIS_H)
180 # define WANT_GETFILEATTRIBUTESEX_WRAPPER 1
188 def checkMkdirOneArg(conf):
189 check_mkdir_one_arg_source = """
190 #include <sys/stat.h>
196 conf.Message('Checking for the number of args for mkdir... ')
197 ret = conf.TryLink(check_mkdir_one_arg_source, '.c') or \
198 conf.TryLink('#include <unistd.h>' + check_mkdir_one_arg_source, '.c') or \
199 conf.TryLink('#include <direct.h>' + check_mkdir_one_arg_source, '.c')
208 def checkCXXGlobalCstd(conf):
209 ''' Check the use of std::tolower or tolower '''
210 check_global_cstd_source = '''
218 conf.Message('Check for the use of global cstd... ')
219 ret = conf.TryLink(check_global_cstd_source, '.c')
227 def checkSelectArgType(conf):
228 ''' Adapted from autoconf '''
229 conf.Message('Checking for arg types for select... ')
230 for arg234 in ['fd_set *', 'int *', 'void *']:
231 for arg1 in ['int', 'size_t', 'unsigned long', 'unsigned']:
232 for arg5 in ['struct timeval *', 'const struct timeval *']:
233 check_select_source = '''
234 #if HAVE_SYS_SELECT_H
235 # include <sys/select.h>
237 #if HAVE_SYS_SOCKET_H
238 # include <sys/socket.h>
240 extern int select (%s, %s, %s, %s, %s);
245 ''' % (arg1, arg234, arg234, arg234, arg5)
246 ret = conf.TryLink(check_select_source, '.c')
249 return (arg1, arg234, arg5)
250 conf.Result('no (use default)')
251 return ('int', 'int *', 'struct timeval *')
254 def checkBoostLibraries(conf, lib, pathes):
255 ''' look for boost libraries '''
256 conf.Message('Checking for boost library %s... ' % lib)
258 # direct form: e.g. libboost_iostreams.a
259 if os.path.isfile(os.path.join(path, 'lib%s.a' % lib)):
262 # check things like libboost_iostreams-gcc.a
263 files = glob.glob(os.path.join(path, 'lib%s-*.a' % lib))
264 # if there are more than one, choose the first one
265 # FIXME: choose the best one.
267 # get xxx-gcc from /usr/local/lib/libboost_xxx-gcc.a
269 return (path, files[0].split(os.sep)[-1][3:-2])
274 def checkCommand(conf, cmd):
275 ''' check the existence of a command
276 return full path to the command, or none
278 conf.Message('Checking for command %s...' % cmd)
280 conf.Result(res is not None)
284 def installCygwinLDScript(path):
285 ''' Install i386pe.x-no-rdata '''
286 ld_script = os.path.join(path, 'i386pe.x-no-rdata')
287 script = open(ld_script, 'w')
288 script.write('''/* specific linker script avoiding .rdata sections, for normal executables
290 http://www.cygwin.com/ml/cygwin/2004-09/msg01101.html
291 http://www.cygwin.com/ml/cygwin-apps/2004-09/msg00309.html
293 OUTPUT_FORMAT(pei-i386)
294 SEARCH_DIR("/usr/i686-pc-cygwin/lib"); SEARCH_DIR("/usr/lib"); SEARCH_DIR("/usr/lib/w32api");
295 ENTRY(_mainCRTStartup)
298 .text __image_base__ + __section_alignment__ :
305 ___CTOR_LIST__ = .; __CTOR_LIST__ = . ;
306 LONG (-1);*(.ctors); *(.ctor); *(SORT(.ctors.*)); LONG (0);
307 ___DTOR_LIST__ = .; __DTOR_LIST__ = . ;
308 LONG (-1); *(.dtors); *(.dtor); *(SORT(.dtors.*)); LONG (0);
310 /* ??? Why is .gcc_exc here? */
315 /* The Cygwin32 library uses a section to avoid copying certain data
316 on fork. This used to be named ".data". The linker used
317 to include this between __data_start__ and __data_end__, but that
318 breaks building the cygwin32 dll. Instead, we name the section
319 ".data_cygwin_nocopy" and explictly include it after __data_end__. */
320 .data BLOCK(__section_alignment__) :
329 ___RUNTIME_PSEUDO_RELOC_LIST__ = .;
330 __RUNTIME_PSEUDO_RELOC_LIST__ = .;
331 *(.rdata_runtime_pseudo_reloc)
332 ___RUNTIME_PSEUDO_RELOC_LIST_END__ = .;
333 __RUNTIME_PSEUDO_RELOC_LIST_END__ = .;
335 *(.data_cygwin_nocopy)
337 .rdata BLOCK(__section_alignment__) :
340 .pdata BLOCK(__section_alignment__) :
344 .bss BLOCK(__section_alignment__) :
351 .edata BLOCK(__section_alignment__) :
362 .idata BLOCK(__section_alignment__) :
364 /* This cannot currently be handled with grouped sections.
365 See pe.em:sort_sections. */
368 /* These zeroes mark the end of the import list. */
369 LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);
375 .CRT BLOCK(__section_alignment__) :
377 ___crt_xc_start__ = . ;
378 *(SORT(.CRT$XC*)) /* C initialization */
379 ___crt_xc_end__ = . ;
380 ___crt_xi_start__ = . ;
381 *(SORT(.CRT$XI*)) /* C++ initialization */
382 ___crt_xi_end__ = . ;
383 ___crt_xl_start__ = . ;
384 *(SORT(.CRT$XL*)) /* TLS callbacks */
385 /* ___crt_xl_end__ is defined in the TLS Directory support code */
386 ___crt_xp_start__ = . ;
387 *(SORT(.CRT$XP*)) /* Pre-termination */
388 ___crt_xp_end__ = . ;
389 ___crt_xt_start__ = . ;
390 *(SORT(.CRT$XT*)) /* Termination */
391 ___crt_xt_end__ = . ;
393 .tls BLOCK(__section_alignment__) :
401 .endjunk BLOCK(__section_alignment__) :
403 /* end is deprecated, don't use it */
408 .rsrc BLOCK(__section_alignment__) :
413 .reloc BLOCK(__section_alignment__) :
417 .stab BLOCK(__section_alignment__) (NOLOAD) :
421 .stabstr BLOCK(__section_alignment__) (NOLOAD) :
425 /* DWARF debug sections.
426 Symbols in the DWARF debugging sections are relative to the beginning
427 of the section. Unlike other targets that fake this by putting the
428 section VMA at 0, the PE format will not allow it. */
429 /* DWARF 1.1 and DWARF 2. */
430 .debug_aranges BLOCK(__section_alignment__) (NOLOAD) :
434 .debug_pubnames BLOCK(__section_alignment__) (NOLOAD) :
439 .debug_info BLOCK(__section_alignment__) (NOLOAD) :
441 *(.debug_info) *(.gnu.linkonce.wi.*)
443 .debug_abbrev BLOCK(__section_alignment__) (NOLOAD) :
447 .debug_line BLOCK(__section_alignment__) (NOLOAD) :
451 .debug_frame BLOCK(__section_alignment__) (NOLOAD) :
455 .debug_str BLOCK(__section_alignment__) (NOLOAD) :
459 .debug_loc BLOCK(__section_alignment__) (NOLOAD) :
463 .debug_macinfo BLOCK(__section_alignment__) (NOLOAD) :
467 /* SGI/MIPS DWARF 2 extensions. */
468 .debug_weaknames BLOCK(__section_alignment__) (NOLOAD) :
472 .debug_funcnames BLOCK(__section_alignment__) (NOLOAD) :
476 .debug_typenames BLOCK(__section_alignment__) (NOLOAD) :
480 .debug_varnames BLOCK(__section_alignment__) (NOLOAD) :
485 .debug_ranges BLOCK(__section_alignment__) (NOLOAD) :
496 # these will be used under win32
502 # does not matter if it fails on other systems
507 def __init__(self, env, logfile, longarg, info):
508 # save the spawn system
510 self.logfile = logfile
511 # clear the logfile (it may not exist)
513 # this will overwrite existing content.
514 writeToFile(logfile, info, append=False)
516 self.longarg = longarg
517 # get hold of the old spawn? (necessary?)
518 self._spawn = env['SPAWN']
521 def spawn(self, sh, escape, cmd, args, spawnenv):
523 newargs = ' '.join(map(escape, args[1:]))
524 cmdline = cmd + " " + newargs
526 # if log is not empty, write to it
527 if self.logfile != '':
528 # this tend to be slow (?) but ensure correct output
529 # Note that cmdline may be long so I do not escape it
531 # since this is not an essential operation, proceed if things go wrong here.
532 writeToFile(self.logfile, cmd + " " + ' '.join(args[1:]) + '\n', append=True)
534 print "Warning: can not write to log file ", self.logfile
536 # if the command is not too long, use the old
537 if not self.longarg or len(cmdline) < 8000:
538 exit_code = self._spawn(sh, escape, cmd, args, spawnenv)
540 sAttrs = win32security.SECURITY_ATTRIBUTES()
541 StartupInfo = win32process.STARTUPINFO()
543 spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
544 # check for any special operating system commands
547 win32file.DeleteFile(arg)
550 # otherwise execute the command.
551 hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
552 win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
553 exit_code = win32process.GetExitCodeProcess(hProcess)
554 win32file.CloseHandle(hProcess);
555 win32file.CloseHandle(hThread);
559 def setLoggedSpawn(env, logfile = '', longarg=False, info=''):
560 ''' This function modify env and allow logging of
561 commands to a logfile. If the argument is too long
562 a win32 spawn will be used instead of the system one
565 # create a new spwn object
566 ls = loggedSpawn(env, logfile, longarg, info)
567 # replace the old SPAWN by the new function
568 env['SPAWN'] = ls.spawn
571 ## def DistSources(env, node):
572 ## env.DistFiles(_get_sources(env, node))
574 ## def DistFiles(env, files):
575 ## assert isinstance(files, (list, tuple))
576 ## DISTFILES = [env.File(fname) for fname in files]
577 ## env.AppendUnique(DISTFILES=DISTFILES)
580 ## def make_distdir(target=None, source=None, env=None):
581 ## distdir = env.subst('$DISTDIR')
582 ## Execute(Delete(distdir))
583 ## Execute(Mkdir(distdir))
584 ## for fnode in env["DISTFILES"]:
585 ## dirname, fname = os.path.split(str(fnode))
587 ## distdirname = os.path.join(distdir, dirname)
588 ## if not os.path.exists(distdirname):
589 ## Execute(Mkdir(distdirname))
590 ## Execute(Copy(os.path.join(distdir, dirname, fname), str(fnode)))
592 ## def make_dist(target=None, source=None, env=None):
593 ## return Popen([env['TAR'], "-zcf",
594 ## env.subst("${PACKAGE}-${VERSION}.tar.gz"),
595 ## env.subst('$DISTDIR')]).wait()
597 ## def make_distcheck(target=None, source=None, env=None):
598 ## distdir = env.subst('$DISTDIR')
599 ## distcheckinstdir = tempfile.mkdtemp('', env.subst('${PACKAGE}-${VERSION}-instdir-'))
600 ## distcheckdestdir = tempfile.mkdtemp('', env.subst('${PACKAGE}-${VERSION}-destdir-'))
601 ## instdirs = [os.path.join(distcheckinstdir, d) for d in
602 ## 'lib', 'share', 'bin', 'include']
603 ## for dir_ in instdirs:
604 ## Execute(Mkdir(dir_))
606 ## cmd = env.subst("cd $DISTDIR && scons DESTDIR=%s prefix=%s"
607 ## " && scons check && scons install") %\
608 ## (os.path.join(distcheckdestdir, ''), distcheckinstdir)
609 ## status = Popen(cmd, shell=True).wait()
612 ## ## Check that inst dirs are empty (to catch cases of $DESTDIR not being honored
613 ## for dir_ in instdirs:
614 ## if os.listdir(dir_):
615 ## raise SCons.Errors.BuildError(target, "%s not empy" % dir_)
616 ## ## Check that something inside $DESTDIR was installed
617 ## dir_ = os.path.join(distcheckdestdir, distcheckinstdir)
618 ## if not os.path.exists(dir_):
619 ## raise SCons.Errors.BuildError(target, "%s does not exist" % dir_)
620 ## Execute(Delete(distcheckinstdir))
621 ## Execute(Delete(distcheckdestdir))
622 ## Execute(Delete(distdir))
624 ## def InstallWithDestDir(self, dir_, source):
625 ## dir_ = '${DESTDIR}' + str(dir_)
626 ## return SConsEnvironment.Install(self, dir_, source)
629 ## def InstallAsWithDestDir(self, target, source):
630 ## target = '${DESTDIR}' + str(target)
631 ## return SConsEnvironment.InstallAs(self, target, source)
633 ## def generate(env):
634 ## env.EnsureSConsVersion(0, 96, 91)
636 ## opts = Options(['options.cache'], ARGUMENTS)
637 ## opts.Add(PathOption('prefix', 'Installation prefix', '/usr/local'))
638 ## opts.Add(PathOption('exec_prefix', 'Installation prefix blah blah',
640 ## opts.Add(PathOption('libdir',
641 ## 'Installation prefix for architecture dependent files', '$prefix/lib'))
642 ## opts.Add(PathOption('includedir',
643 ## 'Installation prefix for C header files', '$prefix/include'))
644 ## opts.Add(PathOption('datadir',
645 ## 'Installation prefix for architecture independent files', '$prefix/share'))
646 ## opts.Add(PathOption('bindir', 'Installation prefix for programs', '$prefix/bin'))
647 ## opts.Add(PathOption('DESTDIR', 'blah blah', None))
649 ## opts.Save('options.cache', env)
650 ## SConsEnvironment.Help(env, opts.GenerateHelpText(env))
652 ## env.Append(CPPFLAGS=r' -DVERSION=\"$VERSION\"')
653 ## env.Append(CCFLAGS=ARGUMENTS.get('CCFLAGS', '-g -O2'))
655 ## env['GNOME_TESTS'] = dict(CheckPython=CheckPython,
656 ## CheckPythonHeaders=CheckPythonHeaders,
657 ## PkgCheckModules=PkgCheckModules)
659 ## SConsEnvironment.DistSources = DistSources
660 ## SConsEnvironment.DistFiles = DistFiles
661 ## env['DISTDIR'] = "${PACKAGE}-${VERSION}"
663 ## #env.Command(env.Dir("$DISTDIR"), None, make_distdir)
665 ## distdir_alias = env.Alias("distdir", None, make_distdir)
666 ## dist_alias = env.Alias("dist", None, make_dist)
667 ## env.Depends(dist_alias, distdir_alias)
668 ## distcheck_alias = env.Alias("distcheck", None, make_distcheck)
669 ## env.Depends(distcheck_alias, distdir_alias)
670 ## env.AlwaysBuild(env.Alias('check'))
672 ## #env['TARFLAGS'] ='-c -z'
673 ## #env['TARSUFFIX'] = '.tar.gz'
674 ## #tar = env.Tar('${PACKAGE}-${VERSION}.tar.gz', "${DISTDIR}")
675 ## #env.Depends(tar, distdir_alias)
676 ## #print env['DEFAULT_TARGETS']
678 ## #env.Depends(distdir_alias, "${DISTFILES}")
679 ## #env.Alias('dist', tar)
680 ## env.AlwaysBuild('dist')
681 ## env.AlwaysBuild('distdir')
682 ## env.AlwaysBuild('distcheck')
683 ## env.DistFiles(['SConstruct', 'scons/gnome.py'])
685 ## env['BUILDERS']['EnvSubstFile'] = SCons.Builder.Builder(action=env_subst)
687 ## SConsEnvironment.PythonByteCompile = env.Action(byte_compile_python)
689 ## env.Install = new.instancemethod(InstallWithDestDir, env, env.__class__)
690 ## env.InstallAs = new.instancemethod(InstallAsWithDestDir, env, env.__class__)