Add a Memoizer metaclass to collect the logic for caching values in one location...
[scons.git] / SConstruct
1 #
2 # SConstruct file to build scons packages during development.
3 #
4 # See the README file for an overview of how SCons is built and tested.
5 #
6
7 copyright_years = '2001, 2002, 2003, 2004'
8
9 #
10 # __COPYRIGHT__
11 #
12 # Permission is hereby granted, free of charge, to any person obtaining
13 # a copy of this software and associated documentation files (the
14 # "Software"), to deal in the Software without restriction, including
15 # without limitation the rights to use, copy, modify, merge, publish,
16 # distribute, sublicense, and/or sell copies of the Software, and to
17 # permit persons to whom the Software is furnished to do so, subject to
18 # the following conditions:
19 #
20 # The above copyright notice and this permission notice shall be included
21 # in all copies or substantial portions of the Software.
22 #
23 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
24 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
25 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 #
31
32 import distutils.util
33 import os
34 import os.path
35 import socket
36 import stat
37 import string
38 import sys
39 import time
40
41 project = 'scons'
42 default_version = '0.96'
43 copyright = "Copyright (c) %s The SCons Foundation" % copyright_years
44
45 Default('.')
46
47 SConsignFile()
48
49 #
50 # An internal "whereis" routine to figure out if a given program
51 # is available on this system.
52 #
53 def whereis(file):
54     for dir in string.split(os.environ['PATH'], os.pathsep):
55         f = os.path.join(dir, file)
56         if os.path.isfile(f):
57             try:
58                 st = os.stat(f)
59             except:
60                 continue
61             if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
62                 return f
63     return None
64
65 #
66 # We let the presence or absence of various utilities determine
67 # whether or not we bother to build certain pieces of things.
68 # This should allow people to still do SCons work even if they
69 # don't have Aegis or RPM installed, for example.
70 #
71 aegis = whereis('aegis')
72 aesub = whereis('aesub')
73 dh_builddeb = whereis('dh_builddeb')
74 fakeroot = whereis('fakeroot')
75 gzip = whereis('gzip')
76 rpmbuild = whereis('rpmbuild') or whereis('rpm')
77 unzip = whereis('unzip')
78 zip = whereis('zip')
79
80 #
81 # Now grab the information that we "build" into the files.
82 #
83 try:
84     date = ARGUMENTS['date']
85 except:
86     date = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(time.time()))
87
88 if ARGUMENTS.has_key('developer'):
89     developer = ARGUMENTS['developer']
90 elif os.environ.has_key('USERNAME'):
91     developer = os.environ['USERNAME']
92 elif os.environ.has_key('LOGNAME'):
93     developer = os.environ['LOGNAME']
94 elif os.environ.has_key('USER'):
95     developer = os.environ['USER']
96
97 if ARGUMENTS.has_key('build_system'):
98     build_system = ARGUMENTS['build_system']
99 else:
100     build_system = string.split(socket.gethostname(), '.')[0]
101
102 if ARGUMENTS.has_key('version'):
103     revision = ARGUMENTS['version']
104 elif aesub:
105     revision = os.popen(aesub + " \\$version", "r").read()[:-1]
106 else:
107     revision = default_version
108
109 # This is old code that adds an initial "0" to revision numbers < 10.
110 #a = string.split(revision, '.')
111 #arr = [a[0]]
112 #for s in a[1:]:
113 #    if len(s) == 1:
114 #        s = '0' + s
115 #    arr.append(s)
116 #revision = string.join(arr, '.')
117
118 # Here's how we'd turn the calculated $revision into our package $version.
119 # This makes it difficult to coordinate with other files (debian/changelog
120 # and rpm/scons.spec) that hard-code the version number, so just go with
121 # the flow for now and hard code it here, too.
122 #if len(arr) >= 2:
123 #    arr = arr[:-1]
124 #def xxx(str):
125 #    if str[0] == 'C' or str[0] == 'D':
126 #        str = str[1:]
127 #    while len(str) > 2 and str[0] == '0':
128 #        str = str[1:]
129 #    return str
130 #arr = map(lambda x, xxx=xxx: xxx(x), arr)
131 #version = string.join(arr, '.')
132 version = default_version
133
134 build_id = string.replace(revision, version + '.', '')
135
136 if ARGUMENTS.has_key('change'):
137     change = ARGUMENTS['change']
138 elif aesub:
139     change = os.popen(aesub + " \\$change", "r").read()[:-1]
140 else:
141     change = default_version
142
143 python_ver = sys.version[0:3]
144
145 platform = distutils.util.get_platform()
146
147 ENV = { 'PATH' : os.environ['PATH'] }
148 for key in ['AEGIS_PROJECT', 'LOGNAME', 'PYTHONPATH']:
149     if os.environ.has_key(key):
150         ENV[key] = os.environ[key]
151
152 cwd_build = os.path.join(os.getcwd(), "build")
153
154 test_deb_dir          = os.path.join(cwd_build, "test-deb")
155 test_rpm_dir          = os.path.join(cwd_build, "test-rpm")
156 test_tar_gz_dir       = os.path.join(cwd_build, "test-tar-gz")
157 test_src_tar_gz_dir   = os.path.join(cwd_build, "test-src-tar-gz")
158 test_local_tar_gz_dir = os.path.join(cwd_build, "test-local-tar-gz")
159 test_zip_dir          = os.path.join(cwd_build, "test-zip")
160 test_src_zip_dir      = os.path.join(cwd_build, "test-src-zip")
161 test_local_zip_dir    = os.path.join(cwd_build, "test-local-zip")
162
163 unpack_tar_gz_dir     = os.path.join(cwd_build, "unpack-tar-gz")
164 unpack_zip_dir        = os.path.join(cwd_build, "unpack-zip")
165
166 if platform == "win32":
167     tar_hflag = ''
168     python_project_subinst_dir = os.path.join("Lib", "site-packages", project)
169     project_script_subinst_dir = 'Scripts'
170 else:
171     tar_hflag = 'h'
172     python_project_subinst_dir = os.path.join("lib", project)
173     project_script_subinst_dir = 'bin'
174
175
176 zcat = 'gzip -d -c'
177
178 #
179 # Figure out if we can handle .zip files.
180 #
181 zipit = None
182 unzipit = None
183 try:
184     import zipfile
185
186     def zipit(env, target, source):
187         print "Zipping %s:" % str(target[0])
188         def visit(arg, dirname, names):
189             for name in names:
190                 path = os.path.join(dirname, name)
191                 if os.path.isfile(path):
192                     arg.write(path)
193         zf = zipfile.ZipFile(str(target[0]), 'w')
194         olddir = os.getcwd()
195         os.chdir(env['CD'])
196         try: os.path.walk(env['PSV'], visit, zf)
197         finally: os.chdir(olddir)
198         zf.close()
199
200     def unzipit(env, target, source):
201         print "Unzipping %s:" % str(source[0])
202         zf = zipfile.ZipFile(str(source[0]), 'r')
203         for name in zf.namelist():
204             dest = os.path.join(env['UNPACK_ZIP_DIR'], name)
205             dir = os.path.dirname(dest)
206             try:
207                 os.makedirs(dir)
208             except:
209                 pass
210             print dest,name
211             # if the file exists, then delete it before writing
212             # to it so that we don't end up trying to write to a symlink:
213             if os.path.isfile(dest) or os.path.islink(dest):
214                 os.unlink(dest)
215             if not os.path.isdir(dest):
216                 open(dest, 'w').write(zf.read(name))
217
218 except:
219     if unzip and zip:
220         zipit = "cd $CD && $ZIP $ZIPFLAGS $( ${TARGET.abspath} $) $PSV"
221         unzipit = "$UNZIP $UNZIPFLAGS $SOURCES"
222
223 def SCons_revision(target, source, env):
224     """Interpolate specific values from the environment into a file.
225
226     This is used to copy files into a tree that gets packaged up
227     into the source file package.
228     """
229     t = str(target[0])
230     s = source[0].rstr()
231     contents = open(s, 'rb').read()
232     # Note:  We construct the __*__ substitution strings here
233     # so that they don't get replaced when this file gets
234     # copied into the tree for packaging.
235     contents = string.replace(contents, '__BUILD'     + '__', env['BUILD'])
236     contents = string.replace(contents, '__BUILDSYS'  + '__', env['BUILDSYS'])
237     contents = string.replace(contents, '__COPYRIGHT' + '__', env['COPYRIGHT'])
238     contents = string.replace(contents, '__DATE'      + '__', env['DATE'])
239     contents = string.replace(contents, '__DEVELOPER' + '__', env['DEVELOPER'])
240     contents = string.replace(contents, '__FILE'      + '__', str(source[0]))
241     contents = string.replace(contents, '__REVISION'  + '__', env['REVISION'])
242     contents = string.replace(contents, '__VERSION'   + '__', env['VERSION'])
243     contents = string.replace(contents, '__NULL'      + '__', '')
244     open(t, 'wb').write(contents)
245     os.chmod(t, os.stat(s)[0])
246
247 revbuilder = Builder(action = Action(SCons_revision,
248                                      varlist=['COPYRIGHT', 'VERSION']))
249
250 env = Environment(
251                    ENV                 = ENV,
252
253                    BUILD               = build_id,
254                    BUILDSYS            = build_system,
255                    COPYRIGHT           = copyright,
256                    DATE                = date,
257                    DEVELOPER           = developer,
258                    REVISION            = revision,
259                    VERSION             = version,
260                    DH_COMPAT           = 2,
261
262                    TAR_HFLAG           = tar_hflag,
263
264                    ZIP                 = zip,
265                    ZIPFLAGS            = '-r',
266                    UNZIP               = unzip,
267                    UNZIPFLAGS          = '-o -d $UNPACK_ZIP_DIR',
268
269                    ZCAT                = zcat,
270
271                    RPMBUILD            = rpmbuild,
272                    RPM2CPIO            = 'rpm2cpio',
273
274                    TEST_DEB_DIR        = test_deb_dir,
275                    TEST_RPM_DIR        = test_rpm_dir,
276                    TEST_SRC_TAR_GZ_DIR = test_src_tar_gz_dir,
277                    TEST_SRC_ZIP_DIR    = test_src_zip_dir,
278                    TEST_TAR_GZ_DIR     = test_tar_gz_dir,
279                    TEST_ZIP_DIR        = test_zip_dir,
280
281                    UNPACK_TAR_GZ_DIR   = unpack_tar_gz_dir,
282                    UNPACK_ZIP_DIR      = unpack_zip_dir,
283
284                    BUILDERS            = { 'SCons_revision' : revbuilder },
285
286                    PYTHON              = sys.executable
287                  )
288
289 Version_values = [Value(version), Value(build_id)]
290
291 #
292 # Define SCons packages.
293 #
294 # In the original, more complicated packaging scheme, we were going
295 # to have separate packages for:
296 #
297 #       python-scons    only the build engine
298 #       scons-script    only the script
299 #       scons           the script plus the build engine
300 #
301 # We're now only delivering a single "scons" package, but this is still
302 # "built" as two sub-packages (the build engine and the script), so
303 # the definitions remain here, even though we're not using them for
304 # separate packages.
305 #
306
307 python_scons = {
308         'pkg'           : 'python-' + project,
309         'src_subdir'    : 'engine',
310         'inst_subdir'   : os.path.join('lib', 'python1.5', 'site-packages'),
311         'rpm_dir'       : '/usr/lib/scons',
312
313         'debian_deps'   : [
314                             'debian/changelog',
315                             'debian/control',
316                             'debian/copyright',
317                             'debian/dirs',
318                             'debian/docs',
319                             'debian/postinst',
320                             'debian/prerm',
321                             'debian/rules',
322                           ],
323
324         'files'         : [ 'LICENSE.txt',
325                             'README.txt',
326                             'setup.cfg',
327                             'setup.py',
328                           ],
329
330         'filemap'       : {
331                             'LICENSE.txt' : '../LICENSE.txt'
332                           },
333
334         'explicit_deps' : {
335                             'SCons/__init__.py' : Version_values,
336                           },
337 }
338
339 #
340 # The original packaging scheme would have have required us to push
341 # the Python version number into the package name (python1.5-scons,
342 # python2.0-scons, etc.), which would have required a definition
343 # like the following.  Leave this here in case we ever decide to do
344 # this in the future, but note that this would require some modification
345 # to src/engine/setup.py before it would really work.
346 #
347 #python2_scons = {
348 #        'pkg'          : 'python2-' + project,
349 #        'src_subdir'   : 'engine',
350 #        'inst_subdir'  : os.path.join('lib', 'python2.2', 'site-packages'),
351 #
352 #        'debian_deps'  : [
353 #                            'debian/changelog',
354 #                            'debian/control',
355 #                            'debian/copyright',
356 #                            'debian/dirs',
357 #                            'debian/docs',
358 #                            'debian/postinst',
359 #                            'debian/prerm',
360 #                            'debian/rules',
361 #                          ],
362 #
363 #        'files'        : [
364 #                            'LICENSE.txt',
365 #                            'README.txt',
366 #                            'setup.cfg',
367 #                            'setup.py',
368 #                          ],
369 #        'filemap'      : {
370 #                            'LICENSE.txt' : '../LICENSE.txt',
371 #                          },
372 #}
373 #
374
375 scons_script = {
376         'pkg'           : project + '-script',
377         'src_subdir'    : 'script',
378         'inst_subdir'   : 'bin',
379         'rpm_dir'       : '/usr/bin',
380
381         'debian_deps'   : [
382                             'debian/changelog',
383                             'debian/control',
384                             'debian/copyright',
385                             'debian/dirs',
386                             'debian/docs',
387                             'debian/postinst',
388                             'debian/prerm',
389                             'debian/rules',
390                           ],
391
392         'files'         : [
393                             'LICENSE.txt',
394                             'README.txt',
395                             'setup.cfg',
396                             'setup.py',
397                           ],
398
399         'filemap'       : {
400                             'LICENSE.txt' : '../LICENSE.txt',
401                             'scons'       : 'scons.py',
402                             'sconsign'    : 'sconsign.py',
403                            },
404
405         'explicit_deps' : {
406                             'scons'       : Version_values,
407                             'sconsign'    : Version_values,
408                           },
409 }
410
411 scons = {
412         'pkg'           : project,
413
414         'debian_deps'   : [
415                             'debian/changelog',
416                             'debian/control',
417                             'debian/copyright',
418                             'debian/dirs',
419                             'debian/docs',
420                             'debian/postinst',
421                             'debian/prerm',
422                             'debian/rules',
423                           ],
424
425         'files'         : [
426                             'CHANGES.txt',
427                             'LICENSE.txt',
428                             'README.txt',
429                             'RELEASE.txt',
430                             'os_spawnv_fix.diff',
431                             'scons.1',
432                             'sconsign.1',
433                             'script/scons.bat',
434                             'setup.cfg',
435                             'setup.py',
436                           ],
437
438         'filemap'       : {
439                             'scons.1' : '../doc/man/scons.1',
440                             'sconsign.1' : '../doc/man/sconsign.1',
441                           },
442
443         'subpkgs'       : [ python_scons, scons_script ],
444
445         'subinst_dirs'  : {
446                              'python-' + project : python_project_subinst_dir,
447                              project + '-script' : project_script_subinst_dir,
448                            },
449 }
450
451 scripts = ['scons', 'sconsign']
452
453 src_deps = []
454 src_files = []
455
456 for p in [ scons ]:
457     #
458     # Initialize variables with the right directories for this package.
459     #
460     pkg = p['pkg']
461     pkg_version = "%s-%s" % (pkg, version)
462
463     src = 'src'
464     if p.has_key('src_subdir'):
465         src = os.path.join(src, p['src_subdir'])
466
467     build = os.path.join('build', pkg)
468
469     tar_gz = os.path.join(build, 'dist', "%s.tar.gz" % pkg_version)
470     platform_tar_gz = os.path.join(build,
471                                    'dist',
472                                    "%s.%s.tar.gz" % (pkg_version, platform))
473     zip = os.path.join(build, 'dist', "%s.zip" % pkg_version)
474     platform_zip = os.path.join(build,
475                                 'dist',
476                                 "%s.%s.zip" % (pkg_version, platform))
477     win32_exe = os.path.join(build, 'dist', "%s.win32.exe" % pkg_version)
478
479     #
480     # Update the environment with the relevant information
481     # for this package.
482     #
483     # We can get away with calling setup.py using a directory path
484     # like this because we put a preamble in it that will chdir()
485     # to the directory in which setup.py exists.
486     #
487     setup_py = os.path.join(build, 'setup.py')
488     env.Replace(PKG = pkg,
489                 PKG_VERSION = pkg_version,
490                 SETUP_PY = setup_py)
491     Local(setup_py)
492
493     #
494     # Read up the list of source files from our MANIFEST.in.
495     # This list should *not* include LICENSE.txt, MANIFEST,
496     # README.txt, or setup.py.  Make a copy of the list for the
497     # destination files.
498     #
499     manifest_in = File(os.path.join(src, 'MANIFEST.in')).rstr()
500     src_files = map(lambda x: x[:-1],
501                     open(manifest_in).readlines())
502     raw_files = src_files[:]
503     dst_files = src_files[:]
504     rpm_files = []
505
506     MANIFEST_in_list = []
507
508     if p.has_key('subpkgs'):
509         #
510         # This package includes some sub-packages.  Read up their
511         # MANIFEST.in files, and add them to our source and destination
512         # file lists, modifying them as appropriate to add the
513         # specified subdirs.
514         #
515         for sp in p['subpkgs']:
516             ssubdir = sp['src_subdir']
517             isubdir = p['subinst_dirs'][sp['pkg']]
518             MANIFEST_in = File(os.path.join(src, ssubdir, 'MANIFEST.in')).rstr()
519             MANIFEST_in_list.append(MANIFEST_in)
520             files = map(lambda x: x[:-1], open(MANIFEST_in).readlines())
521             raw_files.extend(files)
522             src_files.extend(map(lambda x, s=ssubdir: os.path.join(s, x), files))
523             for f in files:
524                 r = os.path.join(sp['rpm_dir'], f)
525                 rpm_files.append(r)
526                 if f[-3:] == ".py":
527                     rpm_files.append(r + 'c')
528             files = map(lambda x, i=isubdir: os.path.join(i, x), files)
529             dst_files.extend(files)
530             for k, f in sp['filemap'].items():
531                 if f:
532                     k = os.path.join(ssubdir, k)
533                     p['filemap'][k] = os.path.join(ssubdir, f)
534             for f, deps in sp['explicit_deps'].items():
535                 f = os.path.join(build, ssubdir, f)
536                 env.Depends(f, deps)
537
538     #
539     # Now that we have the "normal" source files, add those files
540     # that are standard for each distribution.  Note that we don't
541     # add these to dst_files, because they don't get installed.
542     # And we still have the MANIFEST to add.
543     #
544     src_files.extend(p['files'])
545
546     #
547     # Now run everything in src_file through the sed command we
548     # concocted to expand __FILE__, __VERSION__, etc.
549     #
550     for b in src_files:
551         s = p['filemap'].get(b, b)
552         env.SCons_revision(os.path.join(build, b), os.path.join(src, s))
553
554     #
555     # NOW, finally, we can create the MANIFEST, which we do
556     # by having Python spit out the contents of the src_files
557     # array we've carefully created.  After we've added
558     # MANIFEST itself to the array, of course.
559     #
560     src_files.append("MANIFEST")
561     MANIFEST_in_list.append(os.path.join(src, 'MANIFEST.in'))
562
563     def write_src_files(target, source, **kw):
564         global src_files
565         src_files.sort()
566         f = open(str(target[0]), 'wb')
567         for file in src_files:
568             f.write(file + "\n")
569         f.close()
570         return 0
571     env.Command(os.path.join(build, 'MANIFEST'),
572                 MANIFEST_in_list,
573                 write_src_files)
574
575     #
576     # Now go through and arrange to create whatever packages we can.
577     #
578     build_src_files = map(lambda x, b=build: os.path.join(b, x), src_files)
579     apply(Local, build_src_files, {})
580
581     distutils_formats = []
582
583     distutils_targets = [ win32_exe ]
584
585     install_targets = distutils_targets[:]
586
587     if gzip:
588
589         distutils_formats.append('gztar')
590
591         src_deps.append(tar_gz)
592
593         distutils_targets.extend([ tar_gz, platform_tar_gz ])
594         install_targets.extend([ tar_gz, platform_tar_gz ])
595
596         #
597         # Unpack the tar.gz archive created by the distutils into
598         # build/unpack-tar-gz/scons-{version}.
599         #
600         # We'd like to replace the last three lines with the following:
601         #
602         #       tar zxf $SOURCES -C $UNPACK_TAR_GZ_DIR
603         #
604         # but that gives heartburn to Cygwin's tar, so work around it
605         # with separate zcat-tar-rm commands.
606         #
607         unpack_tar_gz_files = map(lambda x, u=unpack_tar_gz_dir, pv=pkg_version:
608                                          os.path.join(u, pv, x),
609                                   src_files)
610         env.Command(unpack_tar_gz_files, tar_gz, [
611                     Delete(os.path.join(unpack_tar_gz_dir, pkg_version)),
612                     "$ZCAT $SOURCES > .temp",
613                     "tar xf .temp -C $UNPACK_TAR_GZ_DIR",
614                     Delete(".temp"),
615         ])
616
617         #
618         # Run setup.py in the unpacked subdirectory to "install" everything
619         # into our build/test subdirectory.  The runtest.py script will set
620         # PYTHONPATH so that the tests only look under build/test-{package},
621         # and under etc (for the testing modules TestCmd.py, TestSCons.py,
622         # and unittest.py).  This makes sure that our tests pass with what
623         # we really packaged, not because of something hanging around in
624         # the development directory.
625         #
626         # We can get away with calling setup.py using a directory path
627         # like this because we put a preamble in it that will chdir()
628         # to the directory in which setup.py exists.
629         #
630         dfiles = map(lambda x, d=test_tar_gz_dir: os.path.join(d, x), dst_files)
631         env.Command(dfiles, unpack_tar_gz_files, [
632             Delete(os.path.join(unpack_tar_gz_dir, pkg_version, 'build')),
633             Delete("$TEST_TAR_GZ_DIR"),
634             '$PYTHON "%s" install "--prefix=$TEST_TAR_GZ_DIR"' % \
635                 os.path.join(unpack_tar_gz_dir, pkg_version, 'setup.py'),
636         ])
637
638         #
639         # Generate portage files for submission to Gentoo Linux.
640         #
641         gentoo = os.path.join('build', 'gentoo')
642         ebuild = os.path.join(gentoo, 'scons-%s.ebuild' % version)
643         digest = os.path.join(gentoo, 'files', 'digest-scons-%s' % version)
644         env.Command(ebuild, os.path.join('gentoo', 'scons.ebuild.in'), SCons_revision)
645         def Digestify(target, source, env):
646             import md5
647             def hexdigest(s):
648                 """Return a signature as a string of hex characters.
649                 """
650                 # NOTE:  This routine is a method in the Python 2.0 interface
651                 # of the native md5 module, but we want SCons to operate all
652                 # the way back to at least Python 1.5.2, which doesn't have it.
653                 h = string.hexdigits
654                 r = ''
655                 for c in s:
656                     i = ord(c)
657                     r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
658                 return r
659             src = source[0].rfile()
660             contents = open(str(src)).read()
661             sig = hexdigest(md5.new(contents).digest())
662             bytes = os.stat(str(src))[6]
663             open(str(target[0]), 'w').write("MD5 %s %s %d\n" % (sig,
664                                                                 src.name,
665                                                                 bytes))
666         env.Command(digest, tar_gz, Digestify)
667
668     if zipit:
669
670         distutils_formats.append('zip')
671
672         src_deps.append(zip)
673
674         distutils_targets.extend([ zip, platform_zip ])
675         install_targets.extend([ zip, platform_zip ])
676
677         #
678         # Unpack the zip archive created by the distutils into
679         # build/unpack-zip/scons-{version}.
680         #
681         unpack_zip_files = map(lambda x, u=unpack_zip_dir, pv=pkg_version:
682                                       os.path.join(u, pv, x),
683                                src_files)
684
685         env.Command(unpack_zip_files, zip, [
686             Delete(os.path.join(unpack_zip_dir, pkg_version)),
687             unzipit,
688         ])
689
690         #
691         # Run setup.py in the unpacked subdirectory to "install" everything
692         # into our build/test subdirectory.  The runtest.py script will set
693         # PYTHONPATH so that the tests only look under build/test-{package},
694         # and under etc (for the testing modules TestCmd.py, TestSCons.py,
695         # and unittest.py).  This makes sure that our tests pass with what
696         # we really packaged, not because of something hanging around in
697         # the development directory.
698         #
699         # We can get away with calling setup.py using a directory path
700         # like this because we put a preamble in it that will chdir()
701         # to the directory in which setup.py exists.
702         #
703         dfiles = map(lambda x, d=test_zip_dir: os.path.join(d, x), dst_files)
704         env.Command(dfiles, unpack_zip_files, [
705             Delete(os.path.join(unpack_zip_dir, pkg_version, 'build')),
706             Delete("$TEST_ZIP_DIR"),
707             '$PYTHON "%s" install "--prefix=$TEST_ZIP_DIR"' % \
708                 os.path.join(unpack_zip_dir, pkg_version, 'setup.py'),
709         ])
710
711     if rpmbuild:
712         topdir = os.path.join(os.getcwd(), build, 'build',
713                               'bdist.' + platform, 'rpm')
714
715         BUILDdir = os.path.join(topdir, 'BUILD', pkg + '-' + version)
716         RPMSdir = os.path.join(topdir, 'RPMS', 'noarch')
717         SOURCESdir = os.path.join(topdir, 'SOURCES')
718         SPECSdir = os.path.join(topdir, 'SPECS')
719         SRPMSdir = os.path.join(topdir, 'SRPMS')
720
721         specfile_in = os.path.join('rpm', "%s.spec.in" % pkg)
722         specfile = os.path.join(SPECSdir, "%s-1.spec" % pkg_version)
723         sourcefile = os.path.join(SOURCESdir, "%s.tar.gz" % pkg_version);
724         noarch_rpm = os.path.join(RPMSdir, "%s-1.noarch.rpm" % pkg_version)
725         src_rpm = os.path.join(SRPMSdir, "%s-1.src.rpm" % pkg_version)
726
727         def spec_function(target, source, env):
728             """Generate the RPM .spec file from the template file.
729
730             This fills in the %files portion of the .spec file with a
731             list generated from our MANIFEST(s), so we don't have to
732             maintain multiple lists.
733             """
734             c = open(str(source[0]), 'rb').read()
735             c = string.replace(c, '__RPM_FILES__', env['RPM_FILES'])
736             open(str(target[0]), 'wb').write(c)
737
738         rpm_files.sort()
739         rpm_files_str = string.join(rpm_files, "\n") + "\n"
740         rpm_spec_env = env.Copy(RPM_FILES = rpm_files_str)
741         rpm_spec_action = Action(spec_function, varlist=['RPM_FILES'])
742         rpm_spec_env.Command(specfile, specfile_in, rpm_spec_action)
743
744         env.InstallAs(sourcefile, tar_gz)
745         Local(sourcefile)
746
747         targets = [ noarch_rpm, src_rpm ]
748         cmd = "$RPMBUILD --define '_topdir $(%s$)' -ba $SOURCES" % topdir
749         if not os.path.isdir(BUILDdir):
750             cmd = ("$( mkdir -p %s; $)" % BUILDdir) + cmd
751         env.Command(targets, specfile, cmd)
752         env.Depends(targets, sourcefile)
753
754         install_targets.extend(targets)
755
756         dfiles = map(lambda x, d=test_rpm_dir: os.path.join(d, 'usr', x),
757                      dst_files)
758         env.Command(dfiles,
759                     noarch_rpm,
760                     "$RPM2CPIO $SOURCES | (cd $TEST_RPM_DIR && cpio -id)")
761
762     if dh_builddeb and fakeroot:
763         # Our Debian packaging builds directly into build/dist,
764         # so we don't need to add the .debs to install_targets.
765         deb = os.path.join('build', 'dist', "%s_%s-1_all.deb" % (pkg, version))
766         for d in p['debian_deps']:
767             b = env.SCons_revision(os.path.join(build, d), d)
768             env.Depends(deb, b)
769             Local(b)
770         env.Command(deb, build_src_files, [
771             "cd %s && fakeroot make -f debian/rules PYTHON=$PYTHON BUILDDEB_OPTIONS=--destdir=../../build/dist binary" % build,
772                     ])
773
774         old = os.path.join('lib', 'scons', '')
775         new = os.path.join('lib', 'python2.2', 'site-packages', '')
776         def xxx(s, old=old, new=new):
777             if s[:len(old)] == old:
778                 s = new + s[len(old):]
779             return os.path.join('usr', s)
780         dfiles = map(lambda x, t=test_deb_dir: os.path.join(t, x),
781                      map(xxx, dst_files))
782         env.Command(dfiles,
783                     deb,
784                     "dpkg --fsys-tarfile $SOURCES | (cd $TEST_DEB_DIR && tar -xf -)")
785
786
787     #
788     # Use the Python distutils to generate the appropriate packages.
789     #
790     commands = [
791         Delete(os.path.join(build, 'build', 'lib')),
792         Delete(os.path.join(build, 'build', 'scripts')),
793     ]
794
795     if distutils_formats:
796         commands.append(Delete(os.path.join(build,
797                                             'build',
798                                             'bdist.' + platform,
799                                             'dumb')))
800         for format in distutils_formats:
801             commands.append("$PYTHON $SETUP_PY bdist_dumb -f %s" % format)
802
803         commands.append("$PYTHON $SETUP_PY sdist --formats=%s" %  \
804                             string.join(distutils_formats, ','))
805
806     commands.append("$PYTHON $SETUP_PY bdist_wininst")
807
808     env.Command(distutils_targets, build_src_files, commands)
809
810     #
811     # Now create local packages for people who want to let people
812     # build their SCons-buildable packages without having to
813     # install SCons.
814     #
815     s_l_v = '%s-local-%s' % (pkg, version)
816
817     local = os.path.join('build', pkg + '-local')
818     cwd_local = os.path.join(os.getcwd(), local)
819     cwd_local_slv = os.path.join(os.getcwd(), local, s_l_v)
820
821     local_tar_gz = os.path.join('build', 'dist', "%s.tar.gz" % s_l_v)
822     local_zip = os.path.join('build', 'dist', "%s.zip" % s_l_v)
823
824     commands = [
825         Delete(local),
826         '$PYTHON $SETUP_PY install "--install-script=%s" "--install-lib=%s" --no-compile' % \
827                                                 (cwd_local, cwd_local_slv),
828     ]
829
830     for script in scripts:
831         #commands.append("mv %s/%s %s/%s.py" % (local, script, local, script))
832         local_script = os.path.join(local, script)
833         commands.append(Move(local_script + '.py', local_script))
834
835     rf = filter(lambda x: not x in scripts, raw_files)
836     rf = map(lambda x, slv=s_l_v: os.path.join(slv, x), rf)
837     for script in scripts:
838         rf.append("%s.py" % script)
839     local_targets = map(lambda x, s=local: os.path.join(s, x), rf)
840
841     env.Command(local_targets, build_src_files, commands)
842
843     scons_LICENSE = os.path.join(local, 'scons-LICENSE')
844     env.SCons_revision(scons_LICENSE, 'LICENSE-local')
845     local_targets.append(scons_LICENSE)
846
847     scons_README = os.path.join(local, 'scons-README')
848     env.SCons_revision(scons_README, 'README-local')
849     local_targets.append(scons_README)
850
851     if gzip:
852         env.Command(local_tar_gz,
853                     local_targets,
854                     "cd %s && tar czf $( ${TARGET.abspath} $) *" % local)
855
856         unpack_targets = map(lambda x, d=test_local_tar_gz_dir:
857                                     os.path.join(d, x),
858                              rf)
859         commands = [Delete(test_local_tar_gz_dir),
860                     Mkdir(test_local_tar_gz_dir),
861                     "cd %s && tar xzf $( ${SOURCE.abspath} $)" % test_local_tar_gz_dir]
862
863         env.Command(unpack_targets, local_tar_gz, commands)
864
865     if zipit:
866         env.Command(local_zip, local_targets, zipit,
867                     CD = local, PSV = '.')
868
869         unpack_targets = map(lambda x, d=test_local_zip_dir:
870                                     os.path.join(d, x),
871                              rf)
872         commands = [Delete(test_local_zip_dir),
873                     Mkdir(test_local_zip_dir),
874                     unzipit]
875
876         env.Command(unpack_targets, local_zip, unzipit,
877                     UNPACK_ZIP_DIR = test_local_zip_dir)
878
879     #
880     # And, lastly, install the appropriate packages in the
881     # appropriate subdirectory.
882     #
883     b_d_files = env.Install(os.path.join('build', 'dist'), install_targets)
884     Local(b_d_files)
885
886 #
887 #
888 #
889 Export('env')
890
891 SConscript('etc/SConscript')
892
893 #
894 # Documentation.
895 #
896 Export('env', 'whereis')
897
898 SConscript('doc/SConscript')
899
900 #
901 # If we're running in the actual Aegis project, pack up a complete
902 # source archive from the project files and files in the change,
903 # so we can share it with helpful developers who don't use Aegis.
904 #
905
906 if change:
907     df = []
908     cmd = "aegis -list -unf -c %s cf 2>/dev/null" % change
909     for line in map(lambda x: x[:-1], os.popen(cmd, "r").readlines()):
910         a = string.split(line)
911         if a[1] == "remove":
912             df.append(a[-1])
913
914     cmd = "aegis -list -terse pf 2>/dev/null"
915     pf = map(lambda x: x[:-1], os.popen(cmd, "r").readlines())
916     cmd = "aegis -list -terse -c %s cf 2>/dev/null" % change
917     cf = map(lambda x: x[:-1], os.popen(cmd, "r").readlines())
918     u = {}
919     for f in pf + cf:
920         u[f] = 1
921     for f in df:
922         try:
923             del u[f]
924         except KeyError:
925             pass
926     sfiles = filter(lambda x: x[-9:] != '.aeignore' and
927                               x[-9:] != '.sconsign' and
928                               x[-10:] != '.cvsignore',
929                     u.keys())
930
931     if sfiles:
932         ps = "%s-src" % project
933         psv = "%s-%s" % (ps, version)
934         b_ps = os.path.join('build', ps)
935         b_psv = os.path.join('build', psv)
936         b_psv_stamp = b_psv + '-stamp'
937
938         src_tar_gz = os.path.join('build', 'dist', '%s.tar.gz' % psv)
939         src_zip = os.path.join('build', 'dist', '%s.zip' % psv)
940
941         Local(src_tar_gz, src_zip)
942
943         for file in sfiles:
944             env.SCons_revision(os.path.join(b_ps, file), file)
945
946         b_ps_files = map(lambda x, d=b_ps: os.path.join(d, x), sfiles)
947         cmds = [
948             Delete(b_psv),
949             Copy(b_psv, b_ps),
950             Touch("$TARGET"),
951         ]
952
953         env.Command(b_psv_stamp, src_deps + b_ps_files, cmds)
954
955         apply(Local, b_ps_files, {})
956
957         if gzip:
958
959             env.Command(src_tar_gz, b_psv_stamp,
960                         "tar cz${TAR_HFLAG} -f $TARGET -C build %s" % psv)
961
962             #
963             # Unpack the archive into build/unpack/scons-{version}.
964             #
965             unpack_tar_gz_files = map(lambda x, u=unpack_tar_gz_dir, psv=psv:
966                                              os.path.join(u, psv, x),
967                                       sfiles)
968
969             #
970             # We'd like to replace the last three lines with the following:
971             #
972             #   tar zxf $SOURCES -C $UNPACK_TAR_GZ_DIR
973             #
974             # but that gives heartburn to Cygwin's tar, so work around it
975             # with separate zcat-tar-rm commands.
976             env.Command(unpack_tar_gz_files, src_tar_gz, [
977                 Delete(os.path.join(unpack_tar_gz_dir, psv)),
978                 "$ZCAT $SOURCES > .temp",
979                 "tar xf .temp -C $UNPACK_TAR_GZ_DIR",
980                 Delete(".temp"),
981             ])
982
983             #
984             # Run setup.py in the unpacked subdirectory to "install" everything
985             # into our build/test subdirectory.  The runtest.py script will set
986             # PYTHONPATH so that the tests only look under build/test-{package},
987             # and under etc (for the testing modules TestCmd.py, TestSCons.py,
988             # and unittest.py).  This makes sure that our tests pass with what
989             # we really packaged, not because of something hanging around in
990             # the development directory.
991             #
992             # We can get away with calling setup.py using a directory path
993             # like this because we put a preamble in it that will chdir()
994             # to the directory in which setup.py exists.
995             #
996             dfiles = map(lambda x, d=test_src_tar_gz_dir: os.path.join(d, x),
997                             dst_files)
998             scons_lib_dir = os.path.join(unpack_tar_gz_dir, psv, 'src', 'engine')
999             ENV = env.Dictionary('ENV').copy()
1000             ENV['SCONS_LIB_DIR'] = scons_lib_dir
1001             ENV['USERNAME'] = developer
1002             env.Command(dfiles, unpack_tar_gz_files,
1003                 [
1004                 Delete(os.path.join(unpack_tar_gz_dir,
1005                                     psv,
1006                                     'build',
1007                                     'scons',
1008                                     'build')),
1009                 Delete("$TEST_SRC_TAR_GZ_DIR"),
1010                 'cd "%s" && $PYTHON "%s" "%s"' % \
1011                     (os.path.join(unpack_tar_gz_dir, psv),
1012                      os.path.join('src', 'script', 'scons.py'),
1013                      os.path.join('build', 'scons')),
1014                 '$PYTHON "%s" install "--prefix=$TEST_SRC_TAR_GZ_DIR"' % \
1015                     os.path.join(unpack_tar_gz_dir,
1016                                  psv,
1017                                  'build',
1018                                  'scons',
1019                                  'setup.py'),
1020                 ],
1021                 ENV = ENV)
1022
1023         if zipit:
1024
1025             env.Command(src_zip, b_psv_stamp, zipit, CD = 'build', PSV = psv)
1026
1027             #
1028             # Unpack the archive into build/unpack/scons-{version}.
1029             #
1030             unpack_zip_files = map(lambda x, u=unpack_zip_dir, psv=psv:
1031                                              os.path.join(u, psv, x),
1032                                       sfiles)
1033
1034             env.Command(unpack_zip_files, src_zip, [
1035                 Delete(os.path.join(unpack_zip_dir, psv)),
1036                 unzipit
1037             ])
1038
1039             #
1040             # Run setup.py in the unpacked subdirectory to "install" everything
1041             # into our build/test subdirectory.  The runtest.py script will set
1042             # PYTHONPATH so that the tests only look under build/test-{package},
1043             # and under etc (for the testing modules TestCmd.py, TestSCons.py,
1044             # and unittest.py).  This makes sure that our tests pass with what
1045             # we really packaged, not because of something hanging around in
1046             # the development directory.
1047             #
1048             # We can get away with calling setup.py using a directory path
1049             # like this because we put a preamble in it that will chdir()
1050             # to the directory in which setup.py exists.
1051             #
1052             dfiles = map(lambda x, d=test_src_zip_dir: os.path.join(d, x),
1053                             dst_files)
1054             scons_lib_dir = os.path.join(unpack_zip_dir, psv, 'src', 'engine')
1055             ENV = env.Dictionary('ENV').copy()
1056             ENV['SCONS_LIB_DIR'] = scons_lib_dir
1057             ENV['USERNAME'] = developer
1058             env.Command(dfiles, unpack_zip_files,
1059                 [
1060                 Delete(os.path.join(unpack_zip_dir,
1061                                     psv,
1062                                     'build',
1063                                     'scons',
1064                                     'build')),
1065                 Delete("$TEST_SRC_ZIP_DIR"),
1066                 'cd "%s" && $PYTHON "%s" "%s"' % \
1067                     (os.path.join(unpack_zip_dir, psv),
1068                      os.path.join('src', 'script', 'scons.py'),
1069                      os.path.join('build', 'scons')),
1070                 '$PYTHON "%s" install "--prefix=$TEST_SRC_ZIP_DIR"' % \
1071                     os.path.join(unpack_zip_dir,
1072                                  psv,
1073                                  'build',
1074                                  'scons',
1075                                  'setup.py'),
1076                 ],
1077                 ENV = ENV)