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