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, desc=''):
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() != '':
133 config_content += '/* ' + desc + ' */\n'
134 config_content += lines + '\n\n'
137 def endConfigH(top_src_dir):
138 ''' Write the last part of config.h '''
139 global config_content
140 writeToFile(os.path.join(top_src_dir, config_h), config_content +
141 '''/************************************************************
142 ** You should not need to change anything beyond this point */
144 #ifndef HAVE_STRERROR
145 #if defined(__cplusplus)
148 char * strerror(int n);
152 #ifndef HAVE_DECL_MKSTEMP
153 #if defined(__cplusplus)
160 #if defined(HAVE_OSTREAM) && defined(HAVE_LOCALE) && defined(HAVE_SSTREAM)
161 # define USE_BOOST_FORMAT 1
163 # define USE_BOOST_FORMAT 0
166 #define BOOST_USER_CONFIG <config.h>
168 #if !defined(ENABLE_ASSERTIONS)
169 # define BOOST_DISABLE_ASSERTS 1
171 #define BOOST_ENABLE_ASSERT_HANDLER 1
173 #define BOOST_DISABLE_THREADS 1
174 #define BOOST_NO_WREGEX 1
175 #define BOOST_NO_WSTRING 1
178 # define BOOST_POSIX 1
181 #if defined(HAVE_NEWAPIS_H)
182 # define WANT_GETFILEATTRIBUTESEX_WRAPPER 1
190 def checkMkdirOneArg(conf):
191 check_mkdir_one_arg_source = """
192 #include <sys/stat.h>
198 conf.Message('Checking for the number of args for mkdir... ')
199 ret = conf.TryLink(check_mkdir_one_arg_source, '.c') or \
200 conf.TryLink('#include <unistd.h>' + check_mkdir_one_arg_source, '.c') or \
201 conf.TryLink('#include <direct.h>' + check_mkdir_one_arg_source, '.c')
210 def checkCXXGlobalCstd(conf):
211 ''' Check the use of std::tolower or tolower '''
212 check_global_cstd_source = '''
220 conf.Message('Check for the use of global cstd... ')
221 ret = conf.TryLink(check_global_cstd_source, '.c')
229 def checkSelectArgType(conf):
230 ''' Adapted from autoconf '''
231 conf.Message('Checking for arg types for select... ')
232 for arg234 in ['fd_set *', 'int *', 'void *']:
233 for arg1 in ['int', 'size_t', 'unsigned long', 'unsigned']:
234 for arg5 in ['struct timeval *', 'const struct timeval *']:
235 check_select_source = '''
236 #if HAVE_SYS_SELECT_H
237 # include <sys/select.h>
239 #if HAVE_SYS_SOCKET_H
240 # include <sys/socket.h>
242 extern int select (%s, %s, %s, %s, %s);
247 ''' % (arg1, arg234, arg234, arg234, arg5)
248 ret = conf.TryLink(check_select_source, '.c')
251 return (arg1, arg234, arg5)
252 conf.Result('no (use default)')
253 return ('int', 'int *', 'struct timeval *')
256 def checkBoostLibraries(conf, lib, pathes):
257 ''' look for boost libraries '''
258 conf.Message('Checking for boost library %s... ' % lib)
260 # direct form: e.g. libboost_iostreams.a
261 if os.path.isfile(os.path.join(path, 'lib%s.a' % lib)):
264 # check things like libboost_iostreams-gcc.a
265 files = glob.glob(os.path.join(path, 'lib%s-*.a' % lib))
266 # if there are more than one, choose the first one
267 # FIXME: choose the best one.
269 # get xxx-gcc from /usr/local/lib/libboost_xxx-gcc.a
271 return (path, files[0].split(os.sep)[-1][3:-2])
276 def checkCommand(conf, cmd):
277 ''' check the existence of a command
278 return full path to the command, or none
280 conf.Message('Checking for command %s...' % cmd)
282 conf.Result(res is not None)
286 def checkLC_MESSAGES(conf):
287 ''' check the definition of LC_MESSAGES '''
288 check_LC_MESSAGES = '''
295 conf.Message('Check for LC_MESSAGES in locale.h... ')
296 ret = conf.TryLink(check_LC_MESSAGES, '.c')
301 # FIXME: not quite sure about this part.
302 def checkIconvConst(conf):
303 ''' check the declaration of iconv '''
304 check_iconv_const = '''
311 #if defined(__STDC__) || defined(__cplusplus)
312 #ifndef LIBICONV_DLL_EXPORTED
313 size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);
324 conf.Message('Check if the declaration of iconv needs const... ')
325 ret = conf.TryLink(check_iconv_const, '.c')
330 def installCygwinLDScript(path):
331 ''' Install i386pe.x-no-rdata '''
332 ld_script = os.path.join(path, 'i386pe.x-no-rdata')
333 script = open(ld_script, 'w')
334 script.write('''/* specific linker script avoiding .rdata sections, for normal executables
336 http://www.cygwin.com/ml/cygwin/2004-09/msg01101.html
337 http://www.cygwin.com/ml/cygwin-apps/2004-09/msg00309.html
339 OUTPUT_FORMAT(pei-i386)
340 SEARCH_DIR("/usr/i686-pc-cygwin/lib"); SEARCH_DIR("/usr/lib"); SEARCH_DIR("/usr/lib/w32api");
341 ENTRY(_mainCRTStartup)
344 .text __image_base__ + __section_alignment__ :
351 ___CTOR_LIST__ = .; __CTOR_LIST__ = . ;
352 LONG (-1);*(.ctors); *(.ctor); *(SORT(.ctors.*)); LONG (0);
353 ___DTOR_LIST__ = .; __DTOR_LIST__ = . ;
354 LONG (-1); *(.dtors); *(.dtor); *(SORT(.dtors.*)); LONG (0);
356 /* ??? Why is .gcc_exc here? */
361 /* The Cygwin32 library uses a section to avoid copying certain data
362 on fork. This used to be named ".data". The linker used
363 to include this between __data_start__ and __data_end__, but that
364 breaks building the cygwin32 dll. Instead, we name the section
365 ".data_cygwin_nocopy" and explictly include it after __data_end__. */
366 .data BLOCK(__section_alignment__) :
375 ___RUNTIME_PSEUDO_RELOC_LIST__ = .;
376 __RUNTIME_PSEUDO_RELOC_LIST__ = .;
377 *(.rdata_runtime_pseudo_reloc)
378 ___RUNTIME_PSEUDO_RELOC_LIST_END__ = .;
379 __RUNTIME_PSEUDO_RELOC_LIST_END__ = .;
381 *(.data_cygwin_nocopy)
383 .rdata BLOCK(__section_alignment__) :
386 .pdata BLOCK(__section_alignment__) :
390 .bss BLOCK(__section_alignment__) :
397 .edata BLOCK(__section_alignment__) :
408 .idata BLOCK(__section_alignment__) :
410 /* This cannot currently be handled with grouped sections.
411 See pe.em:sort_sections. */
414 /* These zeroes mark the end of the import list. */
415 LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);
421 .CRT BLOCK(__section_alignment__) :
423 ___crt_xc_start__ = . ;
424 *(SORT(.CRT$XC*)) /* C initialization */
425 ___crt_xc_end__ = . ;
426 ___crt_xi_start__ = . ;
427 *(SORT(.CRT$XI*)) /* C++ initialization */
428 ___crt_xi_end__ = . ;
429 ___crt_xl_start__ = . ;
430 *(SORT(.CRT$XL*)) /* TLS callbacks */
431 /* ___crt_xl_end__ is defined in the TLS Directory support code */
432 ___crt_xp_start__ = . ;
433 *(SORT(.CRT$XP*)) /* Pre-termination */
434 ___crt_xp_end__ = . ;
435 ___crt_xt_start__ = . ;
436 *(SORT(.CRT$XT*)) /* Termination */
437 ___crt_xt_end__ = . ;
439 .tls BLOCK(__section_alignment__) :
447 .endjunk BLOCK(__section_alignment__) :
449 /* end is deprecated, don't use it */
454 .rsrc BLOCK(__section_alignment__) :
459 .reloc BLOCK(__section_alignment__) :
463 .stab BLOCK(__section_alignment__) (NOLOAD) :
467 .stabstr BLOCK(__section_alignment__) (NOLOAD) :
471 /* DWARF debug sections.
472 Symbols in the DWARF debugging sections are relative to the beginning
473 of the section. Unlike other targets that fake this by putting the
474 section VMA at 0, the PE format will not allow it. */
475 /* DWARF 1.1 and DWARF 2. */
476 .debug_aranges BLOCK(__section_alignment__) (NOLOAD) :
480 .debug_pubnames BLOCK(__section_alignment__) (NOLOAD) :
485 .debug_info BLOCK(__section_alignment__) (NOLOAD) :
487 *(.debug_info) *(.gnu.linkonce.wi.*)
489 .debug_abbrev BLOCK(__section_alignment__) (NOLOAD) :
493 .debug_line BLOCK(__section_alignment__) (NOLOAD) :
497 .debug_frame BLOCK(__section_alignment__) (NOLOAD) :
501 .debug_str BLOCK(__section_alignment__) (NOLOAD) :
505 .debug_loc BLOCK(__section_alignment__) (NOLOAD) :
509 .debug_macinfo BLOCK(__section_alignment__) (NOLOAD) :
513 /* SGI/MIPS DWARF 2 extensions. */
514 .debug_weaknames BLOCK(__section_alignment__) (NOLOAD) :
518 .debug_funcnames BLOCK(__section_alignment__) (NOLOAD) :
522 .debug_typenames BLOCK(__section_alignment__) (NOLOAD) :
526 .debug_varnames BLOCK(__section_alignment__) (NOLOAD) :
531 .debug_ranges BLOCK(__section_alignment__) (NOLOAD) :
542 # these will be used under win32
548 # does not matter if it fails on other systems
553 def __init__(self, env, logfile, longarg, info):
554 # save the spawn system
556 self.logfile = logfile
557 # clear the logfile (it may not exist)
559 # this will overwrite existing content.
560 writeToFile(logfile, info, append=False)
562 self.longarg = longarg
563 # get hold of the old spawn? (necessary?)
564 self._spawn = env['SPAWN']
567 def spawn(self, sh, escape, cmd, args, spawnenv):
569 newargs = ' '.join(map(escape, args[1:]))
570 cmdline = cmd + " " + newargs
572 # if log is not empty, write to it
573 if self.logfile != '':
574 # this tend to be slow (?) but ensure correct output
575 # Note that cmdline may be long so I do not escape it
577 # since this is not an essential operation, proceed if things go wrong here.
578 writeToFile(self.logfile, cmd + " " + ' '.join(args[1:]) + '\n', append=True)
580 print "Warning: can not write to log file ", self.logfile
582 # if the command is not too long, use the old
583 if not self.longarg or len(cmdline) < 8000:
584 exit_code = self._spawn(sh, escape, cmd, args, spawnenv)
586 sAttrs = win32security.SECURITY_ATTRIBUTES()
587 StartupInfo = win32process.STARTUPINFO()
589 spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
590 # check for any special operating system commands
593 win32file.DeleteFile(arg)
596 # otherwise execute the command.
597 hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
598 win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
599 exit_code = win32process.GetExitCodeProcess(hProcess)
600 win32file.CloseHandle(hProcess);
601 win32file.CloseHandle(hThread);
605 def setLoggedSpawn(env, logfile = '', longarg=False, info=''):
606 ''' This function modify env and allow logging of
607 commands to a logfile. If the argument is too long
608 a win32 spawn will be used instead of the system one
611 # create a new spwn object
612 ls = loggedSpawn(env, logfile, longarg, info)
613 # replace the old SPAWN by the new function
614 env['SPAWN'] = ls.spawn
617 ## def DistSources(env, node):
618 ## env.DistFiles(_get_sources(env, node))
620 ## def DistFiles(env, files):
621 ## assert isinstance(files, (list, tuple))
622 ## DISTFILES = [env.File(fname) for fname in files]
623 ## env.AppendUnique(DISTFILES=DISTFILES)
626 ## def make_distdir(target=None, source=None, env=None):
627 ## distdir = env.subst('$DISTDIR')
628 ## Execute(Delete(distdir))
629 ## Execute(Mkdir(distdir))
630 ## for fnode in env["DISTFILES"]:
631 ## dirname, fname = os.path.split(str(fnode))
633 ## distdirname = os.path.join(distdir, dirname)
634 ## if not os.path.exists(distdirname):
635 ## Execute(Mkdir(distdirname))
636 ## Execute(Copy(os.path.join(distdir, dirname, fname), str(fnode)))
638 ## def make_dist(target=None, source=None, env=None):
639 ## return Popen([env['TAR'], "-zcf",
640 ## env.subst("${PACKAGE}-${VERSION}.tar.gz"),
641 ## env.subst('$DISTDIR')]).wait()
643 ## def make_distcheck(target=None, source=None, env=None):
644 ## distdir = env.subst('$DISTDIR')
645 ## distcheckinstdir = tempfile.mkdtemp('', env.subst('${PACKAGE}-${VERSION}-instdir-'))
646 ## distcheckdestdir = tempfile.mkdtemp('', env.subst('${PACKAGE}-${VERSION}-destdir-'))
647 ## instdirs = [os.path.join(distcheckinstdir, d) for d in
648 ## 'lib', 'share', 'bin', 'include']
649 ## for dir_ in instdirs:
650 ## Execute(Mkdir(dir_))
652 ## cmd = env.subst("cd $DISTDIR && scons DESTDIR=%s prefix=%s"
653 ## " && scons check && scons install") %\
654 ## (os.path.join(distcheckdestdir, ''), distcheckinstdir)
655 ## status = Popen(cmd, shell=True).wait()
658 ## ## Check that inst dirs are empty (to catch cases of $DESTDIR not being honored
659 ## for dir_ in instdirs:
660 ## if os.listdir(dir_):
661 ## raise SCons.Errors.BuildError(target, "%s not empy" % dir_)
662 ## ## Check that something inside $DESTDIR was installed
663 ## dir_ = os.path.join(distcheckdestdir, distcheckinstdir)
664 ## if not os.path.exists(dir_):
665 ## raise SCons.Errors.BuildError(target, "%s does not exist" % dir_)
666 ## Execute(Delete(distcheckinstdir))
667 ## Execute(Delete(distcheckdestdir))
668 ## Execute(Delete(distdir))
670 ## def InstallWithDestDir(self, dir_, source):
671 ## dir_ = '${DESTDIR}' + str(dir_)
672 ## return SConsEnvironment.Install(self, dir_, source)
675 ## def InstallAsWithDestDir(self, target, source):
676 ## target = '${DESTDIR}' + str(target)
677 ## return SConsEnvironment.InstallAs(self, target, source)
679 ## def generate(env):
680 ## env.EnsureSConsVersion(0, 96, 91)
682 ## opts = Options(['options.cache'], ARGUMENTS)
683 ## opts.Add(PathOption('prefix', 'Installation prefix', '/usr/local'))
684 ## opts.Add(PathOption('exec_prefix', 'Installation prefix blah blah',
686 ## opts.Add(PathOption('libdir',
687 ## 'Installation prefix for architecture dependent files', '$prefix/lib'))
688 ## opts.Add(PathOption('includedir',
689 ## 'Installation prefix for C header files', '$prefix/include'))
690 ## opts.Add(PathOption('datadir',
691 ## 'Installation prefix for architecture independent files', '$prefix/share'))
692 ## opts.Add(PathOption('bindir', 'Installation prefix for programs', '$prefix/bin'))
693 ## opts.Add(PathOption('DESTDIR', 'blah blah', None))
695 ## opts.Save('options.cache', env)
696 ## SConsEnvironment.Help(env, opts.GenerateHelpText(env))
698 ## env.Append(CPPFLAGS=r' -DVERSION=\"$VERSION\"')
699 ## env.Append(CCFLAGS=ARGUMENTS.get('CCFLAGS', '-g -O2'))
701 ## env['GNOME_TESTS'] = dict(CheckPython=CheckPython,
702 ## CheckPythonHeaders=CheckPythonHeaders,
703 ## PkgCheckModules=PkgCheckModules)
705 ## SConsEnvironment.DistSources = DistSources
706 ## SConsEnvironment.DistFiles = DistFiles
707 ## env['DISTDIR'] = "${PACKAGE}-${VERSION}"
709 ## #env.Command(env.Dir("$DISTDIR"), None, make_distdir)
711 ## distdir_alias = env.Alias("distdir", None, make_distdir)
712 ## dist_alias = env.Alias("dist", None, make_dist)
713 ## env.Depends(dist_alias, distdir_alias)
714 ## distcheck_alias = env.Alias("distcheck", None, make_distcheck)
715 ## env.Depends(distcheck_alias, distdir_alias)
716 ## env.AlwaysBuild(env.Alias('check'))
718 ## #env['TARFLAGS'] ='-c -z'
719 ## #env['TARSUFFIX'] = '.tar.gz'
720 ## #tar = env.Tar('${PACKAGE}-${VERSION}.tar.gz', "${DISTDIR}")
721 ## #env.Depends(tar, distdir_alias)
722 ## #print env['DEFAULT_TARGETS']
724 ## #env.Depends(distdir_alias, "${DISTFILES}")
725 ## #env.Alias('dist', tar)
726 ## env.AlwaysBuild('dist')
727 ## env.AlwaysBuild('distdir')
728 ## env.AlwaysBuild('distcheck')
729 ## env.DistFiles(['SConstruct', 'scons/gnome.py'])
731 ## env['BUILDERS']['EnvSubstFile'] = SCons.Builder.Builder(action=env_subst)
733 ## SConsEnvironment.PythonByteCompile = env.Action(byte_compile_python)
735 ## env.Install = new.instancemethod(InstallWithDestDir, env, env.__class__)
736 ## env.InstallAs = new.instancemethod(InstallAsWithDestDir, env, env.__class__)