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 checkLC_MESSAGES(conf):
285 ''' check the definition of LC_MESSAGES '''
286 check_LC_MESSAGES = '''
293 conf.Message('Check for LC_MESSAGES in locale.h... ')
294 ret = conf.TryLink(check_LC_MESSAGES, '.c')
299 # FIXME: not quite sure about this part.
300 def checkIconvConst(conf):
301 ''' check the declaration of iconv '''
302 check_iconv_const = '''
309 #if defined(__STDC__) || defined(__cplusplus)
310 size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);
314 extern size_t iconv(iconv_t cd, const char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);
320 conf.Message('Check if the declaration of iconv needs const... ')
321 ret = conf.TryLink(check_iconv_const, '.c')
326 def installCygwinLDScript(path):
327 ''' Install i386pe.x-no-rdata '''
328 ld_script = os.path.join(path, 'i386pe.x-no-rdata')
329 script = open(ld_script, 'w')
330 script.write('''/* specific linker script avoiding .rdata sections, for normal executables
332 http://www.cygwin.com/ml/cygwin/2004-09/msg01101.html
333 http://www.cygwin.com/ml/cygwin-apps/2004-09/msg00309.html
335 OUTPUT_FORMAT(pei-i386)
336 SEARCH_DIR("/usr/i686-pc-cygwin/lib"); SEARCH_DIR("/usr/lib"); SEARCH_DIR("/usr/lib/w32api");
337 ENTRY(_mainCRTStartup)
340 .text __image_base__ + __section_alignment__ :
347 ___CTOR_LIST__ = .; __CTOR_LIST__ = . ;
348 LONG (-1);*(.ctors); *(.ctor); *(SORT(.ctors.*)); LONG (0);
349 ___DTOR_LIST__ = .; __DTOR_LIST__ = . ;
350 LONG (-1); *(.dtors); *(.dtor); *(SORT(.dtors.*)); LONG (0);
352 /* ??? Why is .gcc_exc here? */
357 /* The Cygwin32 library uses a section to avoid copying certain data
358 on fork. This used to be named ".data". The linker used
359 to include this between __data_start__ and __data_end__, but that
360 breaks building the cygwin32 dll. Instead, we name the section
361 ".data_cygwin_nocopy" and explictly include it after __data_end__. */
362 .data BLOCK(__section_alignment__) :
371 ___RUNTIME_PSEUDO_RELOC_LIST__ = .;
372 __RUNTIME_PSEUDO_RELOC_LIST__ = .;
373 *(.rdata_runtime_pseudo_reloc)
374 ___RUNTIME_PSEUDO_RELOC_LIST_END__ = .;
375 __RUNTIME_PSEUDO_RELOC_LIST_END__ = .;
377 *(.data_cygwin_nocopy)
379 .rdata BLOCK(__section_alignment__) :
382 .pdata BLOCK(__section_alignment__) :
386 .bss BLOCK(__section_alignment__) :
393 .edata BLOCK(__section_alignment__) :
404 .idata BLOCK(__section_alignment__) :
406 /* This cannot currently be handled with grouped sections.
407 See pe.em:sort_sections. */
410 /* These zeroes mark the end of the import list. */
411 LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);
417 .CRT BLOCK(__section_alignment__) :
419 ___crt_xc_start__ = . ;
420 *(SORT(.CRT$XC*)) /* C initialization */
421 ___crt_xc_end__ = . ;
422 ___crt_xi_start__ = . ;
423 *(SORT(.CRT$XI*)) /* C++ initialization */
424 ___crt_xi_end__ = . ;
425 ___crt_xl_start__ = . ;
426 *(SORT(.CRT$XL*)) /* TLS callbacks */
427 /* ___crt_xl_end__ is defined in the TLS Directory support code */
428 ___crt_xp_start__ = . ;
429 *(SORT(.CRT$XP*)) /* Pre-termination */
430 ___crt_xp_end__ = . ;
431 ___crt_xt_start__ = . ;
432 *(SORT(.CRT$XT*)) /* Termination */
433 ___crt_xt_end__ = . ;
435 .tls BLOCK(__section_alignment__) :
443 .endjunk BLOCK(__section_alignment__) :
445 /* end is deprecated, don't use it */
450 .rsrc BLOCK(__section_alignment__) :
455 .reloc BLOCK(__section_alignment__) :
459 .stab BLOCK(__section_alignment__) (NOLOAD) :
463 .stabstr BLOCK(__section_alignment__) (NOLOAD) :
467 /* DWARF debug sections.
468 Symbols in the DWARF debugging sections are relative to the beginning
469 of the section. Unlike other targets that fake this by putting the
470 section VMA at 0, the PE format will not allow it. */
471 /* DWARF 1.1 and DWARF 2. */
472 .debug_aranges BLOCK(__section_alignment__) (NOLOAD) :
476 .debug_pubnames BLOCK(__section_alignment__) (NOLOAD) :
481 .debug_info BLOCK(__section_alignment__) (NOLOAD) :
483 *(.debug_info) *(.gnu.linkonce.wi.*)
485 .debug_abbrev BLOCK(__section_alignment__) (NOLOAD) :
489 .debug_line BLOCK(__section_alignment__) (NOLOAD) :
493 .debug_frame BLOCK(__section_alignment__) (NOLOAD) :
497 .debug_str BLOCK(__section_alignment__) (NOLOAD) :
501 .debug_loc BLOCK(__section_alignment__) (NOLOAD) :
505 .debug_macinfo BLOCK(__section_alignment__) (NOLOAD) :
509 /* SGI/MIPS DWARF 2 extensions. */
510 .debug_weaknames BLOCK(__section_alignment__) (NOLOAD) :
514 .debug_funcnames BLOCK(__section_alignment__) (NOLOAD) :
518 .debug_typenames BLOCK(__section_alignment__) (NOLOAD) :
522 .debug_varnames BLOCK(__section_alignment__) (NOLOAD) :
527 .debug_ranges BLOCK(__section_alignment__) (NOLOAD) :
538 # these will be used under win32
544 # does not matter if it fails on other systems
549 def __init__(self, env, logfile, longarg, info):
550 # save the spawn system
552 self.logfile = logfile
553 # clear the logfile (it may not exist)
555 # this will overwrite existing content.
556 writeToFile(logfile, info, append=False)
558 self.longarg = longarg
559 # get hold of the old spawn? (necessary?)
560 self._spawn = env['SPAWN']
563 def spawn(self, sh, escape, cmd, args, spawnenv):
565 newargs = ' '.join(map(escape, args[1:]))
566 cmdline = cmd + " " + newargs
568 # if log is not empty, write to it
569 if self.logfile != '':
570 # this tend to be slow (?) but ensure correct output
571 # Note that cmdline may be long so I do not escape it
573 # since this is not an essential operation, proceed if things go wrong here.
574 writeToFile(self.logfile, cmd + " " + ' '.join(args[1:]) + '\n', append=True)
576 print "Warning: can not write to log file ", self.logfile
578 # if the command is not too long, use the old
579 if not self.longarg or len(cmdline) < 8000:
580 exit_code = self._spawn(sh, escape, cmd, args, spawnenv)
582 sAttrs = win32security.SECURITY_ATTRIBUTES()
583 StartupInfo = win32process.STARTUPINFO()
585 spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
586 # check for any special operating system commands
589 win32file.DeleteFile(arg)
592 # otherwise execute the command.
593 hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
594 win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
595 exit_code = win32process.GetExitCodeProcess(hProcess)
596 win32file.CloseHandle(hProcess);
597 win32file.CloseHandle(hThread);
601 def setLoggedSpawn(env, logfile = '', longarg=False, info=''):
602 ''' This function modify env and allow logging of
603 commands to a logfile. If the argument is too long
604 a win32 spawn will be used instead of the system one
607 # create a new spwn object
608 ls = loggedSpawn(env, logfile, longarg, info)
609 # replace the old SPAWN by the new function
610 env['SPAWN'] = ls.spawn
613 ## def DistSources(env, node):
614 ## env.DistFiles(_get_sources(env, node))
616 ## def DistFiles(env, files):
617 ## assert isinstance(files, (list, tuple))
618 ## DISTFILES = [env.File(fname) for fname in files]
619 ## env.AppendUnique(DISTFILES=DISTFILES)
622 ## def make_distdir(target=None, source=None, env=None):
623 ## distdir = env.subst('$DISTDIR')
624 ## Execute(Delete(distdir))
625 ## Execute(Mkdir(distdir))
626 ## for fnode in env["DISTFILES"]:
627 ## dirname, fname = os.path.split(str(fnode))
629 ## distdirname = os.path.join(distdir, dirname)
630 ## if not os.path.exists(distdirname):
631 ## Execute(Mkdir(distdirname))
632 ## Execute(Copy(os.path.join(distdir, dirname, fname), str(fnode)))
634 ## def make_dist(target=None, source=None, env=None):
635 ## return Popen([env['TAR'], "-zcf",
636 ## env.subst("${PACKAGE}-${VERSION}.tar.gz"),
637 ## env.subst('$DISTDIR')]).wait()
639 ## def make_distcheck(target=None, source=None, env=None):
640 ## distdir = env.subst('$DISTDIR')
641 ## distcheckinstdir = tempfile.mkdtemp('', env.subst('${PACKAGE}-${VERSION}-instdir-'))
642 ## distcheckdestdir = tempfile.mkdtemp('', env.subst('${PACKAGE}-${VERSION}-destdir-'))
643 ## instdirs = [os.path.join(distcheckinstdir, d) for d in
644 ## 'lib', 'share', 'bin', 'include']
645 ## for dir_ in instdirs:
646 ## Execute(Mkdir(dir_))
648 ## cmd = env.subst("cd $DISTDIR && scons DESTDIR=%s prefix=%s"
649 ## " && scons check && scons install") %\
650 ## (os.path.join(distcheckdestdir, ''), distcheckinstdir)
651 ## status = Popen(cmd, shell=True).wait()
654 ## ## Check that inst dirs are empty (to catch cases of $DESTDIR not being honored
655 ## for dir_ in instdirs:
656 ## if os.listdir(dir_):
657 ## raise SCons.Errors.BuildError(target, "%s not empy" % dir_)
658 ## ## Check that something inside $DESTDIR was installed
659 ## dir_ = os.path.join(distcheckdestdir, distcheckinstdir)
660 ## if not os.path.exists(dir_):
661 ## raise SCons.Errors.BuildError(target, "%s does not exist" % dir_)
662 ## Execute(Delete(distcheckinstdir))
663 ## Execute(Delete(distcheckdestdir))
664 ## Execute(Delete(distdir))
666 ## def InstallWithDestDir(self, dir_, source):
667 ## dir_ = '${DESTDIR}' + str(dir_)
668 ## return SConsEnvironment.Install(self, dir_, source)
671 ## def InstallAsWithDestDir(self, target, source):
672 ## target = '${DESTDIR}' + str(target)
673 ## return SConsEnvironment.InstallAs(self, target, source)
675 ## def generate(env):
676 ## env.EnsureSConsVersion(0, 96, 91)
678 ## opts = Options(['options.cache'], ARGUMENTS)
679 ## opts.Add(PathOption('prefix', 'Installation prefix', '/usr/local'))
680 ## opts.Add(PathOption('exec_prefix', 'Installation prefix blah blah',
682 ## opts.Add(PathOption('libdir',
683 ## 'Installation prefix for architecture dependent files', '$prefix/lib'))
684 ## opts.Add(PathOption('includedir',
685 ## 'Installation prefix for C header files', '$prefix/include'))
686 ## opts.Add(PathOption('datadir',
687 ## 'Installation prefix for architecture independent files', '$prefix/share'))
688 ## opts.Add(PathOption('bindir', 'Installation prefix for programs', '$prefix/bin'))
689 ## opts.Add(PathOption('DESTDIR', 'blah blah', None))
691 ## opts.Save('options.cache', env)
692 ## SConsEnvironment.Help(env, opts.GenerateHelpText(env))
694 ## env.Append(CPPFLAGS=r' -DVERSION=\"$VERSION\"')
695 ## env.Append(CCFLAGS=ARGUMENTS.get('CCFLAGS', '-g -O2'))
697 ## env['GNOME_TESTS'] = dict(CheckPython=CheckPython,
698 ## CheckPythonHeaders=CheckPythonHeaders,
699 ## PkgCheckModules=PkgCheckModules)
701 ## SConsEnvironment.DistSources = DistSources
702 ## SConsEnvironment.DistFiles = DistFiles
703 ## env['DISTDIR'] = "${PACKAGE}-${VERSION}"
705 ## #env.Command(env.Dir("$DISTDIR"), None, make_distdir)
707 ## distdir_alias = env.Alias("distdir", None, make_distdir)
708 ## dist_alias = env.Alias("dist", None, make_dist)
709 ## env.Depends(dist_alias, distdir_alias)
710 ## distcheck_alias = env.Alias("distcheck", None, make_distcheck)
711 ## env.Depends(distcheck_alias, distdir_alias)
712 ## env.AlwaysBuild(env.Alias('check'))
714 ## #env['TARFLAGS'] ='-c -z'
715 ## #env['TARSUFFIX'] = '.tar.gz'
716 ## #tar = env.Tar('${PACKAGE}-${VERSION}.tar.gz', "${DISTDIR}")
717 ## #env.Depends(tar, distdir_alias)
718 ## #print env['DEFAULT_TARGETS']
720 ## #env.Depends(distdir_alias, "${DISTFILES}")
721 ## #env.Alias('dist', tar)
722 ## env.AlwaysBuild('dist')
723 ## env.AlwaysBuild('distdir')
724 ## env.AlwaysBuild('distcheck')
725 ## env.DistFiles(['SConstruct', 'scons/gnome.py'])
727 ## env['BUILDERS']['EnvSubstFile'] = SCons.Builder.Builder(action=env_subst)
729 ## SConsEnvironment.PythonByteCompile = env.Action(byte_compile_python)
731 ## env.Install = new.instancemethod(InstallWithDestDir, env, env.__class__)
732 ## env.InstallAs = new.instancemethod(InstallAsWithDestDir, env, env.__class__)